blob: 73cf414b5c1ec96f4cd0f94e735379b8670dcf9e [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chenga8e29892007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengd3d9d662009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng5657c012009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
Evan Chenga8e29892007-01-19 07:51:42 +000027#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Chris Lattner705e07f2009-08-23 03:41:05 +000029#include "llvm/Support/raw_ostream.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc99ef082007-02-09 20:54:44 +000031#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000032#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/Statistic.h"
Jim Grosbach1fc7d712009-11-11 02:47:19 +000034#include "llvm/Support/CommandLine.h"
Bob Wilsonb9239532009-10-15 20:49:47 +000035#include <algorithm>
Evan Chenga8e29892007-01-19 07:51:42 +000036using namespace llvm;
37
Evan Chenga1efbbd2009-08-14 00:32:16 +000038STATISTIC(NumCPEs, "Number of constpool entries");
39STATISTIC(NumSplit, "Number of uncond branches inserted");
40STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42STATISTIC(NumTBs, "Number of table branches generated");
43STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Cheng31b99dd2009-08-14 18:31:44 +000044STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Evan Chengde17fb62009-10-31 23:46:45 +000045STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
Jim Grosbach1fc7d712009-11-11 02:47:19 +000046STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
47
48
49static cl::opt<bool>
50AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(false),
51 cl::desc("Adjust basic block layout to better use TB[BH]"));
Evan Chenga8e29892007-01-19 07:51:42 +000052
53namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000054 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000055 /// requires constant pool entries to be scattered among the instructions
56 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000057 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000058 /// special instructions.
59 ///
60 /// The terminology used in this pass includes:
61 /// Islands - Clumps of constants placed in the function.
62 /// Water - Potential places where an island could be formed.
63 /// CPE - A constant pool entry that has been placed somewhere, which
64 /// tracks a list of users.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000065 class ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000066 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000067 /// by MBB Number. The two-byte pads required for Thumb alignment are
68 /// counted as part of the following block (i.e., the offset and size for
69 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000070 std::vector<unsigned> BBSizes;
Bob Wilson84945262009-05-12 17:09:30 +000071
Dale Johannesen99c49a42007-02-25 00:47:03 +000072 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000073 /// The two-byte pads required for Thumb alignment are counted as part of
74 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000075 std::vector<unsigned> BBOffsets;
76
Evan Chenga8e29892007-01-19 07:51:42 +000077 /// WaterList - A sorted list of basic blocks where islands could be placed
78 /// (i.e. blocks that don't fall through to the following block, due
79 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000080 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000081
Bob Wilsonb9239532009-10-15 20:49:47 +000082 /// NewWaterList - The subset of WaterList that was created since the
83 /// previous iteration by inserting unconditional branches.
84 SmallSet<MachineBasicBlock*, 4> NewWaterList;
85
Bob Wilson034de5f2009-10-12 18:52:13 +000086 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
87
Evan Chenga8e29892007-01-19 07:51:42 +000088 /// CPUser - One user of a constant pool, keeping the machine instruction
89 /// pointer, the constant pool being referenced, and the max displacement
Bob Wilson549dda92009-10-15 05:52:29 +000090 /// allowed from the instruction to the CP. The HighWaterMark records the
91 /// highest basic block where a new CPEntry can be placed. To ensure this
92 /// pass terminates, the CP entries are initially placed at the end of the
93 /// function and then move monotonically to lower addresses. The
94 /// exception to this rule is when the current CP entry for a particular
95 /// CPUser is out of range, but there is another CP entry for the same
96 /// constant value in range. We want to use the existing in-range CP
97 /// entry, but if it later moves out of range, the search for new water
98 /// should resume where it left off. The HighWaterMark is used to record
99 /// that point.
Evan Chenga8e29892007-01-19 07:51:42 +0000100 struct CPUser {
101 MachineInstr *MI;
102 MachineInstr *CPEMI;
Bob Wilson549dda92009-10-15 05:52:29 +0000103 MachineBasicBlock *HighWaterMark;
Evan Chenga8e29892007-01-19 07:51:42 +0000104 unsigned MaxDisp;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000105 bool NegOk;
Evan Chengd3d9d662009-07-23 18:27:47 +0000106 bool IsSoImm;
107 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
108 bool neg, bool soimm)
Bob Wilson549dda92009-10-15 05:52:29 +0000109 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
110 HighWaterMark = CPEMI->getParent();
111 }
Evan Chenga8e29892007-01-19 07:51:42 +0000112 };
Bob Wilson84945262009-05-12 17:09:30 +0000113
Evan Chenga8e29892007-01-19 07:51:42 +0000114 /// CPUsers - Keep track of all of the machine instructions that use various
115 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +0000116 std::vector<CPUser> CPUsers;
Bob Wilson84945262009-05-12 17:09:30 +0000117
Evan Chengc99ef082007-02-09 20:54:44 +0000118 /// CPEntry - One per constant pool entry, keeping the machine instruction
119 /// pointer, the constpool index, and the number of CPUser's which
120 /// reference this entry.
121 struct CPEntry {
122 MachineInstr *CPEMI;
123 unsigned CPI;
124 unsigned RefCount;
125 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
126 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
127 };
128
129 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000130 /// instructions. For each original constpool index (i.e. those that
131 /// existed upon entry to this pass), it keeps a vector of entries.
132 /// Original elements are cloned as we go along; the clones are
133 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +0000134 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilson84945262009-05-12 17:09:30 +0000135
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000136 /// ImmBranch - One per immediate branch, keeping the machine instruction
137 /// pointer, conditional or unconditional, the max displacement,
138 /// and (if isCond is true) the corresponding unconditional branch
139 /// opcode.
140 struct ImmBranch {
141 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000142 unsigned MaxDisp : 31;
143 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000144 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000145 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
146 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000147 };
148
Evan Cheng2706f972007-05-16 05:14:06 +0000149 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000150 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000151 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000152
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000153 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
154 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000155 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000156
Evan Cheng5657c012009-07-29 02:18:14 +0000157 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
158 SmallVector<MachineInstr*, 4> T2JumpTables;
159
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000160 /// HasFarJump - True if any far jump instruction has been emitted during
161 /// the branch fix up pass.
162 bool HasFarJump;
163
Evan Chenga8e29892007-01-19 07:51:42 +0000164 const TargetInstrInfo *TII;
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000165 const ARMSubtarget *STI;
Dale Johannesen8593e412007-04-29 19:19:30 +0000166 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000167 bool isThumb;
Evan Chengd3d9d662009-07-23 18:27:47 +0000168 bool isThumb1;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000169 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000170 public:
Devang Patel19974732007-05-03 01:11:54 +0000171 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000172 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000173
Evan Cheng5657c012009-07-29 02:18:14 +0000174 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000175
176 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000177 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000178 }
Bob Wilson84945262009-05-12 17:09:30 +0000179
Evan Chenga8e29892007-01-19 07:51:42 +0000180 private:
Evan Cheng5657c012009-07-29 02:18:14 +0000181 void DoInitialPlacement(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000182 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000183 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng5657c012009-07-29 02:18:14 +0000184 void InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000185 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000186 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000187 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000188 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000189 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000190 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonb9239532009-10-15 20:49:47 +0000191 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000192 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
Bob Wilson757652c2009-10-12 21:39:43 +0000193 MachineBasicBlock *&NewMBB);
Evan Cheng5657c012009-07-29 02:18:14 +0000194 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000195 void RemoveDeadCPEMI(MachineInstr *CPEMI);
196 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000197 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000198 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
199 bool DoDump = false);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000200 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000201 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000202 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000203 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Evan Chengc0dbec72007-01-31 19:57:44 +0000204 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng5657c012009-07-29 02:18:14 +0000205 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
206 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
207 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000208 bool UndoLRSpillRestore();
Evan Chenga1efbbd2009-08-14 00:32:16 +0000209 bool OptimizeThumb2Instructions(MachineFunction &MF);
210 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng5657c012009-07-29 02:18:14 +0000211 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Jim Grosbach1fc7d712009-11-11 02:47:19 +0000212 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
213 MachineBasicBlock *JTBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000214
Evan Chenga8e29892007-01-19 07:51:42 +0000215 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000216 void dumpBBs();
Evan Cheng5657c012009-07-29 02:18:14 +0000217 void verify(MachineFunction &MF);
Evan Chenga8e29892007-01-19 07:51:42 +0000218 };
Devang Patel19974732007-05-03 01:11:54 +0000219 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000220}
221
Dale Johannesen8593e412007-04-29 19:19:30 +0000222/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng5657c012009-07-29 02:18:14 +0000223void ARMConstantIslands::verify(MachineFunction &MF) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000224 assert(BBOffsets.size() == BBSizes.size());
225 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
226 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengd3d9d662009-07-23 18:27:47 +0000227 if (!isThumb)
228 return;
229#ifndef NDEBUG
Evan Cheng5657c012009-07-29 02:18:14 +0000230 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengd3d9d662009-07-23 18:27:47 +0000231 MBBI != E; ++MBBI) {
232 MachineBasicBlock *MBB = MBBI;
233 if (!MBB->empty() &&
234 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
235 unsigned MBBId = MBB->getNumber();
236 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
237 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dale Johannesen8593e412007-04-29 19:19:30 +0000238 }
239 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000240#endif
Dale Johannesen8593e412007-04-29 19:19:30 +0000241}
242
243/// print block size and offset information - debugging
244void ARMConstantIslands::dumpBBs() {
245 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000246 DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
247 << " size " << BBSizes[J] << "\n");
Dale Johannesen8593e412007-04-29 19:19:30 +0000248 }
249}
250
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000251/// createARMConstantIslandPass - returns an instance of the constpool
252/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000253FunctionPass *llvm::createARMConstantIslandPass() {
254 return new ARMConstantIslands();
255}
256
Evan Cheng5657c012009-07-29 02:18:14 +0000257bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
258 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000259
Evan Cheng5657c012009-07-29 02:18:14 +0000260 TII = MF.getTarget().getInstrInfo();
261 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000262 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
263
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000264 isThumb = AFI->isThumbFunction();
Evan Chengd3d9d662009-07-23 18:27:47 +0000265 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000266 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000267
268 HasFarJump = false;
269
Evan Chenga8e29892007-01-19 07:51:42 +0000270 // Renumber all of the machine basic blocks in the function, guaranteeing that
271 // the numbers agree with the position of the block in the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000272 MF.RenumberBlocks();
Evan Chenga8e29892007-01-19 07:51:42 +0000273
Evan Chengd26b14c2009-07-31 18:28:05 +0000274 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengd3d9d662009-07-23 18:27:47 +0000275 // This is so we can keep exact track of where the alignment padding goes.
276
Evan Chengd26b14c2009-07-31 18:28:05 +0000277 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengd3d9d662009-07-23 18:27:47 +0000278 // aligned.
279 AFI->setAlign(isThumb1 ? 1U : 2U);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000280
Evan Chenga8e29892007-01-19 07:51:42 +0000281 // Perform the initial placement of the constant pool entries. To start with,
282 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000283 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000284 if (!MCP.isEmpty()) {
Evan Cheng5657c012009-07-29 02:18:14 +0000285 DoInitialPlacement(MF, CPEMIs);
Evan Chengd3d9d662009-07-23 18:27:47 +0000286 if (isThumb1)
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000287 AFI->setAlign(2U);
288 }
Bob Wilson84945262009-05-12 17:09:30 +0000289
Evan Chenga8e29892007-01-19 07:51:42 +0000290 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000291 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000292
Evan Chenga8e29892007-01-19 07:51:42 +0000293 // Do the initial scan of the function, building up information about the
294 // sizes of each block, the location of all the water, and finding all of the
295 // constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000296 InitialFunctionScan(MF, CPEMIs);
Jim Grosbachf4997e82009-11-11 19:04:24 +0000297
298 bool MadeChange = false;
299 if (isThumb2)
300 MadeChange |= OptimizeThumb2JumpTables(MF);
301
Evan Chenga8e29892007-01-19 07:51:42 +0000302 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000303
Evan Chenged884f32007-04-03 23:39:48 +0000304 /// Remove dead constant pool entries.
305 RemoveUnusedCPEntries();
306
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000307 // Iteratively place constant pool entries and fix up branches until there
308 // is no change.
Evan Chengb6879b22009-08-07 07:35:21 +0000309 unsigned NoCPIters = 0, NoBRIters = 0;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000310 while (true) {
Evan Chengb6879b22009-08-07 07:35:21 +0000311 bool CPChange = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000312 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000313 CPChange |= HandleConstantPoolUser(MF, i);
314 if (CPChange && ++NoCPIters > 30)
315 llvm_unreachable("Constant Island pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000316 DEBUG(dumpBBs());
Bob Wilsonb9239532009-10-15 20:49:47 +0000317
318 // Clear NewWaterList now. If we split a block for branches, it should
319 // appear as "new water" for the next iteration of constant pool placement.
320 NewWaterList.clear();
Evan Chengb6879b22009-08-07 07:35:21 +0000321
322 bool BRChange = false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000323 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengb6879b22009-08-07 07:35:21 +0000324 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
325 if (BRChange && ++NoBRIters > 30)
326 llvm_unreachable("Branch Fix Up pass failed to converge!");
Evan Cheng82020102007-07-10 22:00:16 +0000327 DEBUG(dumpBBs());
Evan Chengb6879b22009-08-07 07:35:21 +0000328
329 if (!CPChange && !BRChange)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000330 break;
331 MadeChange = true;
332 }
Evan Chenged884f32007-04-03 23:39:48 +0000333
Evan Chenga1efbbd2009-08-14 00:32:16 +0000334 // Shrink 32-bit Thumb2 branch, load, and store instructions.
335 if (isThumb2)
336 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000337
Dale Johannesen8593e412007-04-29 19:19:30 +0000338 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng5657c012009-07-29 02:18:14 +0000339 verify(MF);
Dale Johannesen8593e412007-04-29 19:19:30 +0000340
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000341 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
342 // Undo the spill / restore of LR if possible.
Evan Cheng5657c012009-07-29 02:18:14 +0000343 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000344 MadeChange |= UndoLRSpillRestore();
345
Evan Chenga8e29892007-01-19 07:51:42 +0000346 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000347 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000348 WaterList.clear();
349 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000350 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000351 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000352 PushPopMIs.clear();
Evan Cheng5657c012009-07-29 02:18:14 +0000353 T2JumpTables.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000354
355 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000356}
357
358/// DoInitialPlacement - Perform the initial placement of the constant pool
359/// entries. To start with, we put them all at the end of the function.
Evan Cheng5657c012009-07-29 02:18:14 +0000360void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +0000361 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000362 // Create the basic block to hold the CPE's.
Evan Cheng5657c012009-07-29 02:18:14 +0000363 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
364 MF.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000365
Evan Chenga8e29892007-01-19 07:51:42 +0000366 // Add all of the constants from the constant pool to the end block, use an
367 // identity mapping of CPI's to CPE's.
368 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng5657c012009-07-29 02:18:14 +0000369 MF.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000370
Evan Cheng5657c012009-07-29 02:18:14 +0000371 const TargetData &TD = *MF.getTarget().getTargetData();
Evan Chenga8e29892007-01-19 07:51:42 +0000372 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000373 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000374 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
375 // we would have to pad them out or something so that instructions stay
376 // aligned.
377 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
378 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000379 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000380 .addImm(i).addConstantPoolIndex(i).addImm(Size);
381 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000382
383 // Add a new CPEntry, but no corresponding CPUser yet.
384 std::vector<CPEntry> CPEs;
385 CPEs.push_back(CPEntry(CPEMI, i));
386 CPEntries.push_back(CPEs);
387 NumCPEs++;
Chris Lattner893e1c92009-08-23 06:49:22 +0000388 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
389 << "\n");
Evan Chenga8e29892007-01-19 07:51:42 +0000390 }
391}
392
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000393/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000394/// into the block immediately after it.
395static bool BBHasFallthrough(MachineBasicBlock *MBB) {
396 // Get the next machine basic block in the function.
397 MachineFunction::iterator MBBI = MBB;
398 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
399 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000400
Evan Chenga8e29892007-01-19 07:51:42 +0000401 MachineBasicBlock *NextBB = next(MBBI);
402 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
403 E = MBB->succ_end(); I != E; ++I)
404 if (*I == NextBB)
405 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000406
Evan Chenga8e29892007-01-19 07:51:42 +0000407 return false;
408}
409
Evan Chengc99ef082007-02-09 20:54:44 +0000410/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
411/// look up the corresponding CPEntry.
412ARMConstantIslands::CPEntry
413*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
414 const MachineInstr *CPEMI) {
415 std::vector<CPEntry> &CPEs = CPEntries[CPI];
416 // Number of entries per constpool index should be small, just do a
417 // linear search.
418 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
419 if (CPEs[i].CPEMI == CPEMI)
420 return &CPEs[i];
421 }
422 return NULL;
423}
424
Evan Chenga8e29892007-01-19 07:51:42 +0000425/// InitialFunctionScan - Do the initial scan of the function, building up
426/// information about the sizes of each block, the location of all the water,
427/// and finding all of the constant pool users.
Evan Cheng5657c012009-07-29 02:18:14 +0000428void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Evan Chenge03cff62007-02-09 23:59:14 +0000429 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000430 unsigned Offset = 0;
Evan Cheng5657c012009-07-29 02:18:14 +0000431 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chenga8e29892007-01-19 07:51:42 +0000432 MBBI != E; ++MBBI) {
433 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000434
Evan Chenga8e29892007-01-19 07:51:42 +0000435 // If this block doesn't fall through into the next MBB, then this is
436 // 'water' that a constant pool island could be placed.
437 if (!BBHasFallthrough(&MBB))
438 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000439
Evan Chenga8e29892007-01-19 07:51:42 +0000440 unsigned MBBSize = 0;
441 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
442 I != E; ++I) {
443 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000444 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000445
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000446 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000447 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000448 bool isCond = false;
449 unsigned Bits = 0;
450 unsigned Scale = 1;
451 int UOpc = Opc;
452 switch (Opc) {
Evan Cheng5657c012009-07-29 02:18:14 +0000453 default:
454 continue; // Ignore other JT branches
Dale Johannesen8593e412007-04-29 19:19:30 +0000455 case ARM::tBR_JTr:
Evan Cheng66ac5312009-07-25 00:33:29 +0000456 // A Thumb1 table jump may involve padding; for the offsets to
Dale Johannesen8593e412007-04-29 19:19:30 +0000457 // be right, functions containing these must be 4-byte aligned.
458 AFI->setAlign(2U);
459 if ((Offset+MBBSize)%4 != 0)
Evan Cheng5657c012009-07-29 02:18:14 +0000460 // FIXME: Add a pseudo ALIGN instruction instead.
Dale Johannesen8593e412007-04-29 19:19:30 +0000461 MBBSize += 2; // padding
462 continue; // Does not get an entry in ImmBranches
Evan Cheng5657c012009-07-29 02:18:14 +0000463 case ARM::t2BR_JT:
464 T2JumpTables.push_back(I);
465 continue; // Does not get an entry in ImmBranches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000466 case ARM::Bcc:
467 isCond = true;
468 UOpc = ARM::B;
469 // Fallthrough
470 case ARM::B:
471 Bits = 24;
472 Scale = 4;
473 break;
474 case ARM::tBcc:
475 isCond = true;
476 UOpc = ARM::tB;
477 Bits = 8;
478 Scale = 2;
479 break;
480 case ARM::tB:
481 Bits = 11;
482 Scale = 2;
483 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000484 case ARM::t2Bcc:
485 isCond = true;
486 UOpc = ARM::t2B;
487 Bits = 20;
488 Scale = 2;
489 break;
490 case ARM::t2B:
491 Bits = 24;
492 Scale = 2;
493 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000494 }
Evan Chengb43216e2007-02-01 10:16:15 +0000495
496 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000497 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000498 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000499 }
500
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000501 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
502 PushPopMIs.push_back(I);
503
Evan Chengd3d9d662009-07-23 18:27:47 +0000504 if (Opc == ARM::CONSTPOOL_ENTRY)
505 continue;
506
Evan Chenga8e29892007-01-19 07:51:42 +0000507 // Scan the instructions for constant pool operands.
508 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000509 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000510 // We found one. The addressing mode tells us the max displacement
511 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000512
Evan Chenga8e29892007-01-19 07:51:42 +0000513 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000514 unsigned Bits = 0;
515 unsigned Scale = 1;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000516 bool NegOk = false;
Evan Chengd3d9d662009-07-23 18:27:47 +0000517 bool IsSoImm = false;
518
519 switch (Opc) {
Bob Wilson84945262009-05-12 17:09:30 +0000520 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000521 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengd3d9d662009-07-23 18:27:47 +0000522 break;
523
524 // Taking the address of a CP entry.
525 case ARM::LEApcrel:
526 // This takes a SoImm, which is 8 bit immediate rotated. We'll
527 // pretend the maximum offset is 255 * 4. Since each instruction
528 // 4 byte wide, this is always correct. We'llc heck for other
529 // displacements that fits in a SoImm as well.
Evan Chengb43216e2007-02-01 10:16:15 +0000530 Bits = 8;
Evan Chengd3d9d662009-07-23 18:27:47 +0000531 Scale = 4;
532 NegOk = true;
533 IsSoImm = true;
534 break;
535 case ARM::t2LEApcrel:
536 Bits = 12;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000537 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000538 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000539 case ARM::tLEApcrel:
540 Bits = 8;
541 Scale = 4;
542 break;
543
544 case ARM::LDR:
545 case ARM::LDRcp:
546 case ARM::t2LDRpci:
Evan Cheng556f33c2007-02-01 20:44:52 +0000547 Bits = 12; // +-offset_12
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000548 NegOk = true;
Evan Chenga8e29892007-01-19 07:51:42 +0000549 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000550
551 case ARM::tLDRpci:
552 case ARM::tLDRcp:
Evan Chengb43216e2007-02-01 10:16:15 +0000553 Bits = 8;
554 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000555 break;
Evan Chengd3d9d662009-07-23 18:27:47 +0000556
Jim Grosbache5165492009-11-09 00:11:35 +0000557 case ARM::VLDRD:
558 case ARM::VLDRS:
Evan Chengd3d9d662009-07-23 18:27:47 +0000559 Bits = 8;
560 Scale = 4; // +-(offset_8*4)
561 NegOk = true;
Evan Cheng055b0312009-06-29 07:51:04 +0000562 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000563 }
Evan Chengb43216e2007-02-01 10:16:15 +0000564
Evan Chenga8e29892007-01-19 07:51:42 +0000565 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000566 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000567 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng31b99dd2009-08-14 18:31:44 +0000568 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengd3d9d662009-07-23 18:27:47 +0000569 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Evan Chengc99ef082007-02-09 20:54:44 +0000570
571 // Increment corresponding CPEntry reference count.
572 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
573 assert(CPE && "Cannot find a corresponding CPEntry!");
574 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000575
Evan Chenga8e29892007-01-19 07:51:42 +0000576 // Instructions can only use one CP entry, don't bother scanning the
577 // rest of the operands.
578 break;
579 }
580 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000581
Dale Johannesen8593e412007-04-29 19:19:30 +0000582 // In thumb mode, if this block is a constpool island, we may need padding
583 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000584 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000585 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000586 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
587 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000588 MBBSize += 2;
589
Evan Chenga8e29892007-01-19 07:51:42 +0000590 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000591 BBOffsets.push_back(Offset);
592 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000593 }
594}
595
Evan Chenga8e29892007-01-19 07:51:42 +0000596/// GetOffsetOf - Return the current offset of the specified machine instruction
597/// from the start of the function. This offset changes as stuff is moved
598/// around inside the function.
599unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
600 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000601
Evan Chenga8e29892007-01-19 07:51:42 +0000602 // The offset is composed of two things: the sum of the sizes of all MBB's
603 // before this instruction's block, and the offset from the start of the block
604 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000605 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000606
Dale Johannesen8593e412007-04-29 19:19:30 +0000607 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
608 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000609 if (isThumb &&
610 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000611 Offset%4 != 0)
612 Offset += 2;
613
Evan Chenga8e29892007-01-19 07:51:42 +0000614 // Sum instructions before MI in MBB.
615 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
616 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
617 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000618 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000619 }
620}
621
622/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
623/// ID.
624static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
625 const MachineBasicBlock *RHS) {
626 return LHS->getNumber() < RHS->getNumber();
627}
628
629/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
630/// machine function, it upsets all of the block numbers. Renumber the blocks
631/// and update the arrays that parallel this numbering.
632void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
633 // Renumber the MBB's to keep them consequtive.
634 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000635
Evan Chenga8e29892007-01-19 07:51:42 +0000636 // Insert a size into BBSizes to align it properly with the (newly
637 // renumbered) block numbers.
638 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000639
640 // Likewise for BBOffsets.
641 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000642
643 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000644 // available water after it.
Bob Wilson034de5f2009-10-12 18:52:13 +0000645 water_iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000646 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
647 CompareMBBNumbers);
648 WaterList.insert(IP, NewBB);
649}
650
651
652/// Split the basic block containing MI into two blocks, which are joined by
Bob Wilsonb9239532009-10-15 20:49:47 +0000653/// an unconditional branch. Update data structures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000654/// account for this change and returns the newly created block.
655MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000656 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000657 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000658
659 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000660 MachineBasicBlock *NewBB =
661 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000662 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000663 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000664
Evan Chenga8e29892007-01-19 07:51:42 +0000665 // Splice the instructions starting with MI over to NewBB.
666 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000667
Evan Chenga8e29892007-01-19 07:51:42 +0000668 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000669 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000670 // There doesn't seem to be meaningful DebugInfo available; this doesn't
671 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000672 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
673 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000674 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000675
Evan Chenga8e29892007-01-19 07:51:42 +0000676 // Update the CFG. All succs of OrigBB are now succs of NewBB.
677 while (!OrigBB->succ_empty()) {
678 MachineBasicBlock *Succ = *OrigBB->succ_begin();
679 OrigBB->removeSuccessor(Succ);
680 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000681
Evan Chenga8e29892007-01-19 07:51:42 +0000682 // This pass should be run after register allocation, so there should be no
683 // PHI nodes to update.
684 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
685 && "PHI nodes should be eliminated by now!");
686 }
Bob Wilson84945262009-05-12 17:09:30 +0000687
Evan Chenga8e29892007-01-19 07:51:42 +0000688 // OrigBB branches to NewBB.
689 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000690
Evan Chenga8e29892007-01-19 07:51:42 +0000691 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000692 // This is almost the same as UpdateForInsertedWaterBlock, except that
693 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000694 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000695
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000696 // Insert a size into BBSizes to align it properly with the (newly
697 // renumbered) block numbers.
698 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000699
Dale Johannesen99c49a42007-02-25 00:47:03 +0000700 // Likewise for BBOffsets.
701 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
702
Bob Wilson84945262009-05-12 17:09:30 +0000703 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000704 // available water after it (but not if it's already there, which happens
705 // when splitting before a conditional branch that is followed by an
706 // unconditional branch - in that case we want to insert NewBB).
Bob Wilson034de5f2009-10-12 18:52:13 +0000707 water_iterator IP =
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000708 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
709 CompareMBBNumbers);
710 MachineBasicBlock* WaterBB = *IP;
711 if (WaterBB == OrigBB)
712 WaterList.insert(next(IP), NewBB);
713 else
714 WaterList.insert(IP, OrigBB);
Bob Wilsonb9239532009-10-15 20:49:47 +0000715 NewWaterList.insert(OrigBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000716
Dale Johannesen8593e412007-04-29 19:19:30 +0000717 // Figure out how large the first NewMBB is. (It cannot
718 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000719 unsigned NewBBSize = 0;
720 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
721 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000722 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000723
Dale Johannesen99c49a42007-02-25 00:47:03 +0000724 unsigned OrigBBI = OrigBB->getNumber();
725 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000726 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000727 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000728
Evan Chenga8e29892007-01-19 07:51:42 +0000729 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000730 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng25f7cfc2009-08-01 06:13:52 +0000731 int delta = isThumb1 ? 2 : 4;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000732 BBSizes[OrigBBI] -= NewBBSize - delta;
733
734 // ...and adjust BBOffsets for NewBB accordingly.
735 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
736
737 // All BBOffsets following these blocks must be modified.
738 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000739
740 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000741}
742
Dale Johannesen8593e412007-04-29 19:19:30 +0000743/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000744/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000745/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000746bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +0000747 unsigned TrialOffset, unsigned MaxDisp,
748 bool NegativeOK, bool IsSoImm) {
Bob Wilson84945262009-05-12 17:09:30 +0000749 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
750 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000751 // Effectively, the valid range of displacements is 2 bytes smaller for such
752 // references.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000753 unsigned TotalAdj = 0;
754 if (isThumb && UserOffset%4 !=0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000755 UserOffset -= 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000756 TotalAdj = 2;
757 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000758 // CPEs will be rounded up to a multiple of 4.
Evan Cheng31b99dd2009-08-14 18:31:44 +0000759 if (isThumb && TrialOffset%4 != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000760 TrialOffset += 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +0000761 TotalAdj += 2;
762 }
763
764 // In Thumb2 mode, later branch adjustments can shift instructions up and
765 // cause alignment change. In the worst case scenario this can cause the
766 // user's effective address to be subtracted by 2 and the CPE's address to
767 // be plus 2.
768 if (isThumb2 && TotalAdj != 4)
769 MaxDisp -= (4 - TotalAdj);
Dale Johannesen8593e412007-04-29 19:19:30 +0000770
Dale Johannesen99c49a42007-02-25 00:47:03 +0000771 if (UserOffset <= TrialOffset) {
772 // User before the Trial.
Evan Chengd3d9d662009-07-23 18:27:47 +0000773 if (TrialOffset - UserOffset <= MaxDisp)
774 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000775 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000776 } else if (NegativeOK) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000777 if (UserOffset - TrialOffset <= MaxDisp)
778 return true;
Evan Cheng40efc252009-07-24 19:31:03 +0000779 // FIXME: Make use full range of soimm values.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000780 }
781 return false;
782}
783
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000784/// WaterIsInRange - Returns true if a CPE placed after the specified
785/// Water (a basic block) will be in range for the specific MI.
786
787bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000788 MachineBasicBlock* Water, CPUser &U) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000789 unsigned MaxDisp = U.MaxDisp;
Bob Wilson84945262009-05-12 17:09:30 +0000790 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000791 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000792
Dale Johannesend959aa42007-04-02 20:31:06 +0000793 // If the CPE is to be inserted before the instruction, that will raise
Bob Wilsonaf4b7352009-10-12 22:49:05 +0000794 // the offset of the instruction.
Dale Johannesend959aa42007-04-02 20:31:06 +0000795 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000796 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000797
Evan Chengd3d9d662009-07-23 18:27:47 +0000798 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000799}
800
801/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000802/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000803bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000804 MachineInstr *CPEMI, unsigned MaxDisp,
805 bool NegOk, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000806 unsigned CPEOffset = GetOffsetOf(CPEMI);
807 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000808
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000809 if (DoDump) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000810 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
811 << " max delta=" << MaxDisp
812 << " insn address=" << UserOffset
813 << " CPE address=" << CPEOffset
814 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000815 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000816
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000817 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Evan Chengc0dbec72007-01-31 19:57:44 +0000818}
819
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000820#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000821/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
822/// unconditionally branches to its only successor.
823static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
824 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
825 return false;
826
827 MachineBasicBlock *Succ = *MBB->succ_begin();
828 MachineBasicBlock *Pred = *MBB->pred_begin();
829 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000830 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
831 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000832 return PredMI->getOperand(0).getMBB() == Succ;
833 return false;
834}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000835#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000836
Bob Wilson84945262009-05-12 17:09:30 +0000837void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000838 int delta) {
839 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengd3d9d662009-07-23 18:27:47 +0000840 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
841 i < e; ++i) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000842 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000843 // If some existing blocks have padding, adjust the padding as needed, a
844 // bit tricky. delta can be negative so don't use % on that.
Evan Chengd3d9d662009-07-23 18:27:47 +0000845 if (!isThumb)
846 continue;
847 MachineBasicBlock *MBB = MBBI;
848 if (!MBB->empty()) {
849 // Constant pool entries require padding.
850 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000851 unsigned OldOffset = BBOffsets[i] - delta;
852 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000853 // add new padding
854 BBSizes[i] += 2;
855 delta += 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000856 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000857 // remove existing padding
Evan Cheng4a8ea212009-08-11 07:36:14 +0000858 BBSizes[i] -= 2;
Evan Chengd3d9d662009-07-23 18:27:47 +0000859 delta -= 2;
Dale Johannesen8593e412007-04-29 19:19:30 +0000860 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000861 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000862 // Thumb1 jump tables require padding. They should be at the end;
863 // following unconditional branches are removed by AnalyzeBranch.
Evan Cheng78947622009-07-24 18:20:44 +0000864 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng66ac5312009-07-25 00:33:29 +0000865 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng4a8ea212009-08-11 07:36:14 +0000866 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
867 unsigned OldMIOffset = NewMIOffset - delta;
868 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000869 // remove existing padding
870 BBSizes[i] -= 2;
871 delta -= 2;
Evan Cheng4a8ea212009-08-11 07:36:14 +0000872 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengd3d9d662009-07-23 18:27:47 +0000873 // add new padding
874 BBSizes[i] += 2;
875 delta += 2;
876 }
877 }
878 if (delta==0)
879 return;
Dale Johannesen8593e412007-04-29 19:19:30 +0000880 }
Evan Chengd3d9d662009-07-23 18:27:47 +0000881 MBBI = next(MBBI);
Dale Johannesen8593e412007-04-29 19:19:30 +0000882 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000883}
884
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000885/// DecrementOldEntry - find the constant pool entry with index CPI
886/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000887/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000888/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000889
Evan Chenged884f32007-04-03 23:39:48 +0000890bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000891 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000892 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
893 assert(CPE && "Unexpected!");
894 if (--CPE->RefCount == 0) {
895 RemoveDeadCPEMI(CPEMI);
896 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000897 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000898 return true;
899 }
900 return false;
901}
902
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000903/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
904/// if not, see if an in-range clone of the CPE is in range, and if so,
905/// change the data structures so the user references the clone. Returns:
906/// 0 = no existing entry found
907/// 1 = entry found, and there were no code insertions or deletions
908/// 2 = entry found, and there were code insertions or deletions
909int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
910{
911 MachineInstr *UserMI = U.MI;
912 MachineInstr *CPEMI = U.CPEMI;
913
914 // Check to see if the CPE is already in-range.
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000915 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000916 DEBUG(errs() << "In range\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000917 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000918 }
919
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000920 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000921 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000922 std::vector<CPEntry> &CPEs = CPEntries[CPI];
923 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
924 // We already tried this one
925 if (CPEs[i].CPEMI == CPEMI)
926 continue;
927 // Removing CPEs can leave empty entries, skip
928 if (CPEs[i].CPEMI == NULL)
929 continue;
Evan Cheng5d8f1ca2009-07-21 23:56:01 +0000930 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Chris Lattner893e1c92009-08-23 06:49:22 +0000931 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
932 << CPEs[i].CPI << "\n");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000933 // Point the CPUser node to the replacement
934 U.CPEMI = CPEs[i].CPEMI;
935 // Change the CPI in the instruction operand to refer to the clone.
936 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000937 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000938 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000939 break;
940 }
941 // Adjust the refcount of the clone...
942 CPEs[i].RefCount++;
943 // ...and the original. If we didn't remove the old entry, none of the
944 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000945 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000946 }
947 }
948 return 0;
949}
950
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000951/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
952/// the specific unconditional branch instruction.
953static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000954 switch (Opc) {
955 case ARM::tB:
956 return ((1<<10)-1)*2;
957 case ARM::t2B:
958 return ((1<<23)-1)*2;
959 default:
960 break;
961 }
Jim Grosbach764ab522009-08-11 15:33:49 +0000962
David Goodwin5e47a9a2009-06-30 18:04:13 +0000963 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000964}
965
Bob Wilsonb9239532009-10-15 20:49:47 +0000966/// LookForWater - Look for an existing entry in the WaterList in which
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000967/// we can place the CPE referenced from U so it's within range of U's MI.
Bob Wilsonb9239532009-10-15 20:49:47 +0000968/// Returns true if found, false if not. If it returns true, WaterIter
Bob Wilsonf98032e2009-10-12 21:23:15 +0000969/// is set to the WaterList entry. For Thumb, prefer water that will not
970/// introduce padding to water that will. To ensure that this pass
971/// terminates, the CPE location for a particular CPUser is only allowed to
972/// move to a lower address, so search backward from the end of the list and
973/// prefer the first water that is in range.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000974bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Bob Wilsonb9239532009-10-15 20:49:47 +0000975 water_iterator &WaterIter) {
Bob Wilson3b757352009-10-12 19:04:03 +0000976 if (WaterList.empty())
977 return false;
978
Bob Wilson32c50e82009-10-12 20:45:53 +0000979 bool FoundWaterThatWouldPad = false;
980 water_iterator IPThatWouldPad;
Bob Wilson3b757352009-10-12 19:04:03 +0000981 for (water_iterator IP = prior(WaterList.end()),
982 B = WaterList.begin();; --IP) {
983 MachineBasicBlock* WaterBB = *IP;
Bob Wilsonb9239532009-10-15 20:49:47 +0000984 // Check if water is in range and is either at a lower address than the
985 // current "high water mark" or a new water block that was created since
986 // the previous iteration by inserting an unconditional branch. In the
987 // latter case, we want to allow resetting the high water mark back to
988 // this new water since we haven't seen it before. Inserting branches
989 // should be relatively uncommon and when it does happen, we want to be
990 // sure to take advantage of it for all the CPEs near that block, so that
991 // we don't insert more branches than necessary.
992 if (WaterIsInRange(UserOffset, WaterBB, U) &&
993 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
994 NewWaterList.count(WaterBB))) {
Bob Wilson3b757352009-10-12 19:04:03 +0000995 unsigned WBBId = WaterBB->getNumber();
996 if (isThumb &&
997 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
998 // This is valid Water, but would introduce padding. Remember
999 // it in case we don't find any Water that doesn't do this.
Bob Wilson32c50e82009-10-12 20:45:53 +00001000 if (!FoundWaterThatWouldPad) {
1001 FoundWaterThatWouldPad = true;
Bob Wilson3b757352009-10-12 19:04:03 +00001002 IPThatWouldPad = IP;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001003 }
Bob Wilson3b757352009-10-12 19:04:03 +00001004 } else {
Bob Wilsonb9239532009-10-15 20:49:47 +00001005 WaterIter = IP;
Bob Wilson3b757352009-10-12 19:04:03 +00001006 return true;
Evan Chengd3d9d662009-07-23 18:27:47 +00001007 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001008 }
Bob Wilson3b757352009-10-12 19:04:03 +00001009 if (IP == B)
1010 break;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001011 }
Bob Wilson32c50e82009-10-12 20:45:53 +00001012 if (FoundWaterThatWouldPad) {
Bob Wilsonb9239532009-10-15 20:49:47 +00001013 WaterIter = IPThatWouldPad;
Dale Johannesen8593e412007-04-29 19:19:30 +00001014 return true;
1015 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001016 return false;
1017}
1018
Bob Wilson84945262009-05-12 17:09:30 +00001019/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001020/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1021/// block is used if in range, and the conditional branch munged so control
1022/// flow is correct. Otherwise the block is split to create a hole with an
Bob Wilson757652c2009-10-12 21:39:43 +00001023/// unconditional branch around it. In either case NewMBB is set to a
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001024/// block following which the new island can be inserted (the WaterList
1025/// is not adjusted).
Bob Wilson84945262009-05-12 17:09:30 +00001026void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Bob Wilson757652c2009-10-12 21:39:43 +00001027 unsigned UserOffset,
1028 MachineBasicBlock *&NewMBB) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001029 CPUser &U = CPUsers[CPUserIndex];
1030 MachineInstr *UserMI = U.MI;
1031 MachineInstr *CPEMI = U.CPEMI;
1032 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +00001033 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001034 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +00001035 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001036
Bob Wilson36fa5322009-10-15 05:10:36 +00001037 // If the block does not end in an unconditional branch already, and if the
1038 // end of the block is within range, make new water there. (The addition
1039 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1040 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dale Johannesen8593e412007-04-29 19:19:30 +00001041 // inside OffsetIsInRange.
Bob Wilson36fa5322009-10-15 05:10:36 +00001042 if (BBHasFallthrough(UserMBB) &&
Evan Chengd3d9d662009-07-23 18:27:47 +00001043 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1044 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Chris Lattner893e1c92009-08-23 06:49:22 +00001045 DEBUG(errs() << "Split at end of block\n");
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001046 if (&UserMBB->back() == UserMI)
1047 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Bob Wilson757652c2009-10-12 21:39:43 +00001048 NewMBB = next(MachineFunction::iterator(UserMBB));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001049 // Add an unconditional branch from UserMBB to fallthrough block.
1050 // Record it for branch lengthening; this new branch will not get out of
1051 // range, but if the preceding conditional branch is out of range, the
1052 // targets will be exchanged, and the altered branch may be out of
1053 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +00001054 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +00001055 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
Bob Wilson757652c2009-10-12 21:39:43 +00001056 TII->get(UncondBr)).addMBB(NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001057 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +00001058 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001059 MaxDisp, false, UncondBr));
Evan Chengd3d9d662009-07-23 18:27:47 +00001060 int delta = isThumb1 ? 2 : 4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001061 BBSizes[UserMBB->getNumber()] += delta;
1062 AdjustBBOffsetsAfter(UserMBB, delta);
1063 } else {
1064 // What a big block. Find a place within the block to split it.
Evan Chengd3d9d662009-07-23 18:27:47 +00001065 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001066 // and constant pool entries are 4 bytes: if instruction I references
1067 // island CPE, and instruction I+1 references CPE', it will
1068 // not work well to put CPE as far forward as possible, since then
1069 // CPE' cannot immediately follow it (that location is 2 bytes
1070 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +00001071 // a new island. So, we make a first guess, then walk through the
1072 // instructions between the one currently being looked at and the
1073 // possible insertion point, and make sure any other instructions
1074 // that reference CPEs will be able to use the same island area;
1075 // if not, we back up the insertion point.
1076
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001077 // The 4 in the following is for the unconditional branch we'll be
Evan Chengd3d9d662009-07-23 18:27:47 +00001078 // inserting (allows for long branch on Thumb1). Alignment of the
Dale Johannesen8593e412007-04-29 19:19:30 +00001079 // island is handled inside OffsetIsInRange.
1080 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001081 // This could point off the end of the block if we've already got
1082 // constant pool entries following this block; only the last one is
1083 // in the water list. Back past any possible branches (allow for a
1084 // conditional and a maximally long unconditional).
1085 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001086 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengd3d9d662009-07-23 18:27:47 +00001087 (isThumb1 ? 6 : 8);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001088 unsigned EndInsertOffset = BaseInsertOffset +
1089 CPEMI->getOperand(2).getImm();
1090 MachineBasicBlock::iterator MI = UserMI;
1091 ++MI;
1092 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001093 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001094 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001095 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001096 MI = next(MI)) {
1097 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001098 CPUser &U = CPUsers[CPUIndex];
Bob Wilson84945262009-05-12 17:09:30 +00001099 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengd3d9d662009-07-23 18:27:47 +00001100 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1101 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1102 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001103 }
1104 // This is overly conservative, as we don't account for CPEMIs
1105 // being reused within the block, but it doesn't matter much.
1106 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1107 CPUIndex++;
1108 }
1109 }
Chris Lattner893e1c92009-08-23 06:49:22 +00001110 DEBUG(errs() << "Split in middle of big block\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001111 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001112 }
1113}
1114
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001115/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001116/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001117/// place in-range. Return true if we changed any addresses (thus must run
1118/// another pass of branch lengthening), false otherwise.
Evan Cheng5657c012009-07-29 02:18:14 +00001119bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilson84945262009-05-12 17:09:30 +00001120 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001121 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001122 MachineInstr *UserMI = U.MI;
1123 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001124 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001125 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen8593e412007-04-29 19:19:30 +00001126 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga1efbbd2009-08-14 00:32:16 +00001127 // hardware keeps in the PC.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001128 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001129
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001130 // See if the current entry is within range, or there is a clone of it
1131 // in range.
1132 int result = LookForExistingCPEntry(U, UserOffset);
1133 if (result==1) return false;
1134 else if (result==2) return true;
1135
1136 // No existing clone of this CPE is within range.
1137 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001138 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001139
Bob Wilsonf98032e2009-10-12 21:23:15 +00001140 // Look for water where we can place this CPE.
Bob Wilsonb9239532009-10-15 20:49:47 +00001141 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1142 MachineBasicBlock *NewMBB;
1143 water_iterator IP;
1144 if (LookForWater(U, UserOffset, IP)) {
1145 DEBUG(errs() << "found water in range\n");
1146 MachineBasicBlock *WaterBB = *IP;
1147
1148 // If the original WaterList entry was "new water" on this iteration,
1149 // propagate that to the new island. This is just keeping NewWaterList
1150 // updated to match the WaterList, which will be updated below.
1151 if (NewWaterList.count(WaterBB)) {
1152 NewWaterList.erase(WaterBB);
1153 NewWaterList.insert(NewIsland);
1154 }
1155 // The new CPE goes before the following block (NewMBB).
1156 NewMBB = next(MachineFunction::iterator(WaterBB));
1157
1158 } else {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001159 // No water found.
Chris Lattner893e1c92009-08-23 06:49:22 +00001160 DEBUG(errs() << "No water found\n");
Bob Wilson757652c2009-10-12 21:39:43 +00001161 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
Bob Wilsonb9239532009-10-15 20:49:47 +00001162
1163 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1164 // called while handling branches so that the water will be seen on the
1165 // next iteration for constant pools, but in this context, we don't want
1166 // it. Check for this so it will be removed from the WaterList.
1167 // Also remove any entry from NewWaterList.
1168 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1169 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1170 if (IP != WaterList.end())
1171 NewWaterList.erase(WaterBB);
1172
1173 // We are adding new water. Update NewWaterList.
1174 NewWaterList.insert(NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001175 }
1176
Bob Wilsonb9239532009-10-15 20:49:47 +00001177 // Remove the original WaterList entry; we want subsequent insertions in
1178 // this vicinity to go after the one we're about to insert. This
1179 // considerably reduces the number of times we have to move the same CPE
1180 // more than once and is also important to ensure the algorithm terminates.
1181 if (IP != WaterList.end())
1182 WaterList.erase(IP);
1183
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001184 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng5657c012009-07-29 02:18:14 +00001185 MF.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001186
1187 // Update internal data structures to account for the newly inserted MBB.
1188 UpdateForInsertedWaterBlock(NewIsland);
1189
1190 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001191 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001192
1193 // Now that we have an island to add the CPE to, clone the original CPE and
1194 // add it to the island.
Bob Wilson549dda92009-10-15 05:52:29 +00001195 U.HighWaterMark = NewIsland;
Dale Johannesenb6728402009-02-13 02:25:56 +00001196 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1197 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001198 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001199 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001200 NumCPEs++;
1201
Dale Johannesen8593e412007-04-29 19:19:30 +00001202 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001203 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001204 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001205 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001206 // Increase the size of the island block to account for the new entry.
1207 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001208 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001209
Evan Chenga8e29892007-01-19 07:51:42 +00001210 // Finally, change the CPI in the instruction operand to be ID.
1211 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001212 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001213 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001214 break;
1215 }
Bob Wilson84945262009-05-12 17:09:30 +00001216
Chris Lattner705e07f2009-08-23 03:41:05 +00001217 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1218 << '\t' << *UserMI);
Bob Wilson84945262009-05-12 17:09:30 +00001219
Evan Chenga8e29892007-01-19 07:51:42 +00001220 return true;
1221}
1222
Evan Chenged884f32007-04-03 23:39:48 +00001223/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1224/// sizes and offsets of impacted basic blocks.
1225void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1226 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001227 unsigned Size = CPEMI->getOperand(2).getImm();
1228 CPEMI->eraseFromParent();
1229 BBSizes[CPEBB->getNumber()] -= Size;
1230 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001231 if (CPEBB->empty()) {
Evan Chengd3d9d662009-07-23 18:27:47 +00001232 // In thumb1 mode, the size of island may be padded by two to compensate for
Dale Johannesen8593e412007-04-29 19:19:30 +00001233 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001234 // empty, so fix this.
1235 // All succeeding offsets have the current size value added in, fix this.
1236 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001237 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001238 BBSizes[CPEBB->getNumber()] = 0;
1239 }
Evan Chenged884f32007-04-03 23:39:48 +00001240 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001241 AdjustBBOffsetsAfter(CPEBB, -Size);
1242 // An island has only one predecessor BB and one successor BB. Check if
1243 // this BB's predecessor jumps directly to this BB's successor. This
1244 // shouldn't happen currently.
1245 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1246 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001247}
1248
1249/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1250/// are zero.
1251bool ARMConstantIslands::RemoveUnusedCPEntries() {
1252 unsigned MadeChange = false;
1253 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1254 std::vector<CPEntry> &CPEs = CPEntries[i];
1255 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1256 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1257 RemoveDeadCPEMI(CPEs[j].CPEMI);
1258 CPEs[j].CPEMI = NULL;
1259 MadeChange = true;
1260 }
1261 }
Bob Wilson84945262009-05-12 17:09:30 +00001262 }
Evan Chenged884f32007-04-03 23:39:48 +00001263 return MadeChange;
1264}
1265
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001266/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001267/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001268bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1269 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001270 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001271 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001272 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001273
Chris Lattner705e07f2009-08-23 03:41:05 +00001274 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1275 << " from BB#" << MI->getParent()->getNumber()
1276 << " max delta=" << MaxDisp
1277 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1278 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
Evan Chengc0dbec72007-01-31 19:57:44 +00001279
Dale Johannesen8593e412007-04-29 19:19:30 +00001280 if (BrOffset <= DestOffset) {
1281 // Branch before the Dest.
1282 if (DestOffset-BrOffset <= MaxDisp)
1283 return true;
1284 } else {
1285 if (BrOffset-DestOffset <= MaxDisp)
1286 return true;
1287 }
1288 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001289}
1290
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001291/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1292/// away to fit in its displacement field.
Evan Cheng5657c012009-07-29 02:18:14 +00001293bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001294 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001295 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001296
Evan Chengc0dbec72007-01-31 19:57:44 +00001297 // Check to see if the DestBB is already in-range.
1298 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001299 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001300
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001301 if (!Br.isCond)
Evan Cheng5657c012009-07-29 02:18:14 +00001302 return FixUpUnconditionalBr(MF, Br);
1303 return FixUpConditionalBr(MF, Br);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001304}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001305
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001306/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1307/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001308/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001309/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001310bool
Evan Cheng5657c012009-07-29 02:18:14 +00001311ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001312 MachineInstr *MI = Br.MI;
1313 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng53c67c02009-08-07 05:45:07 +00001314 if (!isThumb1)
1315 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001316
1317 // Use BL to implement far jump.
1318 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001319 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001320 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001321 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001322 HasFarJump = true;
1323 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001324
Chris Lattner705e07f2009-08-23 03:41:05 +00001325 DEBUG(errs() << " Changed B to long jump " << *MI);
Evan Chengbd5d3db2007-02-03 02:08:34 +00001326
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001327 return true;
1328}
1329
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001330/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001331/// far away to fit in its displacement field. It is converted to an inverse
1332/// conditional branch + an unconditional branch to the destination.
1333bool
Evan Cheng5657c012009-07-29 02:18:14 +00001334ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001335 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001336 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001337
Bob Wilson39bf0512009-05-12 17:35:29 +00001338 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001339 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001340 // blt L1
1341 // =>
1342 // bge L2
1343 // b L1
1344 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001345 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001346 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001347 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001348
1349 // If the branch is at the end of its MBB and that has a fall-through block,
1350 // direct the updated conditional branch to the fall-through block. Otherwise,
1351 // split the MBB before the next instruction.
1352 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001353 MachineInstr *BMI = &MBB->back();
1354 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001355
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001356 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001357 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001358 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001359 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001360 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001361 // condition and swap destinations:
1362 // beq L1
1363 // b L2
1364 // =>
1365 // bne L2
1366 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001367 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001368 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Chris Lattner705e07f2009-08-23 03:41:05 +00001369 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1370 << *BMI);
Chris Lattner8aa797a2007-12-30 23:10:15 +00001371 BMI->getOperand(0).setMBB(DestBB);
1372 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001373 MI->getOperand(1).setImm(CC);
1374 return true;
1375 }
1376 }
1377 }
1378
1379 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001380 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001381 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001382 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001383 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001384 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001385 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1386 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001387 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001388 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001389 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001390 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001391
Chris Lattner893e1c92009-08-23 06:49:22 +00001392 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1393 << " also invert condition and change dest. to BB#"
1394 << NextBB->getNumber() << "\n");
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001395
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001396 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001397 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001398 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1399 TII->get(MI->getOpcode()))
1400 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001401 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001402 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001403 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001404 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001405 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001406 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001407
1408 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001409 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001410 MI->eraseFromParent();
1411
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001412 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001413 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001414 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001415 return true;
1416}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001417
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001418/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng4b322e52009-08-11 21:11:32 +00001419/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1420/// to do this if tBfar is not used.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001421bool ARMConstantIslands::UndoLRSpillRestore() {
1422 bool MadeChange = false;
1423 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1424 MachineInstr *MI = PushPopMIs[i];
Evan Cheng10469f82009-10-01 20:54:53 +00001425 // First two operands are predicates, the third is a zero since there
1426 // is no writeback.
Evan Cheng44bec522007-05-15 01:29:07 +00001427 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng10469f82009-10-01 20:54:53 +00001428 MI->getOperand(3).getReg() == ARM::PC &&
1429 MI->getNumExplicitOperands() == 4) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001430 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001431 MI->eraseFromParent();
1432 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001433 }
1434 }
1435 return MadeChange;
1436}
Evan Cheng5657c012009-07-29 02:18:14 +00001437
Evan Chenga1efbbd2009-08-14 00:32:16 +00001438bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1439 bool MadeChange = false;
1440
1441 // Shrink ADR and LDR from constantpool.
1442 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1443 CPUser &U = CPUsers[i];
1444 unsigned Opcode = U.MI->getOpcode();
1445 unsigned NewOpc = 0;
1446 unsigned Scale = 1;
1447 unsigned Bits = 0;
1448 switch (Opcode) {
1449 default: break;
1450 case ARM::t2LEApcrel:
1451 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1452 NewOpc = ARM::tLEApcrel;
1453 Bits = 8;
1454 Scale = 4;
1455 }
1456 break;
1457 case ARM::t2LDRpci:
1458 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1459 NewOpc = ARM::tLDRpci;
1460 Bits = 8;
1461 Scale = 4;
1462 }
1463 break;
1464 }
1465
1466 if (!NewOpc)
1467 continue;
1468
1469 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1470 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1471 // FIXME: Check if offset is multiple of scale if scale is not 4.
1472 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1473 U.MI->setDesc(TII->get(NewOpc));
1474 MachineBasicBlock *MBB = U.MI->getParent();
1475 BBSizes[MBB->getNumber()] -= 2;
1476 AdjustBBOffsetsAfter(MBB, -2);
1477 ++NumT2CPShrunk;
1478 MadeChange = true;
1479 }
1480 }
1481
Evan Chenga1efbbd2009-08-14 00:32:16 +00001482 MadeChange |= OptimizeThumb2Branches(MF);
1483 return MadeChange;
1484}
1485
1486bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001487 bool MadeChange = false;
1488
1489 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1490 ImmBranch &Br = ImmBranches[i];
1491 unsigned Opcode = Br.MI->getOpcode();
1492 unsigned NewOpc = 0;
1493 unsigned Scale = 1;
1494 unsigned Bits = 0;
1495 switch (Opcode) {
1496 default: break;
1497 case ARM::t2B:
1498 NewOpc = ARM::tB;
1499 Bits = 11;
1500 Scale = 2;
1501 break;
Evan Chengde17fb62009-10-31 23:46:45 +00001502 case ARM::t2Bcc: {
Evan Cheng31b99dd2009-08-14 18:31:44 +00001503 NewOpc = ARM::tBcc;
1504 Bits = 8;
Evan Chengde17fb62009-10-31 23:46:45 +00001505 Scale = 2;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001506 break;
1507 }
Evan Chengde17fb62009-10-31 23:46:45 +00001508 }
1509 if (NewOpc) {
1510 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1511 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1512 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1513 Br.MI->setDesc(TII->get(NewOpc));
1514 MachineBasicBlock *MBB = Br.MI->getParent();
1515 BBSizes[MBB->getNumber()] -= 2;
1516 AdjustBBOffsetsAfter(MBB, -2);
1517 ++NumT2BrShrunk;
1518 MadeChange = true;
1519 }
1520 }
1521
1522 Opcode = Br.MI->getOpcode();
1523 if (Opcode != ARM::tBcc)
Evan Cheng31b99dd2009-08-14 18:31:44 +00001524 continue;
1525
Evan Chengde17fb62009-10-31 23:46:45 +00001526 NewOpc = 0;
1527 unsigned PredReg = 0;
1528 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1529 if (Pred == ARMCC::EQ)
1530 NewOpc = ARM::tCBZ;
1531 else if (Pred == ARMCC::NE)
1532 NewOpc = ARM::tCBNZ;
1533 if (!NewOpc)
1534 continue;
Evan Cheng31b99dd2009-08-14 18:31:44 +00001535 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
Evan Chengde17fb62009-10-31 23:46:45 +00001536 // Check if the distance is within 126. Subtract starting offset by 2
1537 // because the cmp will be eliminated.
1538 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1539 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1540 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1541 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1542 if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1543 unsigned Reg = CmpMI->getOperand(0).getReg();
1544 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1545 if (Pred == ARMCC::AL &&
1546 CmpMI->getOperand(1).getImm() == 0 &&
1547 isARMLowRegister(Reg)) {
1548 MachineBasicBlock *MBB = Br.MI->getParent();
1549 MachineInstr *NewBR =
1550 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1551 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1552 CmpMI->eraseFromParent();
1553 Br.MI->eraseFromParent();
1554 Br.MI = NewBR;
1555 BBSizes[MBB->getNumber()] -= 2;
1556 AdjustBBOffsetsAfter(MBB, -2);
1557 ++NumCBZ;
1558 MadeChange = true;
1559 }
1560 }
Evan Cheng31b99dd2009-08-14 18:31:44 +00001561 }
1562 }
1563
1564 return MadeChange;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001565}
1566
1567
1568/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1569/// jumptables when it's possible.
Evan Cheng5657c012009-07-29 02:18:14 +00001570bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1571 bool MadeChange = false;
1572
1573 // FIXME: After the tables are shrunk, can we get rid some of the
1574 // constantpool tables?
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001575 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
Evan Cheng5657c012009-07-29 02:18:14 +00001576 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1577 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1578 MachineInstr *MI = T2JumpTables[i];
1579 const TargetInstrDesc &TID = MI->getDesc();
1580 unsigned NumOps = TID.getNumOperands();
1581 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1582 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1583 unsigned JTI = JTOP.getIndex();
1584 assert(JTI < JT.size());
1585
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001586 // We prefer if target blocks for the jump table come after the jump
1587 // instruction so we can use TB[BH]. Loop through the target blocks
1588 // and try to adjust them such that that's true.
Evan Cheng5657c012009-07-29 02:18:14 +00001589 unsigned JTOffset = GetOffsetOf(MI) + 4;
1590 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001591 if (AdjustJumpTableBlocks) {
1592 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1593 MachineBasicBlock *MBB = JTBBs[j];
1594 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1595
1596 if (DstOffset < JTOffset) {
1597 // The destination precedes the switch. Try to move the block forward
1598 // so we have a positive offset.
1599 MachineBasicBlock *NewBB =
1600 AdjustJTTargetBlockForward(MBB, MI->getParent());
1601 if (NewBB) {
1602 MJTI->ReplaceMBBInJumpTables(JTBBs[j], NewBB);
1603 JTOffset = GetOffsetOf(MI) + 4;
1604 DstOffset = BBOffsets[MBB->getNumber()];
1605 }
1606 }
1607 }
1608 }
1609
1610 bool ByteOk = true;
1611 bool HalfWordOk = true;
1612 JTOffset = GetOffsetOf(MI) + 4;
Evan Cheng5657c012009-07-29 02:18:14 +00001613 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1614 MachineBasicBlock *MBB = JTBBs[j];
1615 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Cheng8770f742009-07-29 23:20:20 +00001616 // Negative offset is not ok. FIXME: We should change BB layout to make
1617 // sure all the branches are forward.
Evan Chengd26b14c2009-07-31 18:28:05 +00001618 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng5657c012009-07-29 02:18:14 +00001619 ByteOk = false;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001620 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001621 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng5657c012009-07-29 02:18:14 +00001622 HalfWordOk = false;
1623 if (!ByteOk && !HalfWordOk)
1624 break;
1625 }
1626
1627 if (ByteOk || HalfWordOk) {
1628 MachineBasicBlock *MBB = MI->getParent();
1629 unsigned BaseReg = MI->getOperand(0).getReg();
1630 bool BaseRegKill = MI->getOperand(0).isKill();
1631 if (!BaseRegKill)
1632 continue;
1633 unsigned IdxReg = MI->getOperand(1).getReg();
1634 bool IdxRegKill = MI->getOperand(1).isKill();
1635 MachineBasicBlock::iterator PrevI = MI;
1636 if (PrevI == MBB->begin())
1637 continue;
1638
1639 MachineInstr *AddrMI = --PrevI;
1640 bool OptOk = true;
1641 // Examine the instruction that calculate the jumptable entry address.
1642 // If it's not the one just before the t2BR_JT, we won't delete it, then
1643 // it's not worth doing the optimization.
1644 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1645 const MachineOperand &MO = AddrMI->getOperand(k);
1646 if (!MO.isReg() || !MO.getReg())
1647 continue;
1648 if (MO.isDef() && MO.getReg() != BaseReg) {
1649 OptOk = false;
1650 break;
1651 }
1652 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1653 OptOk = false;
1654 break;
1655 }
1656 }
1657 if (!OptOk)
1658 continue;
1659
Evan Chenga1efbbd2009-08-14 00:32:16 +00001660 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1661 // to delete it as well.
Evan Cheng5657c012009-07-29 02:18:14 +00001662 MachineInstr *LeaMI = --PrevI;
Evan Chenga1efbbd2009-08-14 00:32:16 +00001663 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1664 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng5657c012009-07-29 02:18:14 +00001665 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001666 OptOk = false;
Evan Cheng5657c012009-07-29 02:18:14 +00001667
Evan Cheng25f7cfc2009-08-01 06:13:52 +00001668 if (!OptOk)
1669 continue;
1670
1671 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1672 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1673 .addReg(IdxReg, getKillRegState(IdxRegKill))
1674 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1675 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1676 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1677 // is 2-byte aligned. For now, asm printer will fix it up.
1678 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1679 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1680 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1681 OrigSize += TII->GetInstSizeInBytes(MI);
1682
1683 AddrMI->eraseFromParent();
1684 LeaMI->eraseFromParent();
1685 MI->eraseFromParent();
1686
1687 int delta = OrigSize - NewSize;
1688 BBSizes[MBB->getNumber()] -= delta;
1689 AdjustBBOffsetsAfter(MBB, -delta);
1690
1691 ++NumTBs;
1692 MadeChange = true;
Evan Cheng5657c012009-07-29 02:18:14 +00001693 }
1694 }
1695
1696 return MadeChange;
1697}
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001698
1699MachineBasicBlock *ARMConstantIslands::
1700AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1701{
1702 MachineFunction &MF = *BB->getParent();
1703
1704 // FIXME: For now, instead of moving the block, we'll create a new block
1705 // immediate following the jump that's an unconditional branch to the
1706 // actual target. This is obviously not what we want for a real solution,
1707 // but it's useful for proof of concept, and it may be a useful fallback
1708 // later for cases where we otherwise can't move a block.
1709
1710 // Create a new MBB for the code after the jump BB.
1711 MachineBasicBlock *NewBB =
1712 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1713 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1714 MF.insert(MBBI, NewBB);
1715
1716 // Add an unconditional branch from NewBB to BB.
1717 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1718 // correspond directly to anything in the source.
1719 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1720 BuildMI(NewBB, DebugLoc::getUnknownLoc(), TII->get(ARM::t2B)).addMBB(BB);
1721
1722 // Update the CFG.
1723 NewBB->addSuccessor(BB);
1724 JTBB->removeSuccessor(BB);
1725 JTBB->addSuccessor(NewBB);
1726
1727 // Update internal data structures to account for the newly inserted MBB.
Jim Grosbachf4997e82009-11-11 19:04:24 +00001728 // Don't mark the new block as having water following it, as we want the
1729 // blocks following the jump table to be as close together as possible.
Jim Grosbach1fc7d712009-11-11 02:47:19 +00001730 MF.RenumberBlocks(NewBB);
1731
1732 // Insert a size into BBSizes to align it properly with the (newly
1733 // renumbered) block numbers.
1734 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
1735
1736 // Likewise for BBOffsets.
1737 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
1738
1739 // Figure out how large the first NewMBB is.
1740 unsigned NewBBSize = 0;
1741 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
1742 I != E; ++I)
1743 NewBBSize += TII->GetInstSizeInBytes(I);
1744
1745 unsigned NewBBI = NewBB->getNumber();
1746 unsigned JTBBI = JTBB->getNumber();
1747 // Set the size of NewBB in BBSizes.
1748 BBSizes[NewBBI] = NewBBSize;
1749
1750 // ...and adjust BBOffsets for NewBB accordingly.
1751 BBOffsets[NewBBI] = BBOffsets[JTBBI] + BBSizes[JTBBI];
1752
1753 // All BBOffsets following these blocks must be modified.
1754 AdjustBBOffsetsAfter(NewBB, 4);
1755
1756 ++NumJTMoved;
1757 return NewBB;
1758}