blob: 746d5edf17c0cd4069c9d362b0ecfd27bc01daa8 [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 Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Chenga8e29892007-01-19 07:51:42 +000023#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Debug.h"
Evan Chengc99ef082007-02-09 20:54:44 +000027#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
Evan Chenga8e29892007-01-19 07:51:42 +000030using namespace llvm;
31
Evan Chengc99ef082007-02-09 20:54:44 +000032STATISTIC(NumCPEs, "Number of constpool entries");
Evan Chengd1b2c1e2007-01-30 01:18:38 +000033STATISTIC(NumSplit, "Number of uncond branches inserted");
34STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Evan Chenga8e29892007-01-19 07:51:42 +000036
37namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000038 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000039 /// requires constant pool entries to be scattered among the instructions
40 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000041 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000042 /// special instructions.
43 ///
44 /// The terminology used in this pass includes:
45 /// Islands - Clumps of constants placed in the function.
46 /// Water - Potential places where an island could be formed.
47 /// CPE - A constant pool entry that has been placed somewhere, which
48 /// tracks a list of users.
49 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Evan Chenga8e29892007-01-19 07:51:42 +000050 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
Dale Johannesen8593e412007-04-29 19:19:30 +000051 /// by MBB Number. The two-byte pads required for Thumb alignment are
52 /// counted as part of the following block (i.e., the offset and size for
53 /// a padded block will both be ==2 mod 4).
Evan Chenge03cff62007-02-09 23:59:14 +000054 std::vector<unsigned> BBSizes;
Evan Chenga8e29892007-01-19 07:51:42 +000055
Dale Johannesen99c49a42007-02-25 00:47:03 +000056 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
Dale Johannesen8593e412007-04-29 19:19:30 +000057 /// The two-byte pads required for Thumb alignment are counted as part of
58 /// the following block.
Dale Johannesen99c49a42007-02-25 00:47:03 +000059 std::vector<unsigned> BBOffsets;
60
Evan Chenga8e29892007-01-19 07:51:42 +000061 /// WaterList - A sorted list of basic blocks where islands could be placed
62 /// (i.e. blocks that don't fall through to the following block, due
63 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000064 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000065
Evan Chenga8e29892007-01-19 07:51:42 +000066 /// CPUser - One user of a constant pool, keeping the machine instruction
67 /// pointer, the constant pool being referenced, and the max displacement
68 /// allowed from the instruction to the CP.
69 struct CPUser {
70 MachineInstr *MI;
71 MachineInstr *CPEMI;
72 unsigned MaxDisp;
73 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
74 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
75 };
76
77 /// CPUsers - Keep track of all of the machine instructions that use various
78 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000079 std::vector<CPUser> CPUsers;
Evan Chengc99ef082007-02-09 20:54:44 +000080
81 /// CPEntry - One per constant pool entry, keeping the machine instruction
82 /// pointer, the constpool index, and the number of CPUser's which
83 /// reference this entry.
84 struct CPEntry {
85 MachineInstr *CPEMI;
86 unsigned CPI;
87 unsigned RefCount;
88 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
89 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
90 };
91
92 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +000093 /// instructions. For each original constpool index (i.e. those that
94 /// existed upon entry to this pass), it keeps a vector of entries.
95 /// Original elements are cloned as we go along; the clones are
96 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +000097 std::vector<std::vector<CPEntry> > CPEntries;
Evan Chenga8e29892007-01-19 07:51:42 +000098
Evan Chengaf5cbcb2007-01-25 03:12:46 +000099 /// ImmBranch - One per immediate branch, keeping the machine instruction
100 /// pointer, conditional or unconditional, the max displacement,
101 /// and (if isCond is true) the corresponding unconditional branch
102 /// opcode.
103 struct ImmBranch {
104 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000105 unsigned MaxDisp : 31;
106 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000107 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000108 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
109 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000110 };
111
Evan Cheng2706f972007-05-16 05:14:06 +0000112 /// ImmBranches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000113 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000114 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000115
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000116 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
117 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000118 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000119
120 /// HasFarJump - True if any far jump instruction has been emitted during
121 /// the branch fix up pass.
122 bool HasFarJump;
123
Evan Chenga8e29892007-01-19 07:51:42 +0000124 const TargetInstrInfo *TII;
Dale Johannesen8593e412007-04-29 19:19:30 +0000125 ARMFunctionInfo *AFI;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000126 bool isThumb;
Evan Chenga8e29892007-01-19 07:51:42 +0000127 public:
Devang Patel19974732007-05-03 01:11:54 +0000128 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000129 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000130
Evan Chenga8e29892007-01-19 07:51:42 +0000131 virtual bool runOnMachineFunction(MachineFunction &Fn);
132
133 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000134 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000135 }
136
137 private:
138 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000139 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000140 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000141 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000142 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000143 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000144 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000145 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000146 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000147 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Dale Johannesen8593e412007-04-29 19:19:30 +0000148 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000149 MachineBasicBlock** NewMBB);
Dale Johannesen8593e412007-04-29 19:19:30 +0000150 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
151 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000152 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
153 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000154 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000155 void RemoveDeadCPEMI(MachineInstr *CPEMI);
156 bool RemoveUnusedCPEntries();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000157 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
158 MachineInstr *CPEMI, unsigned Disp,
159 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000160 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000161 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000162 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
163 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000164 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000165 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
166 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
167 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
168 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000169
Evan Chenga8e29892007-01-19 07:51:42 +0000170 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000171 void dumpBBs();
172 void verify(MachineFunction &Fn);
Evan Chenga8e29892007-01-19 07:51:42 +0000173 };
Devang Patel19974732007-05-03 01:11:54 +0000174 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000175}
176
Dale Johannesen8593e412007-04-29 19:19:30 +0000177/// verify - check BBOffsets, BBSizes, alignment of islands
178void ARMConstantIslands::verify(MachineFunction &Fn) {
179 assert(BBOffsets.size() == BBSizes.size());
180 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
181 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
182 if (isThumb) {
183 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
184 MBBI != E; ++MBBI) {
185 MachineBasicBlock *MBB = MBBI;
186 if (!MBB->empty() &&
187 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
188 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
189 BBSizes[MBB->getNumber()]%4 == 0) ||
190 (BBOffsets[MBB->getNumber()]%4 != 0 &&
191 BBSizes[MBB->getNumber()]%4 != 0));
192 }
193 }
194}
195
196/// print block size and offset information - debugging
197void ARMConstantIslands::dumpBBs() {
198 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000199 DOUT << "block " << J << " offset " << BBOffsets[J] <<
200 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000201 }
202}
203
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000204/// createARMConstantIslandPass - returns an instance of the constpool
205/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000206FunctionPass *llvm::createARMConstantIslandPass() {
207 return new ARMConstantIslands();
208}
209
210bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000211 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000212
213 TII = Fn.getTarget().getInstrInfo();
Dale Johannesen8593e412007-04-29 19:19:30 +0000214 AFI = Fn.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000215 isThumb = AFI->isThumbFunction();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000216
217 HasFarJump = false;
218
Evan Chenga8e29892007-01-19 07:51:42 +0000219 // Renumber all of the machine basic blocks in the function, guaranteeing that
220 // the numbers agree with the position of the block in the function.
221 Fn.RenumberBlocks();
222
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000223 /// Thumb functions containing constant pools get 2-byte alignment. This is so
224 /// we can keep exact track of where the alignment padding goes. Set default.
225 AFI->setAlign(isThumb ? 1U : 2U);
226
Evan Chenga8e29892007-01-19 07:51:42 +0000227 // Perform the initial placement of the constant pool entries. To start with,
228 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000229 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000230 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000231 DoInitialPlacement(Fn, CPEMIs);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000232 if (isThumb)
233 AFI->setAlign(2U);
234 }
Evan Chenga8e29892007-01-19 07:51:42 +0000235
236 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000237 AFI->initConstPoolEntryUId(CPEMIs.size());
Evan Chenga8e29892007-01-19 07:51:42 +0000238
239 // Do the initial scan of the function, building up information about the
240 // sizes of each block, the location of all the water, and finding all of the
241 // constant pool users.
242 InitialFunctionScan(Fn, CPEMIs);
243 CPEMIs.clear();
244
Evan Chenged884f32007-04-03 23:39:48 +0000245 /// Remove dead constant pool entries.
246 RemoveUnusedCPEntries();
247
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000248 // Iteratively place constant pool entries and fix up branches until there
249 // is no change.
250 bool MadeChange = false;
251 while (true) {
252 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000253 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000254 Change |= HandleConstantPoolUser(Fn, i);
Evan Cheng82020102007-07-10 22:00:16 +0000255 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000256 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000257 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000258 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000259 if (!Change)
260 break;
261 MadeChange = true;
262 }
Evan Chenged884f32007-04-03 23:39:48 +0000263
Dale Johannesen8593e412007-04-29 19:19:30 +0000264 // After a while, this might be made debug-only, but it is not expensive.
265 verify(Fn);
266
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000267 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
268 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000269 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000270 MadeChange |= UndoLRSpillRestore();
271
Evan Chenga8e29892007-01-19 07:51:42 +0000272 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000273 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000274 WaterList.clear();
275 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000276 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000277 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000278 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000279
280 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000281}
282
283/// DoInitialPlacement - Perform the initial placement of the constant pool
284/// entries. To start with, we put them all at the end of the function.
285void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000286 std::vector<MachineInstr*> &CPEMIs){
Evan Chenga8e29892007-01-19 07:51:42 +0000287 // Create the basic block to hold the CPE's.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000288 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
289 Fn.push_back(BB);
Evan Chenga8e29892007-01-19 07:51:42 +0000290
291 // Add all of the constants from the constant pool to the end block, use an
292 // identity mapping of CPI's to CPE's.
293 const std::vector<MachineConstantPoolEntry> &CPs =
294 Fn.getConstantPool()->getConstants();
295
296 const TargetData &TD = *Fn.getTarget().getTargetData();
297 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000298 unsigned Size = TD.getTypePaddedSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000299 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
300 // we would have to pad them out or something so that instructions stay
301 // aligned.
302 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
303 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000304 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000305 .addImm(i).addConstantPoolIndex(i).addImm(Size);
306 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000307
308 // Add a new CPEntry, but no corresponding CPUser yet.
309 std::vector<CPEntry> CPEs;
310 CPEs.push_back(CPEntry(CPEMI, i));
311 CPEntries.push_back(CPEs);
312 NumCPEs++;
313 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000314 }
315}
316
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000317/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000318/// into the block immediately after it.
319static bool BBHasFallthrough(MachineBasicBlock *MBB) {
320 // Get the next machine basic block in the function.
321 MachineFunction::iterator MBBI = MBB;
322 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
323 return false;
324
325 MachineBasicBlock *NextBB = next(MBBI);
326 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
327 E = MBB->succ_end(); I != E; ++I)
328 if (*I == NextBB)
329 return true;
330
331 return false;
332}
333
Evan Chengc99ef082007-02-09 20:54:44 +0000334/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
335/// look up the corresponding CPEntry.
336ARMConstantIslands::CPEntry
337*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
338 const MachineInstr *CPEMI) {
339 std::vector<CPEntry> &CPEs = CPEntries[CPI];
340 // Number of entries per constpool index should be small, just do a
341 // linear search.
342 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
343 if (CPEs[i].CPEMI == CPEMI)
344 return &CPEs[i];
345 }
346 return NULL;
347}
348
Evan Chenga8e29892007-01-19 07:51:42 +0000349/// InitialFunctionScan - Do the initial scan of the function, building up
350/// information about the sizes of each block, the location of all the water,
351/// and finding all of the constant pool users.
352void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000353 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000354 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000355 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
356 MBBI != E; ++MBBI) {
357 MachineBasicBlock &MBB = *MBBI;
358
359 // If this block doesn't fall through into the next MBB, then this is
360 // 'water' that a constant pool island could be placed.
361 if (!BBHasFallthrough(&MBB))
362 WaterList.push_back(&MBB);
363
364 unsigned MBBSize = 0;
365 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
366 I != E; ++I) {
367 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000368 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000369
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000370 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000371 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000372 bool isCond = false;
373 unsigned Bits = 0;
374 unsigned Scale = 1;
375 int UOpc = Opc;
376 switch (Opc) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000377 case ARM::tBR_JTr:
378 // A Thumb table jump may involve padding; for the offsets to
379 // be right, functions containing these must be 4-byte aligned.
380 AFI->setAlign(2U);
381 if ((Offset+MBBSize)%4 != 0)
382 MBBSize += 2; // padding
383 continue; // Does not get an entry in ImmBranches
Evan Cheng743fa032007-01-25 19:43:52 +0000384 default:
Dale Johannesen8593e412007-04-29 19:19:30 +0000385 continue; // Ignore other JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000386 case ARM::Bcc:
387 isCond = true;
388 UOpc = ARM::B;
389 // Fallthrough
390 case ARM::B:
391 Bits = 24;
392 Scale = 4;
393 break;
394 case ARM::tBcc:
395 isCond = true;
396 UOpc = ARM::tB;
397 Bits = 8;
398 Scale = 2;
399 break;
400 case ARM::tB:
401 Bits = 11;
402 Scale = 2;
403 break;
404 }
Evan Chengb43216e2007-02-01 10:16:15 +0000405
406 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000407 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000408 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000409 }
410
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000411 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
412 PushPopMIs.push_back(I);
413
Evan Chenga8e29892007-01-19 07:51:42 +0000414 // Scan the instructions for constant pool operands.
415 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000416 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000417 // We found one. The addressing mode tells us the max displacement
418 // from the PC that this instruction permits.
Evan Chenga8e29892007-01-19 07:51:42 +0000419
420 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000421 unsigned Bits = 0;
422 unsigned Scale = 1;
Chris Lattner749c6f62008-01-07 07:27:27 +0000423 unsigned TSFlags = I->getDesc().TSFlags;
Evan Chenga8e29892007-01-19 07:51:42 +0000424 switch (TSFlags & ARMII::AddrModeMask) {
425 default:
426 // Constant pool entries can reach anything.
427 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
428 continue;
Evan Cheng768c9f72007-04-27 08:14:15 +0000429 if (I->getOpcode() == ARM::tLEApcrel) {
430 Bits = 8; // Taking the address of a CP entry.
431 break;
432 }
Evan Chenga8e29892007-01-19 07:51:42 +0000433 assert(0 && "Unknown addressing mode for CP reference!");
434 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000435 Bits = 8;
436 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000437 break;
438 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000439 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000440 break;
441 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000442 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000443 break;
444 // addrmode4 has no immediate offset.
445 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000446 Bits = 8;
447 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000448 break;
449 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000450 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000451 break;
452 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000453 Bits = 5;
454 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000455 break;
456 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000457 Bits = 5;
458 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000459 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000460 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000461 Bits = 8;
462 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000463 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000464 }
Evan Chengb43216e2007-02-01 10:16:15 +0000465
Evan Chenga8e29892007-01-19 07:51:42 +0000466 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000467 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000468 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng556f33c2007-02-01 20:44:52 +0000469 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000470 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000471
472 // Increment corresponding CPEntry reference count.
473 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
474 assert(CPE && "Cannot find a corresponding CPEntry!");
475 CPE->RefCount++;
Evan Chenga8e29892007-01-19 07:51:42 +0000476
477 // Instructions can only use one CP entry, don't bother scanning the
478 // rest of the operands.
479 break;
480 }
481 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000482
Dale Johannesen8593e412007-04-29 19:19:30 +0000483 // In thumb mode, if this block is a constpool island, we may need padding
484 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000485 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000486 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000487 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
488 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000489 MBBSize += 2;
490
Evan Chenga8e29892007-01-19 07:51:42 +0000491 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000492 BBOffsets.push_back(Offset);
493 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000494 }
495}
496
Evan Chenga8e29892007-01-19 07:51:42 +0000497/// GetOffsetOf - Return the current offset of the specified machine instruction
498/// from the start of the function. This offset changes as stuff is moved
499/// around inside the function.
500unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
501 MachineBasicBlock *MBB = MI->getParent();
502
503 // The offset is composed of two things: the sum of the sizes of all MBB's
504 // before this instruction's block, and the offset from the start of the block
505 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000506 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000507
Dale Johannesen8593e412007-04-29 19:19:30 +0000508 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
509 // alignment padding, and compensate if so.
510 if (isThumb &&
511 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
512 Offset%4 != 0)
513 Offset += 2;
514
Evan Chenga8e29892007-01-19 07:51:42 +0000515 // Sum instructions before MI in MBB.
516 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
517 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
518 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000519 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000520 }
521}
522
523/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
524/// ID.
525static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
526 const MachineBasicBlock *RHS) {
527 return LHS->getNumber() < RHS->getNumber();
528}
529
530/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
531/// machine function, it upsets all of the block numbers. Renumber the blocks
532/// and update the arrays that parallel this numbering.
533void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
534 // Renumber the MBB's to keep them consequtive.
535 NewBB->getParent()->RenumberBlocks(NewBB);
536
537 // Insert a size into BBSizes to align it properly with the (newly
538 // renumbered) block numbers.
539 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000540
541 // Likewise for BBOffsets.
542 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Evan Chenga8e29892007-01-19 07:51:42 +0000543
544 // Next, update WaterList. Specifically, we need to add NewMBB as having
545 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000546 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000547 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
548 CompareMBBNumbers);
549 WaterList.insert(IP, NewBB);
550}
551
552
553/// Split the basic block containing MI into two blocks, which are joined by
554/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000555/// account for this change and returns the newly created block.
556MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000557 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000558 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000559
560 // Create a new MBB for the code after the OrigBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000561 MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000562 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000563 MF.insert(MBBI, NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000564
565 // Splice the instructions starting with MI over to NewBB.
566 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
567
568 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000569 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000570 // There doesn't seem to be meaningful DebugInfo available; this doesn't
571 // correspond to anything in the source.
572 BuildMI(OrigBB, DebugLoc::getUnknownLoc(),
573 TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000574 NumSplit++;
575
576 // Update the CFG. All succs of OrigBB are now succs of NewBB.
577 while (!OrigBB->succ_empty()) {
578 MachineBasicBlock *Succ = *OrigBB->succ_begin();
579 OrigBB->removeSuccessor(Succ);
580 NewBB->addSuccessor(Succ);
581
582 // This pass should be run after register allocation, so there should be no
583 // PHI nodes to update.
584 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
585 && "PHI nodes should be eliminated by now!");
586 }
587
588 // OrigBB branches to NewBB.
589 OrigBB->addSuccessor(NewBB);
590
591 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000592 // This is almost the same as UpdateForInsertedWaterBlock, except that
593 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000594 MF.RenumberBlocks(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000595
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000596 // Insert a size into BBSizes to align it properly with the (newly
597 // renumbered) block numbers.
598 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
599
Dale Johannesen99c49a42007-02-25 00:47:03 +0000600 // Likewise for BBOffsets.
601 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
602
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000603 // Next, update WaterList. Specifically, we need to add OrigMBB as having
604 // available water after it (but not if it's already there, which happens
605 // when splitting before a conditional branch that is followed by an
606 // unconditional branch - in that case we want to insert NewBB).
607 std::vector<MachineBasicBlock*>::iterator IP =
608 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
609 CompareMBBNumbers);
610 MachineBasicBlock* WaterBB = *IP;
611 if (WaterBB == OrigBB)
612 WaterList.insert(next(IP), NewBB);
613 else
614 WaterList.insert(IP, OrigBB);
615
Dale Johannesen8593e412007-04-29 19:19:30 +0000616 // Figure out how large the first NewMBB is. (It cannot
617 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000618 unsigned NewBBSize = 0;
619 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
620 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000621 NewBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000622
Dale Johannesen99c49a42007-02-25 00:47:03 +0000623 unsigned OrigBBI = OrigBB->getNumber();
624 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000625 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000626 BBSizes[NewBBI] = NewBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000627
628 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000629 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000630 unsigned delta = isThumb ? 2 : 4;
631 BBSizes[OrigBBI] -= NewBBSize - delta;
632
633 // ...and adjust BBOffsets for NewBB accordingly.
634 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
635
636 // All BBOffsets following these blocks must be modified.
637 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000638
639 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000640}
641
Dale Johannesen8593e412007-04-29 19:19:30 +0000642/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
643/// reference) is within MaxDisp of TrialOffset (a proposed location of a
644/// constant pool entry).
Dale Johannesen99c49a42007-02-25 00:47:03 +0000645bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
646 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000647 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
648 // purposes of the displacement computation; compensate for that here.
649 // Effectively, the valid range of displacements is 2 bytes smaller for such
650 // references.
651 if (isThumb && UserOffset%4 !=0)
652 UserOffset -= 2;
653 // CPEs will be rounded up to a multiple of 4.
654 if (isThumb && TrialOffset%4 != 0)
655 TrialOffset += 2;
656
Dale Johannesen99c49a42007-02-25 00:47:03 +0000657 if (UserOffset <= TrialOffset) {
658 // User before the Trial.
659 if (TrialOffset-UserOffset <= MaxDisp)
660 return true;
661 } else if (NegativeOK) {
662 if (UserOffset-TrialOffset <= MaxDisp)
663 return true;
664 }
665 return false;
666}
667
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000668/// WaterIsInRange - Returns true if a CPE placed after the specified
669/// Water (a basic block) will be in range for the specific MI.
670
671bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000672 MachineBasicBlock* Water, CPUser &U)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000673{
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000674 unsigned MaxDisp = U.MaxDisp;
Dale Johannesen8593e412007-04-29 19:19:30 +0000675 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Dale Johannesen99c49a42007-02-25 00:47:03 +0000676 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000677 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000678
Dale Johannesend959aa42007-04-02 20:31:06 +0000679 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000680 // the offset of the instruction. (Currently applies only to ARM, so
681 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000682 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000683 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000684
Dale Johannesen99c49a42007-02-25 00:47:03 +0000685 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000686}
687
688/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000689/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000690bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
691 MachineInstr *CPEMI,
692 unsigned MaxDisp, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000693 unsigned CPEOffset = GetOffsetOf(CPEMI);
694 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000695
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000696 if (DoDump) {
697 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
698 << " max delta=" << MaxDisp
699 << " insn address=" << UserOffset
700 << " CPE address=" << CPEOffset
701 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
702 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000703
Dale Johannesen99c49a42007-02-25 00:47:03 +0000704 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000705}
706
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000707#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000708/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
709/// unconditionally branches to its only successor.
710static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
711 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
712 return false;
713
714 MachineBasicBlock *Succ = *MBB->succ_begin();
715 MachineBasicBlock *Pred = *MBB->pred_begin();
716 MachineInstr *PredMI = &Pred->back();
717 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
718 return PredMI->getOperand(0).getMBB() == Succ;
719 return false;
720}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000721#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000722
Dale Johannesen8593e412007-04-29 19:19:30 +0000723void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
724 int delta) {
725 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
726 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000727 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000728 // If some existing blocks have padding, adjust the padding as needed, a
729 // bit tricky. delta can be negative so don't use % on that.
730 if (isThumb) {
731 MachineBasicBlock *MBB = MBBI;
732 if (!MBB->empty()) {
733 // Constant pool entries require padding.
734 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
735 unsigned oldOffset = BBOffsets[i] - delta;
736 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
737 // add new padding
738 BBSizes[i] += 2;
739 delta += 2;
740 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
741 // remove existing padding
742 BBSizes[i] -=2;
743 delta -= 2;
744 }
745 }
Dale Johannesen66a2a8f2007-07-12 16:45:35 +0000746 // Thumb jump tables require padding. They should be at the end;
747 // following unconditional branches are removed by AnalyzeBranch.
Dale Johannesen8593e412007-04-29 19:19:30 +0000748 MachineInstr *ThumbJTMI = NULL;
749 if (prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
750 ThumbJTMI = prior(MBB->end());
Dale Johannesen8593e412007-04-29 19:19:30 +0000751 if (ThumbJTMI) {
752 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
753 unsigned oldMIOffset = newMIOffset - delta;
754 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
755 // remove existing padding
756 BBSizes[i] -= 2;
757 delta -= 2;
758 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
759 // add new padding
760 BBSizes[i] += 2;
761 delta += 2;
762 }
763 }
764 if (delta==0)
765 return;
766 }
767 MBBI = next(MBBI);
768 }
769 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000770}
771
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000772/// DecrementOldEntry - find the constant pool entry with index CPI
773/// and instruction CPEMI, and decrement its refcount. If the refcount
774/// becomes 0 remove the entry and instruction. Returns true if we removed
775/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000776
Evan Chenged884f32007-04-03 23:39:48 +0000777bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000778 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000779 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
780 assert(CPE && "Unexpected!");
781 if (--CPE->RefCount == 0) {
782 RemoveDeadCPEMI(CPEMI);
783 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000784 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000785 return true;
786 }
787 return false;
788}
789
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000790/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
791/// if not, see if an in-range clone of the CPE is in range, and if so,
792/// change the data structures so the user references the clone. Returns:
793/// 0 = no existing entry found
794/// 1 = entry found, and there were no code insertions or deletions
795/// 2 = entry found, and there were code insertions or deletions
796int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
797{
798 MachineInstr *UserMI = U.MI;
799 MachineInstr *CPEMI = U.CPEMI;
800
801 // Check to see if the CPE is already in-range.
Evan Cheng82020102007-07-10 22:00:16 +0000802 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
803 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000804 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000805 }
806
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000807 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000808 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000809 std::vector<CPEntry> &CPEs = CPEntries[CPI];
810 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
811 // We already tried this one
812 if (CPEs[i].CPEMI == CPEMI)
813 continue;
814 // Removing CPEs can leave empty entries, skip
815 if (CPEs[i].CPEMI == NULL)
816 continue;
817 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
818 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
819 // Point the CPUser node to the replacement
820 U.CPEMI = CPEs[i].CPEMI;
821 // Change the CPI in the instruction operand to refer to the clone.
822 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000823 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000824 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000825 break;
826 }
827 // Adjust the refcount of the clone...
828 CPEs[i].RefCount++;
829 // ...and the original. If we didn't remove the old entry, none of the
830 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000831 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000832 }
833 }
834 return 0;
835}
836
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000837/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
838/// the specific unconditional branch instruction.
839static inline unsigned getUnconditionalBrDisp(int Opc) {
840 return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
841}
842
Dale Johannesen8593e412007-04-29 19:19:30 +0000843/// AcceptWater - Small amount of common code factored out of the following.
844
845MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
846 std::vector<MachineBasicBlock*>::iterator IP) {
847 DOUT << "found water in range\n";
848 // Remove the original WaterList entry; we want subsequent
849 // insertions in this vicinity to go after the one we're
850 // about to insert. This considerably reduces the number
851 // of times we have to move the same CPE more than once.
852 WaterList.erase(IP);
853 // CPE goes before following block (NewMBB).
854 return next(MachineFunction::iterator(WaterBB));
855}
856
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000857/// LookForWater - look for an existing entry in the WaterList in which
858/// we can place the CPE referenced from U so it's within range of U's MI.
859/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000860/// is set to the WaterList entry.
861/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
862/// water that will not introduce padding to water that will; within each
863/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000864
865bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000866 MachineBasicBlock** NewMBB) {
867 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
868 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000869 if (!WaterList.empty()) {
870 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
871 B = WaterList.begin();; --IP) {
872 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000873 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000874 if (isThumb &&
875 (BBOffsets[WaterBB->getNumber()] +
876 BBSizes[WaterBB->getNumber()])%4 != 0) {
877 // This is valid Water, but would introduce padding. Remember
878 // it in case we don't find any Water that doesn't do this.
879 if (!WaterBBThatWouldPad) {
880 WaterBBThatWouldPad = WaterBB;
881 IPThatWouldPad = IP;
882 }
883 } else {
884 *NewMBB = AcceptWater(WaterBB, IP);
885 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000886 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000887 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000888 if (IP == B)
889 break;
890 }
891 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000892 if (isThumb && WaterBBThatWouldPad) {
893 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
894 return true;
895 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000896 return false;
897}
898
899/// CreateNewWater - No existing WaterList entry will work for
900/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
901/// block is used if in range, and the conditional branch munged so control
902/// flow is correct. Otherwise the block is split to create a hole with an
903/// unconditional branch around it. In either case *NewMBB is set to a
904/// block following which the new island can be inserted (the WaterList
905/// is not adjusted).
906
907void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
908 unsigned UserOffset, MachineBasicBlock** NewMBB) {
909 CPUser &U = CPUsers[CPUserIndex];
910 MachineInstr *UserMI = U.MI;
911 MachineInstr *CPEMI = U.CPEMI;
912 MachineBasicBlock *UserMBB = UserMI->getParent();
913 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
914 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000915 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000916
917 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000918 // is within range, make new water there. (The addition below is
919 // for the unconditional branch we will be adding: 4 bytes on ARM,
920 // 2 on Thumb. Possible Thumb alignment padding is allowed for
921 // inside OffsetIsInRange.
922 // If the block ends in an unconditional branch already, it is water,
923 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000924 if (&UserMBB->back() == UserMI ||
Dale Johannesen8593e412007-04-29 19:19:30 +0000925 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
926 U.MaxDisp, !isThumb)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000927 DOUT << "Split at end of block\n";
928 if (&UserMBB->back() == UserMI)
929 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
930 *NewMBB = next(MachineFunction::iterator(UserMBB));
931 // Add an unconditional branch from UserMBB to fallthrough block.
932 // Record it for branch lengthening; this new branch will not get out of
933 // range, but if the preceding conditional branch is out of range, the
934 // targets will be exchanged, and the altered branch may be out of
935 // range, so the machinery has to know about it.
936 int UncondBr = isThumb ? ARM::tB : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +0000937 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
938 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000939 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
940 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
941 MaxDisp, false, UncondBr));
942 int delta = isThumb ? 2 : 4;
943 BBSizes[UserMBB->getNumber()] += delta;
944 AdjustBBOffsetsAfter(UserMBB, delta);
945 } else {
946 // What a big block. Find a place within the block to split it.
947 // This is a little tricky on Thumb since instructions are 2 bytes
948 // and constant pool entries are 4 bytes: if instruction I references
949 // island CPE, and instruction I+1 references CPE', it will
950 // not work well to put CPE as far forward as possible, since then
951 // CPE' cannot immediately follow it (that location is 2 bytes
952 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +0000953 // a new island. So, we make a first guess, then walk through the
954 // instructions between the one currently being looked at and the
955 // possible insertion point, and make sure any other instructions
956 // that reference CPEs will be able to use the same island area;
957 // if not, we back up the insertion point.
958
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000959 // The 4 in the following is for the unconditional branch we'll be
Dale Johannesen8593e412007-04-29 19:19:30 +0000960 // inserting (allows for long branch on Thumb). Alignment of the
961 // island is handled inside OffsetIsInRange.
962 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000963 // This could point off the end of the block if we've already got
964 // constant pool entries following this block; only the last one is
965 // in the water list. Back past any possible branches (allow for a
966 // conditional and a maximally long unconditional).
967 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
968 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
969 (isThumb ? 6 : 8);
970 unsigned EndInsertOffset = BaseInsertOffset +
971 CPEMI->getOperand(2).getImm();
972 MachineBasicBlock::iterator MI = UserMI;
973 ++MI;
974 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000975 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000976 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000977 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000978 MI = next(MI)) {
979 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
980 if (!OffsetIsInRange(Offset, EndInsertOffset,
981 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
982 BaseInsertOffset -= (isThumb ? 2 : 4);
983 EndInsertOffset -= (isThumb ? 2 : 4);
984 }
985 // This is overly conservative, as we don't account for CPEMIs
986 // being reused within the block, but it doesn't matter much.
987 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
988 CPUIndex++;
989 }
990 }
991 DOUT << "Split in middle of big block\n";
992 *NewMBB = SplitBlockBeforeInstr(prior(MI));
993 }
994}
995
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000996/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
997/// is out-of-range. If so, pick it up the constant pool value and move it some
998/// place in-range. Return true if we changed any addresses (thus must run
999/// another pass of branch lengthening), false otherwise.
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001000bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1001 unsigned CPUserIndex){
1002 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001003 MachineInstr *UserMI = U.MI;
1004 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001005 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001006 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001007 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001008 // Compute this only once, it's expensive. The 4 or 8 is the value the
1009 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001010 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001011
Evan Cheng185ea1e2007-04-27 18:27:13 +00001012 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1013 // second instruction.
1014 if (UserMI->getOpcode() == ARM::tLEApcrel)
Evan Cheng768c9f72007-04-27 08:14:15 +00001015 UserOffset += 2;
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001016
1017 // See if the current entry is within range, or there is a clone of it
1018 // in range.
1019 int result = LookForExistingCPEntry(U, UserOffset);
1020 if (result==1) return false;
1021 else if (result==2) return true;
1022
1023 // No existing clone of this CPE is within range.
1024 // We will be generating a new clone. Get a UID for it.
Evan Chengf1bbb952008-11-08 00:51:41 +00001025 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001026
1027 // Look for water where we can place this CPE. We look for the farthest one
1028 // away that will work. Forward references only for now (although later
1029 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001030
Dale Johannesen8593e412007-04-29 19:19:30 +00001031 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001032 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001033 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001034 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001035 }
1036
1037 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001038 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1039 Fn.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001040
1041 // Update internal data structures to account for the newly inserted MBB.
1042 UpdateForInsertedWaterBlock(NewIsland);
1043
1044 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001045 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001046
1047 // Now that we have an island to add the CPE to, clone the original CPE and
1048 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001049 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1050 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001051 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001052 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001053 NumCPEs++;
1054
Dale Johannesen8593e412007-04-29 19:19:30 +00001055 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001056 // Compensate for .align 2 in thumb mode.
Dale Johannesen8593e412007-04-29 19:19:30 +00001057 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1058 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001059 // Increase the size of the island block to account for the new entry.
1060 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001061 AdjustBBOffsetsAfter(NewIsland, Size);
Evan Chenga8e29892007-01-19 07:51:42 +00001062
1063 // Finally, change the CPI in the instruction operand to be ID.
1064 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001065 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001066 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001067 break;
1068 }
1069
Evan Chengc99ef082007-02-09 20:54:44 +00001070 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Evan Chenga8e29892007-01-19 07:51:42 +00001071
1072 return true;
1073}
1074
Evan Chenged884f32007-04-03 23:39:48 +00001075/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1076/// sizes and offsets of impacted basic blocks.
1077void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1078 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001079 unsigned Size = CPEMI->getOperand(2).getImm();
1080 CPEMI->eraseFromParent();
1081 BBSizes[CPEBB->getNumber()] -= Size;
1082 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001083 if (CPEBB->empty()) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001084 // In thumb mode, the size of island may be padded by two to compensate for
1085 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001086 // empty, so fix this.
1087 // All succeeding offsets have the current size value added in, fix this.
1088 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001089 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001090 BBSizes[CPEBB->getNumber()] = 0;
1091 }
Evan Chenged884f32007-04-03 23:39:48 +00001092 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001093 AdjustBBOffsetsAfter(CPEBB, -Size);
1094 // An island has only one predecessor BB and one successor BB. Check if
1095 // this BB's predecessor jumps directly to this BB's successor. This
1096 // shouldn't happen currently.
1097 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1098 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001099}
1100
1101/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1102/// are zero.
1103bool ARMConstantIslands::RemoveUnusedCPEntries() {
1104 unsigned MadeChange = false;
1105 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1106 std::vector<CPEntry> &CPEs = CPEntries[i];
1107 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1108 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1109 RemoveDeadCPEMI(CPEs[j].CPEMI);
1110 CPEs[j].CPEMI = NULL;
1111 MadeChange = true;
1112 }
1113 }
1114 }
1115 return MadeChange;
1116}
1117
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001118/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001119/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001120bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1121 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001122 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001123 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001124 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001125
Evan Chengc99ef082007-02-09 20:54:44 +00001126 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1127 << " from BB#" << MI->getParent()->getNumber()
1128 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001129 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1130 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001131
Dale Johannesen8593e412007-04-29 19:19:30 +00001132 if (BrOffset <= DestOffset) {
1133 // Branch before the Dest.
1134 if (DestOffset-BrOffset <= MaxDisp)
1135 return true;
1136 } else {
1137 if (BrOffset-DestOffset <= MaxDisp)
1138 return true;
1139 }
1140 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001141}
1142
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001143/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1144/// away to fit in its displacement field.
1145bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001146 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001147 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001148
Evan Chengc0dbec72007-01-31 19:57:44 +00001149 // Check to see if the DestBB is already in-range.
1150 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001151 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001152
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001153 if (!Br.isCond)
1154 return FixUpUnconditionalBr(Fn, Br);
1155 return FixUpConditionalBr(Fn, Br);
1156}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001157
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001158/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1159/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001160/// spilled in the epilogue, then we can use BL to implement a far jump.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001161/// Otherwise, add an intermediate branch instruction to to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001162bool
1163ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1164 MachineInstr *MI = Br.MI;
1165 MachineBasicBlock *MBB = MI->getParent();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001166 assert(isThumb && "Expected a Thumb function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001167
1168 // Use BL to implement far jump.
1169 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001170 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001171 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001172 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001173 HasFarJump = true;
1174 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001175
Evan Chengc99ef082007-02-09 20:54:44 +00001176 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001177
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001178 return true;
1179}
1180
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001181/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001182/// far away to fit in its displacement field. It is converted to an inverse
1183/// conditional branch + an unconditional branch to the destination.
1184bool
1185ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1186 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001187 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001188
1189 // Add a unconditional branch to the destination and invert the branch
1190 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001191 // blt L1
1192 // =>
1193 // bge L2
1194 // b L1
1195 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001196 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001197 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001198 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001199
1200 // If the branch is at the end of its MBB and that has a fall-through block,
1201 // direct the updated conditional branch to the fall-through block. Otherwise,
1202 // split the MBB before the next instruction.
1203 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001204 MachineInstr *BMI = &MBB->back();
1205 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001206
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001207 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001208 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001209 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001210 BMI->getOpcode() == Br.UncondBr) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001211 // Last MI in the BB is a unconditional branch. Can we simply invert the
1212 // condition and swap destinations:
1213 // beq L1
1214 // b L2
1215 // =>
1216 // bne L2
1217 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001218 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001219 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001220 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001221 BMI->getOperand(0).setMBB(DestBB);
1222 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001223 MI->getOperand(1).setImm(CC);
1224 return true;
1225 }
1226 }
1227 }
1228
1229 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001230 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +00001231 // No need for the branch to the next block. We're adding a unconditional
1232 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001233 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001234 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001235 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1236 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001237 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001238 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001239 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001240 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Evan Chengbd5d3db2007-02-03 02:08:34 +00001241
Evan Chengc99ef082007-02-09 20:54:44 +00001242 DOUT << " Insert B to BB#" << DestBB->getNumber()
1243 << " also invert condition and change dest. to BB#"
1244 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001245
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001246 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001247 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001248 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1249 TII->get(MI->getOpcode()))
1250 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001251 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001252 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001253 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001254 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001255 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001256 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001257
1258 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001259 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001260 MI->eraseFromParent();
1261
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001262 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001263 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001264 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001265 return true;
1266}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001267
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001268/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1269/// LR / restores LR to pc.
1270bool ARMConstantIslands::UndoLRSpillRestore() {
1271 bool MadeChange = false;
1272 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1273 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001274 if (MI->getOpcode() == ARM::tPOP_RET &&
1275 MI->getOperand(0).getReg() == ARM::PC &&
1276 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001277 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001278 MI->eraseFromParent();
1279 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001280 }
1281 }
1282 return MadeChange;
1283}