blob: 9fedaa465434a80bb50574a784bb4b5da7c95159 [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;
Bob Wilson84945262009-05-12 17:09:30 +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 };
Bob Wilson84945262009-05-12 17:09:30 +000076
Evan Chenga8e29892007-01-19 07:51:42 +000077 /// 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;
Bob Wilson84945262009-05-12 17:09:30 +000080
Evan Chengc99ef082007-02-09 20:54:44 +000081 /// 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;
Bob Wilson84945262009-05-12 17:09:30 +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;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000127 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000128 public:
Devang Patel19974732007-05-03 01:11:54 +0000129 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000130 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000131
Evan Chenga8e29892007-01-19 07:51:42 +0000132 virtual bool runOnMachineFunction(MachineFunction &Fn);
133
134 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000135 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000136 }
Bob Wilson84945262009-05-12 17:09:30 +0000137
Evan Chenga8e29892007-01-19 07:51:42 +0000138 private:
139 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000140 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000141 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000142 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000143 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000144 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000145 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000146 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000147 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000148 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000149 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000150 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000151 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000152 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000153 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
154 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000155 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000156 void RemoveDeadCPEMI(MachineInstr *CPEMI);
157 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000158 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000159 MachineInstr *CPEMI, unsigned Disp,
160 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000161 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000162 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000163 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
164 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000165 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000166 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
167 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
168 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
169 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000170
Evan Chenga8e29892007-01-19 07:51:42 +0000171 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000172 void dumpBBs();
173 void verify(MachineFunction &Fn);
Evan Chenga8e29892007-01-19 07:51:42 +0000174 };
Devang Patel19974732007-05-03 01:11:54 +0000175 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000176}
177
Dale Johannesen8593e412007-04-29 19:19:30 +0000178/// verify - check BBOffsets, BBSizes, alignment of islands
179void ARMConstantIslands::verify(MachineFunction &Fn) {
180 assert(BBOffsets.size() == BBSizes.size());
181 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
182 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
183 if (isThumb) {
184 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
185 MBBI != E; ++MBBI) {
186 MachineBasicBlock *MBB = MBBI;
187 if (!MBB->empty() &&
188 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
189 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
190 BBSizes[MBB->getNumber()]%4 == 0) ||
191 (BBOffsets[MBB->getNumber()]%4 != 0 &&
192 BBSizes[MBB->getNumber()]%4 != 0));
193 }
194 }
195}
196
197/// print block size and offset information - debugging
198void ARMConstantIslands::dumpBBs() {
199 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000200 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000201 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000202 }
203}
204
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000205/// createARMConstantIslandPass - returns an instance of the constpool
206/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000207FunctionPass *llvm::createARMConstantIslandPass() {
208 return new ARMConstantIslands();
209}
210
211bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000212 MachineConstantPool &MCP = *Fn.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000213
Evan Chenga8e29892007-01-19 07:51:42 +0000214 TII = Fn.getTarget().getInstrInfo();
Dale Johannesen8593e412007-04-29 19:19:30 +0000215 AFI = Fn.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000216 isThumb = AFI->isThumbFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000217 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000218
219 HasFarJump = false;
220
Evan Chenga8e29892007-01-19 07:51:42 +0000221 // Renumber all of the machine basic blocks in the function, guaranteeing that
222 // the numbers agree with the position of the block in the function.
223 Fn.RenumberBlocks();
224
Bob Wilson84945262009-05-12 17:09:30 +0000225 /// Thumb functions containing constant pools get 2-byte alignment.
226 /// This is so we can keep exact track of where the alignment padding goes.
227 /// Set default.
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000228 AFI->setAlign(isThumb ? 1U : 2U);
229
Evan Chenga8e29892007-01-19 07:51:42 +0000230 // Perform the initial placement of the constant pool entries. To start with,
231 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000232 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000233 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000234 DoInitialPlacement(Fn, CPEMIs);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000235 if (isThumb)
236 AFI->setAlign(2U);
237 }
Bob Wilson84945262009-05-12 17:09:30 +0000238
Evan Chenga8e29892007-01-19 07:51:42 +0000239 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000240 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000241
Evan Chenga8e29892007-01-19 07:51:42 +0000242 // Do the initial scan of the function, building up information about the
243 // sizes of each block, the location of all the water, and finding all of the
244 // constant pool users.
245 InitialFunctionScan(Fn, CPEMIs);
246 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000247
Evan Chenged884f32007-04-03 23:39:48 +0000248 /// Remove dead constant pool entries.
249 RemoveUnusedCPEntries();
250
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000251 // Iteratively place constant pool entries and fix up branches until there
252 // is no change.
253 bool MadeChange = false;
254 while (true) {
255 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000256 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000257 Change |= HandleConstantPoolUser(Fn, i);
Evan Cheng82020102007-07-10 22:00:16 +0000258 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000259 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000260 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000261 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000262 if (!Change)
263 break;
264 MadeChange = true;
265 }
Evan Chenged884f32007-04-03 23:39:48 +0000266
Dale Johannesen8593e412007-04-29 19:19:30 +0000267 // After a while, this might be made debug-only, but it is not expensive.
268 verify(Fn);
269
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000270 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
271 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000272 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000273 MadeChange |= UndoLRSpillRestore();
274
Evan Chenga8e29892007-01-19 07:51:42 +0000275 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000276 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000277 WaterList.clear();
278 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000279 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000280 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000281 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000282
283 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000284}
285
286/// DoInitialPlacement - Perform the initial placement of the constant pool
287/// entries. To start with, we put them all at the end of the function.
288void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Bob Wilson84945262009-05-12 17:09:30 +0000289 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000290 // Create the basic block to hold the CPE's.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000291 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
292 Fn.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000293
Evan Chenga8e29892007-01-19 07:51:42 +0000294 // Add all of the constants from the constant pool to the end block, use an
295 // identity mapping of CPI's to CPE's.
296 const std::vector<MachineConstantPoolEntry> &CPs =
297 Fn.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000298
Evan Chenga8e29892007-01-19 07:51:42 +0000299 const TargetData &TD = *Fn.getTarget().getTargetData();
300 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000301 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000302 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
303 // we would have to pad them out or something so that instructions stay
304 // aligned.
305 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
306 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000307 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000308 .addImm(i).addConstantPoolIndex(i).addImm(Size);
309 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000310
311 // Add a new CPEntry, but no corresponding CPUser yet.
312 std::vector<CPEntry> CPEs;
313 CPEs.push_back(CPEntry(CPEMI, i));
314 CPEntries.push_back(CPEs);
315 NumCPEs++;
316 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000317 }
318}
319
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000320/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000321/// into the block immediately after it.
322static bool BBHasFallthrough(MachineBasicBlock *MBB) {
323 // Get the next machine basic block in the function.
324 MachineFunction::iterator MBBI = MBB;
325 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
326 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000327
Evan Chenga8e29892007-01-19 07:51:42 +0000328 MachineBasicBlock *NextBB = next(MBBI);
329 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
330 E = MBB->succ_end(); I != E; ++I)
331 if (*I == NextBB)
332 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000333
Evan Chenga8e29892007-01-19 07:51:42 +0000334 return false;
335}
336
Evan Chengc99ef082007-02-09 20:54:44 +0000337/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
338/// look up the corresponding CPEntry.
339ARMConstantIslands::CPEntry
340*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
341 const MachineInstr *CPEMI) {
342 std::vector<CPEntry> &CPEs = CPEntries[CPI];
343 // Number of entries per constpool index should be small, just do a
344 // linear search.
345 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
346 if (CPEs[i].CPEMI == CPEMI)
347 return &CPEs[i];
348 }
349 return NULL;
350}
351
Evan Chenga8e29892007-01-19 07:51:42 +0000352/// InitialFunctionScan - Do the initial scan of the function, building up
353/// information about the sizes of each block, the location of all the water,
354/// and finding all of the constant pool users.
355void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000356 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000357 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000358 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
359 MBBI != E; ++MBBI) {
360 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000361
Evan Chenga8e29892007-01-19 07:51:42 +0000362 // If this block doesn't fall through into the next MBB, then this is
363 // 'water' that a constant pool island could be placed.
364 if (!BBHasFallthrough(&MBB))
365 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000366
Evan Chenga8e29892007-01-19 07:51:42 +0000367 unsigned MBBSize = 0;
368 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
369 I != E; ++I) {
370 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000371 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000372
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000373 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000374 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000375 bool isCond = false;
376 unsigned Bits = 0;
377 unsigned Scale = 1;
378 int UOpc = Opc;
379 switch (Opc) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000380 case ARM::tBR_JTr:
David Goodwin5e47a9a2009-06-30 18:04:13 +0000381 case ARM::t2BR_JTr:
David Goodwinc9a59b52009-06-30 19:50:22 +0000382 case ARM::t2BR_JTm:
383 case ARM::t2BR_JTadd:
Dale Johannesen8593e412007-04-29 19:19:30 +0000384 // A Thumb table jump may involve padding; for the offsets to
385 // be right, functions containing these must be 4-byte aligned.
386 AFI->setAlign(2U);
387 if ((Offset+MBBSize)%4 != 0)
388 MBBSize += 2; // padding
389 continue; // Does not get an entry in ImmBranches
Evan Cheng743fa032007-01-25 19:43:52 +0000390 default:
Dale Johannesen8593e412007-04-29 19:19:30 +0000391 continue; // Ignore other JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000392 case ARM::Bcc:
393 isCond = true;
394 UOpc = ARM::B;
395 // Fallthrough
396 case ARM::B:
397 Bits = 24;
398 Scale = 4;
399 break;
400 case ARM::tBcc:
401 isCond = true;
402 UOpc = ARM::tB;
403 Bits = 8;
404 Scale = 2;
405 break;
406 case ARM::tB:
407 Bits = 11;
408 Scale = 2;
409 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000410 case ARM::t2Bcc:
411 isCond = true;
412 UOpc = ARM::t2B;
413 Bits = 20;
414 Scale = 2;
415 break;
416 case ARM::t2B:
417 Bits = 24;
418 Scale = 2;
419 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000420 }
Evan Chengb43216e2007-02-01 10:16:15 +0000421
422 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000423 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000424 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000425 }
426
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000427 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
428 PushPopMIs.push_back(I);
429
Evan Chenga8e29892007-01-19 07:51:42 +0000430 // Scan the instructions for constant pool operands.
431 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000432 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000433 // We found one. The addressing mode tells us the max displacement
434 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000435
Evan Chenga8e29892007-01-19 07:51:42 +0000436 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000437 unsigned Bits = 0;
438 unsigned Scale = 1;
Chris Lattner749c6f62008-01-07 07:27:27 +0000439 unsigned TSFlags = I->getDesc().TSFlags;
Evan Chenga8e29892007-01-19 07:51:42 +0000440 switch (TSFlags & ARMII::AddrModeMask) {
Bob Wilson84945262009-05-12 17:09:30 +0000441 default:
Evan Chenga8e29892007-01-19 07:51:42 +0000442 // Constant pool entries can reach anything.
443 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
444 continue;
Evan Cheng768c9f72007-04-27 08:14:15 +0000445 if (I->getOpcode() == ARM::tLEApcrel) {
446 Bits = 8; // Taking the address of a CP entry.
447 break;
448 }
Evan Chenga8e29892007-01-19 07:51:42 +0000449 assert(0 && "Unknown addressing mode for CP reference!");
450 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000451 Bits = 8;
452 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000453 break;
454 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000455 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000456 break;
457 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000458 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000459 break;
460 // addrmode4 has no immediate offset.
461 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000462 Bits = 8;
463 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000464 break;
Bob Wilson8b024a52009-07-01 23:16:05 +0000465 // addrmode6 has no immediate offset.
Evan Cheng055b0312009-06-29 07:51:04 +0000466 case ARMII::AddrModeT1_1:
Evan Chengb43216e2007-02-01 10:16:15 +0000467 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000468 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000469 case ARMII::AddrModeT1_2:
Evan Chengb43216e2007-02-01 10:16:15 +0000470 Bits = 5;
471 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000472 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000473 case ARMII::AddrModeT1_4:
Evan Chengb43216e2007-02-01 10:16:15 +0000474 Bits = 5;
475 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000476 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000477 case ARMII::AddrModeT1_s:
Evan Chengb43216e2007-02-01 10:16:15 +0000478 Bits = 8;
479 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000480 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000481 case ARMII::AddrModeT2_pc:
482 Bits = 12; // +-offset_12
483 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000484 }
Evan Chengb43216e2007-02-01 10:16:15 +0000485
Evan Chenga8e29892007-01-19 07:51:42 +0000486 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000487 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000488 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilson84945262009-05-12 17:09:30 +0000489 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000490 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000491
492 // Increment corresponding CPEntry reference count.
493 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
494 assert(CPE && "Cannot find a corresponding CPEntry!");
495 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000496
Evan Chenga8e29892007-01-19 07:51:42 +0000497 // Instructions can only use one CP entry, don't bother scanning the
498 // rest of the operands.
499 break;
500 }
501 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000502
Dale Johannesen8593e412007-04-29 19:19:30 +0000503 // In thumb mode, if this block is a constpool island, we may need padding
504 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000505 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000506 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000507 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
508 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000509 MBBSize += 2;
510
Evan Chenga8e29892007-01-19 07:51:42 +0000511 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000512 BBOffsets.push_back(Offset);
513 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000514 }
515}
516
Evan Chenga8e29892007-01-19 07:51:42 +0000517/// GetOffsetOf - Return the current offset of the specified machine instruction
518/// from the start of the function. This offset changes as stuff is moved
519/// around inside the function.
520unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
521 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000522
Evan Chenga8e29892007-01-19 07:51:42 +0000523 // The offset is composed of two things: the sum of the sizes of all MBB's
524 // before this instruction's block, and the offset from the start of the block
525 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000526 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000527
Dale Johannesen8593e412007-04-29 19:19:30 +0000528 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
529 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000530 if (isThumb &&
531 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000532 Offset%4 != 0)
533 Offset += 2;
534
Evan Chenga8e29892007-01-19 07:51:42 +0000535 // Sum instructions before MI in MBB.
536 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
537 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
538 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000539 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000540 }
541}
542
543/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
544/// ID.
545static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
546 const MachineBasicBlock *RHS) {
547 return LHS->getNumber() < RHS->getNumber();
548}
549
550/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
551/// machine function, it upsets all of the block numbers. Renumber the blocks
552/// and update the arrays that parallel this numbering.
553void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
554 // Renumber the MBB's to keep them consequtive.
555 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000556
Evan Chenga8e29892007-01-19 07:51:42 +0000557 // Insert a size into BBSizes to align it properly with the (newly
558 // renumbered) block numbers.
559 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000560
561 // Likewise for BBOffsets.
562 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000563
564 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000565 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000566 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000567 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
568 CompareMBBNumbers);
569 WaterList.insert(IP, NewBB);
570}
571
572
573/// Split the basic block containing MI into two blocks, which are joined by
574/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000575/// account for this change and returns the newly created block.
576MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000577 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000578 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000579
580 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000581 MachineBasicBlock *NewBB =
582 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000583 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000584 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000585
Evan Chenga8e29892007-01-19 07:51:42 +0000586 // Splice the instructions starting with MI over to NewBB.
587 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000588
Evan Chenga8e29892007-01-19 07:51:42 +0000589 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000590 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000591 // There doesn't seem to be meaningful DebugInfo available; this doesn't
592 // correspond to anything in the source.
593 BuildMI(OrigBB, DebugLoc::getUnknownLoc(),
David Goodwin5e47a9a2009-06-30 18:04:13 +0000594 TII->get(isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000595 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000596
Evan Chenga8e29892007-01-19 07:51:42 +0000597 // Update the CFG. All succs of OrigBB are now succs of NewBB.
598 while (!OrigBB->succ_empty()) {
599 MachineBasicBlock *Succ = *OrigBB->succ_begin();
600 OrigBB->removeSuccessor(Succ);
601 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000602
Evan Chenga8e29892007-01-19 07:51:42 +0000603 // This pass should be run after register allocation, so there should be no
604 // PHI nodes to update.
605 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
606 && "PHI nodes should be eliminated by now!");
607 }
Bob Wilson84945262009-05-12 17:09:30 +0000608
Evan Chenga8e29892007-01-19 07:51:42 +0000609 // OrigBB branches to NewBB.
610 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000611
Evan Chenga8e29892007-01-19 07:51:42 +0000612 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000613 // This is almost the same as UpdateForInsertedWaterBlock, except that
614 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000615 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000616
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000617 // Insert a size into BBSizes to align it properly with the (newly
618 // renumbered) block numbers.
619 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000620
Dale Johannesen99c49a42007-02-25 00:47:03 +0000621 // Likewise for BBOffsets.
622 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
623
Bob Wilson84945262009-05-12 17:09:30 +0000624 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000625 // available water after it (but not if it's already there, which happens
626 // when splitting before a conditional branch that is followed by an
627 // unconditional branch - in that case we want to insert NewBB).
628 std::vector<MachineBasicBlock*>::iterator IP =
629 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
630 CompareMBBNumbers);
631 MachineBasicBlock* WaterBB = *IP;
632 if (WaterBB == OrigBB)
633 WaterList.insert(next(IP), NewBB);
634 else
635 WaterList.insert(IP, OrigBB);
636
Dale Johannesen8593e412007-04-29 19:19:30 +0000637 // Figure out how large the first NewMBB is. (It cannot
638 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000639 unsigned NewBBSize = 0;
640 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
641 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000642 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000643
Dale Johannesen99c49a42007-02-25 00:47:03 +0000644 unsigned OrigBBI = OrigBB->getNumber();
645 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000646 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000647 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000648
Evan Chenga8e29892007-01-19 07:51:42 +0000649 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000650 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000651 unsigned delta = isThumb ? 2 : 4;
652 BBSizes[OrigBBI] -= NewBBSize - delta;
653
654 // ...and adjust BBOffsets for NewBB accordingly.
655 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
656
657 // All BBOffsets following these blocks must be modified.
658 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000659
660 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000661}
662
Dale Johannesen8593e412007-04-29 19:19:30 +0000663/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000664/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000665/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000666bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000667 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Bob Wilson84945262009-05-12 17:09:30 +0000668 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
669 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000670 // Effectively, the valid range of displacements is 2 bytes smaller for such
671 // references.
672 if (isThumb && UserOffset%4 !=0)
673 UserOffset -= 2;
674 // CPEs will be rounded up to a multiple of 4.
675 if (isThumb && TrialOffset%4 != 0)
676 TrialOffset += 2;
677
Dale Johannesen99c49a42007-02-25 00:47:03 +0000678 if (UserOffset <= TrialOffset) {
679 // User before the Trial.
680 if (TrialOffset-UserOffset <= MaxDisp)
681 return true;
682 } else if (NegativeOK) {
683 if (UserOffset-TrialOffset <= MaxDisp)
684 return true;
685 }
686 return false;
687}
688
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000689/// WaterIsInRange - Returns true if a CPE placed after the specified
690/// Water (a basic block) will be in range for the specific MI.
691
692bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000693 MachineBasicBlock* Water, CPUser &U)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000694{
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000695 unsigned MaxDisp = U.MaxDisp;
Dale Johannesen8593e412007-04-29 19:19:30 +0000696 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Bob Wilson84945262009-05-12 17:09:30 +0000697 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000698 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000699
Dale Johannesend959aa42007-04-02 20:31:06 +0000700 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000701 // the offset of the instruction. (Currently applies only to ARM, so
702 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000703 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000704 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000705
Dale Johannesen99c49a42007-02-25 00:47:03 +0000706 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000707}
708
709/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000710/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000711bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
712 MachineInstr *CPEMI,
713 unsigned MaxDisp, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000714 unsigned CPEOffset = GetOffsetOf(CPEMI);
715 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000716
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000717 if (DoDump) {
718 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
719 << " max delta=" << MaxDisp
720 << " insn address=" << UserOffset
721 << " CPE address=" << CPEOffset
722 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
723 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000724
Dale Johannesen99c49a42007-02-25 00:47:03 +0000725 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000726}
727
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000728#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000729/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
730/// unconditionally branches to its only successor.
731static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
732 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
733 return false;
734
735 MachineBasicBlock *Succ = *MBB->succ_begin();
736 MachineBasicBlock *Pred = *MBB->pred_begin();
737 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000738 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
739 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000740 return PredMI->getOperand(0).getMBB() == Succ;
741 return false;
742}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000743#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000744
Bob Wilson84945262009-05-12 17:09:30 +0000745void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000746 int delta) {
747 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
748 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000749 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000750 // If some existing blocks have padding, adjust the padding as needed, a
751 // bit tricky. delta can be negative so don't use % on that.
752 if (isThumb) {
753 MachineBasicBlock *MBB = MBBI;
754 if (!MBB->empty()) {
755 // Constant pool entries require padding.
756 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
757 unsigned oldOffset = BBOffsets[i] - delta;
758 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
759 // add new padding
760 BBSizes[i] += 2;
761 delta += 2;
762 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
763 // remove existing padding
764 BBSizes[i] -=2;
765 delta -= 2;
766 }
767 }
Dale Johannesen66a2a8f2007-07-12 16:45:35 +0000768 // Thumb jump tables require padding. They should be at the end;
769 // following unconditional branches are removed by AnalyzeBranch.
Dale Johannesen8593e412007-04-29 19:19:30 +0000770 MachineInstr *ThumbJTMI = NULL;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000771 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
David Goodwinc9a59b52009-06-30 19:50:22 +0000772 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
773 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
774 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
Dale Johannesen8593e412007-04-29 19:19:30 +0000775 ThumbJTMI = prior(MBB->end());
Dale Johannesen8593e412007-04-29 19:19:30 +0000776 if (ThumbJTMI) {
777 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
778 unsigned oldMIOffset = newMIOffset - delta;
779 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
780 // remove existing padding
781 BBSizes[i] -= 2;
782 delta -= 2;
783 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
784 // add new padding
785 BBSizes[i] += 2;
786 delta += 2;
787 }
788 }
789 if (delta==0)
790 return;
791 }
792 MBBI = next(MBBI);
793 }
794 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000795}
796
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000797/// DecrementOldEntry - find the constant pool entry with index CPI
798/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000799/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000800/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000801
Evan Chenged884f32007-04-03 23:39:48 +0000802bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000803 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000804 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
805 assert(CPE && "Unexpected!");
806 if (--CPE->RefCount == 0) {
807 RemoveDeadCPEMI(CPEMI);
808 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000809 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000810 return true;
811 }
812 return false;
813}
814
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000815/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
816/// if not, see if an in-range clone of the CPE is in range, and if so,
817/// change the data structures so the user references the clone. Returns:
818/// 0 = no existing entry found
819/// 1 = entry found, and there were no code insertions or deletions
820/// 2 = entry found, and there were code insertions or deletions
821int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
822{
823 MachineInstr *UserMI = U.MI;
824 MachineInstr *CPEMI = U.CPEMI;
825
826 // Check to see if the CPE is already in-range.
Evan Cheng82020102007-07-10 22:00:16 +0000827 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
828 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000829 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000830 }
831
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000832 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000833 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000834 std::vector<CPEntry> &CPEs = CPEntries[CPI];
835 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
836 // We already tried this one
837 if (CPEs[i].CPEMI == CPEMI)
838 continue;
839 // Removing CPEs can leave empty entries, skip
840 if (CPEs[i].CPEMI == NULL)
841 continue;
842 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
843 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
844 // Point the CPUser node to the replacement
845 U.CPEMI = CPEs[i].CPEMI;
846 // Change the CPI in the instruction operand to refer to the clone.
847 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000848 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000849 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000850 break;
851 }
852 // Adjust the refcount of the clone...
853 CPEs[i].RefCount++;
854 // ...and the original. If we didn't remove the old entry, none of the
855 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000856 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000857 }
858 }
859 return 0;
860}
861
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000862/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
863/// the specific unconditional branch instruction.
864static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000865 switch (Opc) {
866 case ARM::tB:
867 return ((1<<10)-1)*2;
868 case ARM::t2B:
869 return ((1<<23)-1)*2;
870 default:
871 break;
872 }
873
874 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000875}
876
Dale Johannesen8593e412007-04-29 19:19:30 +0000877/// AcceptWater - Small amount of common code factored out of the following.
878
Bob Wilson84945262009-05-12 17:09:30 +0000879MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000880 std::vector<MachineBasicBlock*>::iterator IP) {
881 DOUT << "found water in range\n";
882 // Remove the original WaterList entry; we want subsequent
883 // insertions in this vicinity to go after the one we're
884 // about to insert. This considerably reduces the number
885 // of times we have to move the same CPE more than once.
886 WaterList.erase(IP);
887 // CPE goes before following block (NewMBB).
888 return next(MachineFunction::iterator(WaterBB));
889}
890
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000891/// LookForWater - look for an existing entry in the WaterList in which
892/// we can place the CPE referenced from U so it's within range of U's MI.
893/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000894/// is set to the WaterList entry.
895/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
896/// water that will not introduce padding to water that will; within each
897/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000898
899bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000900 MachineBasicBlock** NewMBB) {
901 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
902 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000903 if (!WaterList.empty()) {
904 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
905 B = WaterList.begin();; --IP) {
906 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000907 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000908 if (isThumb &&
Bob Wilson84945262009-05-12 17:09:30 +0000909 (BBOffsets[WaterBB->getNumber()] +
Dale Johannesen8593e412007-04-29 19:19:30 +0000910 BBSizes[WaterBB->getNumber()])%4 != 0) {
911 // This is valid Water, but would introduce padding. Remember
912 // it in case we don't find any Water that doesn't do this.
913 if (!WaterBBThatWouldPad) {
914 WaterBBThatWouldPad = WaterBB;
915 IPThatWouldPad = IP;
916 }
917 } else {
918 *NewMBB = AcceptWater(WaterBB, IP);
919 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000920 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000921 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000922 if (IP == B)
923 break;
924 }
925 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000926 if (isThumb && WaterBBThatWouldPad) {
927 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
928 return true;
929 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000930 return false;
931}
932
Bob Wilson84945262009-05-12 17:09:30 +0000933/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000934/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
935/// block is used if in range, and the conditional branch munged so control
936/// flow is correct. Otherwise the block is split to create a hole with an
937/// unconditional branch around it. In either case *NewMBB is set to a
938/// block following which the new island can be inserted (the WaterList
939/// is not adjusted).
940
Bob Wilson84945262009-05-12 17:09:30 +0000941void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000942 unsigned UserOffset, MachineBasicBlock** NewMBB) {
943 CPUser &U = CPUsers[CPUserIndex];
944 MachineInstr *UserMI = U.MI;
945 MachineInstr *CPEMI = U.CPEMI;
946 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000947 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000948 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000949 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000950
951 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000952 // is within range, make new water there. (The addition below is
953 // for the unconditional branch we will be adding: 4 bytes on ARM,
954 // 2 on Thumb. Possible Thumb alignment padding is allowed for
955 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000956 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000957 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000958 if (&UserMBB->back() == UserMI ||
Dale Johannesen8593e412007-04-29 19:19:30 +0000959 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
960 U.MaxDisp, !isThumb)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000961 DOUT << "Split at end of block\n";
962 if (&UserMBB->back() == UserMI)
963 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
964 *NewMBB = next(MachineFunction::iterator(UserMBB));
965 // Add an unconditional branch from UserMBB to fallthrough block.
966 // Record it for branch lengthening; this new branch will not get out of
967 // range, but if the preceding conditional branch is out of range, the
968 // targets will be exchanged, and the altered branch may be out of
969 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +0000970 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +0000971 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
972 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000973 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +0000974 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000975 MaxDisp, false, UncondBr));
976 int delta = isThumb ? 2 : 4;
977 BBSizes[UserMBB->getNumber()] += delta;
978 AdjustBBOffsetsAfter(UserMBB, delta);
979 } else {
980 // What a big block. Find a place within the block to split it.
981 // This is a little tricky on Thumb since instructions are 2 bytes
982 // and constant pool entries are 4 bytes: if instruction I references
983 // island CPE, and instruction I+1 references CPE', it will
984 // not work well to put CPE as far forward as possible, since then
985 // CPE' cannot immediately follow it (that location is 2 bytes
986 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +0000987 // a new island. So, we make a first guess, then walk through the
988 // instructions between the one currently being looked at and the
989 // possible insertion point, and make sure any other instructions
990 // that reference CPEs will be able to use the same island area;
991 // if not, we back up the insertion point.
992
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000993 // The 4 in the following is for the unconditional branch we'll be
Dale Johannesen8593e412007-04-29 19:19:30 +0000994 // inserting (allows for long branch on Thumb). Alignment of the
995 // island is handled inside OffsetIsInRange.
996 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000997 // This could point off the end of the block if we've already got
998 // constant pool entries following this block; only the last one is
999 // in the water list. Back past any possible branches (allow for a
1000 // conditional and a maximally long unconditional).
1001 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001002 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001003 (isThumb ? 6 : 8);
1004 unsigned EndInsertOffset = BaseInsertOffset +
1005 CPEMI->getOperand(2).getImm();
1006 MachineBasicBlock::iterator MI = UserMI;
1007 ++MI;
1008 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001009 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001010 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001011 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001012 MI = next(MI)) {
1013 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Bob Wilson84945262009-05-12 17:09:30 +00001014 if (!OffsetIsInRange(Offset, EndInsertOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001015 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1016 BaseInsertOffset -= (isThumb ? 2 : 4);
1017 EndInsertOffset -= (isThumb ? 2 : 4);
1018 }
1019 // This is overly conservative, as we don't account for CPEMIs
1020 // being reused within the block, but it doesn't matter much.
1021 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1022 CPUIndex++;
1023 }
1024 }
1025 DOUT << "Split in middle of big block\n";
1026 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1027 }
1028}
1029
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001030/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001031/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001032/// place in-range. Return true if we changed any addresses (thus must run
1033/// another pass of branch lengthening), false otherwise.
Bob Wilson84945262009-05-12 17:09:30 +00001034bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1035 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001036 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001037 MachineInstr *UserMI = U.MI;
1038 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001039 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001040 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001041 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001042 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilson39bf0512009-05-12 17:35:29 +00001043 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001044 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001045
Evan Cheng185ea1e2007-04-27 18:27:13 +00001046 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1047 // second instruction.
1048 if (UserMI->getOpcode() == ARM::tLEApcrel)
Evan Cheng768c9f72007-04-27 08:14:15 +00001049 UserOffset += 2;
Bob Wilson84945262009-05-12 17:09:30 +00001050
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001051 // See if the current entry is within range, or there is a clone of it
1052 // in range.
1053 int result = LookForExistingCPEntry(U, UserOffset);
1054 if (result==1) return false;
1055 else if (result==2) return true;
1056
1057 // No existing clone of this CPE is within range.
1058 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001059 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001060
1061 // Look for water where we can place this CPE. We look for the farthest one
1062 // away that will work. Forward references only for now (although later
1063 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001064
Dale Johannesen8593e412007-04-29 19:19:30 +00001065 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001066 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001067 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001068 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001069 }
1070
1071 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001072 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1073 Fn.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001074
1075 // Update internal data structures to account for the newly inserted MBB.
1076 UpdateForInsertedWaterBlock(NewIsland);
1077
1078 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001079 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001080
1081 // Now that we have an island to add the CPE to, clone the original CPE and
1082 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001083 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1084 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001085 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001086 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001087 NumCPEs++;
1088
Dale Johannesen8593e412007-04-29 19:19:30 +00001089 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001090 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001091 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001092 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001093 // Increase the size of the island block to account for the new entry.
1094 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001095 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001096
Evan Chenga8e29892007-01-19 07:51:42 +00001097 // Finally, change the CPI in the instruction operand to be ID.
1098 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001099 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001100 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001101 break;
1102 }
Bob Wilson84945262009-05-12 17:09:30 +00001103
Evan Chengc99ef082007-02-09 20:54:44 +00001104 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001105
Evan Chenga8e29892007-01-19 07:51:42 +00001106 return true;
1107}
1108
Evan Chenged884f32007-04-03 23:39:48 +00001109/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1110/// sizes and offsets of impacted basic blocks.
1111void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1112 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001113 unsigned Size = CPEMI->getOperand(2).getImm();
1114 CPEMI->eraseFromParent();
1115 BBSizes[CPEBB->getNumber()] -= Size;
1116 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001117 if (CPEBB->empty()) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001118 // In thumb mode, the size of island may be padded by two to compensate for
1119 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001120 // empty, so fix this.
1121 // All succeeding offsets have the current size value added in, fix this.
1122 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001123 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001124 BBSizes[CPEBB->getNumber()] = 0;
1125 }
Evan Chenged884f32007-04-03 23:39:48 +00001126 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001127 AdjustBBOffsetsAfter(CPEBB, -Size);
1128 // An island has only one predecessor BB and one successor BB. Check if
1129 // this BB's predecessor jumps directly to this BB's successor. This
1130 // shouldn't happen currently.
1131 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1132 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001133}
1134
1135/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1136/// are zero.
1137bool ARMConstantIslands::RemoveUnusedCPEntries() {
1138 unsigned MadeChange = false;
1139 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1140 std::vector<CPEntry> &CPEs = CPEntries[i];
1141 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1142 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1143 RemoveDeadCPEMI(CPEs[j].CPEMI);
1144 CPEs[j].CPEMI = NULL;
1145 MadeChange = true;
1146 }
1147 }
Bob Wilson84945262009-05-12 17:09:30 +00001148 }
Evan Chenged884f32007-04-03 23:39:48 +00001149 return MadeChange;
1150}
1151
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001152/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001153/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001154bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1155 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001156 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001157 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001158 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001159
Evan Chengc99ef082007-02-09 20:54:44 +00001160 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1161 << " from BB#" << MI->getParent()->getNumber()
1162 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001163 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1164 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001165
Dale Johannesen8593e412007-04-29 19:19:30 +00001166 if (BrOffset <= DestOffset) {
1167 // Branch before the Dest.
1168 if (DestOffset-BrOffset <= MaxDisp)
1169 return true;
1170 } else {
1171 if (BrOffset-DestOffset <= MaxDisp)
1172 return true;
1173 }
1174 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001175}
1176
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001177/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1178/// away to fit in its displacement field.
1179bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001180 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001181 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001182
Evan Chengc0dbec72007-01-31 19:57:44 +00001183 // Check to see if the DestBB is already in-range.
1184 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001185 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001186
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001187 if (!Br.isCond)
1188 return FixUpUnconditionalBr(Fn, Br);
1189 return FixUpConditionalBr(Fn, Br);
1190}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001191
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001192/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1193/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001194/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001195/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001196bool
1197ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1198 MachineInstr *MI = Br.MI;
1199 MachineBasicBlock *MBB = MI->getParent();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001200 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001201
1202 // Use BL to implement far jump.
1203 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001204 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001205 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001206 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001207 HasFarJump = true;
1208 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001209
Evan Chengc99ef082007-02-09 20:54:44 +00001210 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001211
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001212 return true;
1213}
1214
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001215/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001216/// far away to fit in its displacement field. It is converted to an inverse
1217/// conditional branch + an unconditional branch to the destination.
1218bool
1219ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1220 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001221 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001222
Bob Wilson39bf0512009-05-12 17:35:29 +00001223 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001224 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001225 // blt L1
1226 // =>
1227 // bge L2
1228 // b L1
1229 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001230 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001231 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001232 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001233
1234 // If the branch is at the end of its MBB and that has a fall-through block,
1235 // direct the updated conditional branch to the fall-through block. Otherwise,
1236 // split the MBB before the next instruction.
1237 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001238 MachineInstr *BMI = &MBB->back();
1239 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001240
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001241 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001242 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001243 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001244 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001245 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001246 // condition and swap destinations:
1247 // beq L1
1248 // b L2
1249 // =>
1250 // bne L2
1251 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001252 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001253 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001254 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001255 BMI->getOperand(0).setMBB(DestBB);
1256 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001257 MI->getOperand(1).setImm(CC);
1258 return true;
1259 }
1260 }
1261 }
1262
1263 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001264 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001265 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001266 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001267 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001268 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001269 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1270 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001271 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001272 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001273 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001274 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001275
Evan Chengc99ef082007-02-09 20:54:44 +00001276 DOUT << " Insert B to BB#" << DestBB->getNumber()
1277 << " also invert condition and change dest. to BB#"
1278 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001279
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001280 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001281 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001282 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1283 TII->get(MI->getOpcode()))
1284 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001285 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001286 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001287 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001288 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001289 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001290 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001291
1292 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001293 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001294 MI->eraseFromParent();
1295
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001296 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001297 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001298 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001299 return true;
1300}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001301
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001302/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1303/// LR / restores LR to pc.
1304bool ARMConstantIslands::UndoLRSpillRestore() {
1305 bool MadeChange = false;
1306 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1307 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001308 if (MI->getOpcode() == ARM::tPOP_RET &&
1309 MI->getOperand(0).getReg() == ARM::PC &&
1310 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001311 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001312 MI->eraseFromParent();
1313 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001314 }
1315 }
1316 return MadeChange;
1317}