blob: 34c9d70e6948a85c56befbfa30f2f5f53b49b42d [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 Goodwinf1daf7d2009-07-08 23:10:31 +0000127 bool isThumb1Only;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000128 bool isThumb2;
Evan Chenga8e29892007-01-19 07:51:42 +0000129 public:
Devang Patel19974732007-05-03 01:11:54 +0000130 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000131 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000132
Evan Chenga8e29892007-01-19 07:51:42 +0000133 virtual bool runOnMachineFunction(MachineFunction &Fn);
134
135 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000136 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000137 }
Bob Wilson84945262009-05-12 17:09:30 +0000138
Evan Chenga8e29892007-01-19 07:51:42 +0000139 private:
140 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000141 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000142 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000143 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000144 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000145 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000146 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000147 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000148 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000149 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000150 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000151 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000152 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000153 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000154 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
155 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000156 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000157 void RemoveDeadCPEMI(MachineInstr *CPEMI);
158 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000159 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000160 MachineInstr *CPEMI, unsigned Disp,
161 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000162 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000163 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000164 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
165 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000166 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000167 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
168 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
169 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
170 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000171
Evan Chenga8e29892007-01-19 07:51:42 +0000172 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000173 void dumpBBs();
174 void verify(MachineFunction &Fn);
Evan Chenga8e29892007-01-19 07:51:42 +0000175 };
Devang Patel19974732007-05-03 01:11:54 +0000176 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000177}
178
Dale Johannesen8593e412007-04-29 19:19:30 +0000179/// verify - check BBOffsets, BBSizes, alignment of islands
180void ARMConstantIslands::verify(MachineFunction &Fn) {
181 assert(BBOffsets.size() == BBSizes.size());
182 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
183 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
184 if (isThumb) {
185 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
186 MBBI != E; ++MBBI) {
187 MachineBasicBlock *MBB = MBBI;
188 if (!MBB->empty() &&
189 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
190 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
191 BBSizes[MBB->getNumber()]%4 == 0) ||
192 (BBOffsets[MBB->getNumber()]%4 != 0 &&
193 BBSizes[MBB->getNumber()]%4 != 0));
194 }
195 }
196}
197
198/// print block size and offset information - debugging
199void ARMConstantIslands::dumpBBs() {
200 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000201 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000202 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000203 }
204}
205
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000206/// createARMConstantIslandPass - returns an instance of the constpool
207/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000208FunctionPass *llvm::createARMConstantIslandPass() {
209 return new ARMConstantIslands();
210}
211
212bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000213 MachineConstantPool &MCP = *Fn.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000214
Evan Chenga8e29892007-01-19 07:51:42 +0000215 TII = Fn.getTarget().getInstrInfo();
Dale Johannesen8593e412007-04-29 19:19:30 +0000216 AFI = Fn.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000217 isThumb = AFI->isThumbFunction();
David Goodwinf1daf7d2009-07-08 23:10:31 +0000218 isThumb1Only = AFI->isThumb1OnlyFunction();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000219 isThumb2 = AFI->isThumb2Function();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000220
221 HasFarJump = false;
222
Evan Chenga8e29892007-01-19 07:51:42 +0000223 // Renumber all of the machine basic blocks in the function, guaranteeing that
224 // the numbers agree with the position of the block in the function.
225 Fn.RenumberBlocks();
226
Bob Wilson84945262009-05-12 17:09:30 +0000227 /// Thumb functions containing constant pools get 2-byte alignment.
228 /// This is so we can keep exact track of where the alignment padding goes.
229 /// Set default.
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000230 AFI->setAlign(isThumb ? 1U : 2U);
231
Evan Chenga8e29892007-01-19 07:51:42 +0000232 // Perform the initial placement of the constant pool entries. To start with,
233 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000234 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000235 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000236 DoInitialPlacement(Fn, CPEMIs);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000237 if (isThumb)
238 AFI->setAlign(2U);
239 }
Bob Wilson84945262009-05-12 17:09:30 +0000240
Evan Chenga8e29892007-01-19 07:51:42 +0000241 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000242 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000243
Evan Chenga8e29892007-01-19 07:51:42 +0000244 // Do the initial scan of the function, building up information about the
245 // sizes of each block, the location of all the water, and finding all of the
246 // constant pool users.
247 InitialFunctionScan(Fn, CPEMIs);
248 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000249
Evan Chenged884f32007-04-03 23:39:48 +0000250 /// Remove dead constant pool entries.
251 RemoveUnusedCPEntries();
252
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000253 // Iteratively place constant pool entries and fix up branches until there
254 // is no change.
255 bool MadeChange = false;
256 while (true) {
257 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000258 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000259 Change |= HandleConstantPoolUser(Fn, i);
Evan Cheng82020102007-07-10 22:00:16 +0000260 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000261 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000262 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000263 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000264 if (!Change)
265 break;
266 MadeChange = true;
267 }
Evan Chenged884f32007-04-03 23:39:48 +0000268
Dale Johannesen8593e412007-04-29 19:19:30 +0000269 // After a while, this might be made debug-only, but it is not expensive.
270 verify(Fn);
271
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000272 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
273 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000274 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000275 MadeChange |= UndoLRSpillRestore();
276
Evan Chenga8e29892007-01-19 07:51:42 +0000277 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000278 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000279 WaterList.clear();
280 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000281 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000282 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000283 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000284
285 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000286}
287
288/// DoInitialPlacement - Perform the initial placement of the constant pool
289/// entries. To start with, we put them all at the end of the function.
290void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Bob Wilson84945262009-05-12 17:09:30 +0000291 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000292 // Create the basic block to hold the CPE's.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000293 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
294 Fn.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000295
Evan Chenga8e29892007-01-19 07:51:42 +0000296 // Add all of the constants from the constant pool to the end block, use an
297 // identity mapping of CPI's to CPE's.
298 const std::vector<MachineConstantPoolEntry> &CPs =
299 Fn.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000300
Evan Chenga8e29892007-01-19 07:51:42 +0000301 const TargetData &TD = *Fn.getTarget().getTargetData();
302 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000303 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000304 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
305 // we would have to pad them out or something so that instructions stay
306 // aligned.
307 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
308 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000309 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000310 .addImm(i).addConstantPoolIndex(i).addImm(Size);
311 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000312
313 // Add a new CPEntry, but no corresponding CPUser yet.
314 std::vector<CPEntry> CPEs;
315 CPEs.push_back(CPEntry(CPEMI, i));
316 CPEntries.push_back(CPEs);
317 NumCPEs++;
318 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000319 }
320}
321
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000322/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000323/// into the block immediately after it.
324static bool BBHasFallthrough(MachineBasicBlock *MBB) {
325 // Get the next machine basic block in the function.
326 MachineFunction::iterator MBBI = MBB;
327 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
328 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000329
Evan Chenga8e29892007-01-19 07:51:42 +0000330 MachineBasicBlock *NextBB = next(MBBI);
331 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
332 E = MBB->succ_end(); I != E; ++I)
333 if (*I == NextBB)
334 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000335
Evan Chenga8e29892007-01-19 07:51:42 +0000336 return false;
337}
338
Evan Chengc99ef082007-02-09 20:54:44 +0000339/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
340/// look up the corresponding CPEntry.
341ARMConstantIslands::CPEntry
342*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
343 const MachineInstr *CPEMI) {
344 std::vector<CPEntry> &CPEs = CPEntries[CPI];
345 // Number of entries per constpool index should be small, just do a
346 // linear search.
347 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
348 if (CPEs[i].CPEMI == CPEMI)
349 return &CPEs[i];
350 }
351 return NULL;
352}
353
Evan Chenga8e29892007-01-19 07:51:42 +0000354/// InitialFunctionScan - Do the initial scan of the function, building up
355/// information about the sizes of each block, the location of all the water,
356/// and finding all of the constant pool users.
357void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000358 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000359 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000360 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
361 MBBI != E; ++MBBI) {
362 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000363
Evan Chenga8e29892007-01-19 07:51:42 +0000364 // If this block doesn't fall through into the next MBB, then this is
365 // 'water' that a constant pool island could be placed.
366 if (!BBHasFallthrough(&MBB))
367 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000368
Evan Chenga8e29892007-01-19 07:51:42 +0000369 unsigned MBBSize = 0;
370 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
371 I != E; ++I) {
372 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000373 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000374
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000375 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000376 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000377 bool isCond = false;
378 unsigned Bits = 0;
379 unsigned Scale = 1;
380 int UOpc = Opc;
381 switch (Opc) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000382 case ARM::tBR_JTr:
David Goodwin5e47a9a2009-06-30 18:04:13 +0000383 case ARM::t2BR_JTr:
David Goodwinc9a59b52009-06-30 19:50:22 +0000384 case ARM::t2BR_JTm:
385 case ARM::t2BR_JTadd:
Dale Johannesen8593e412007-04-29 19:19:30 +0000386 // A Thumb table jump may involve padding; for the offsets to
387 // be right, functions containing these must be 4-byte aligned.
388 AFI->setAlign(2U);
389 if ((Offset+MBBSize)%4 != 0)
390 MBBSize += 2; // padding
391 continue; // Does not get an entry in ImmBranches
Evan Cheng743fa032007-01-25 19:43:52 +0000392 default:
Dale Johannesen8593e412007-04-29 19:19:30 +0000393 continue; // Ignore other JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000394 case ARM::Bcc:
395 isCond = true;
396 UOpc = ARM::B;
397 // Fallthrough
398 case ARM::B:
399 Bits = 24;
400 Scale = 4;
401 break;
402 case ARM::tBcc:
403 isCond = true;
404 UOpc = ARM::tB;
405 Bits = 8;
406 Scale = 2;
407 break;
408 case ARM::tB:
409 Bits = 11;
410 Scale = 2;
411 break;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000412 case ARM::t2Bcc:
413 isCond = true;
414 UOpc = ARM::t2B;
415 Bits = 20;
416 Scale = 2;
417 break;
418 case ARM::t2B:
419 Bits = 24;
420 Scale = 2;
421 break;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000422 }
Evan Chengb43216e2007-02-01 10:16:15 +0000423
424 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000425 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000426 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000427 }
428
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000429 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
430 PushPopMIs.push_back(I);
431
Evan Chenga8e29892007-01-19 07:51:42 +0000432 // Scan the instructions for constant pool operands.
433 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000434 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000435 // We found one. The addressing mode tells us the max displacement
436 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000437
Evan Chenga8e29892007-01-19 07:51:42 +0000438 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000439 unsigned Bits = 0;
440 unsigned Scale = 1;
Chris Lattner749c6f62008-01-07 07:27:27 +0000441 unsigned TSFlags = I->getDesc().TSFlags;
Evan Chenga8e29892007-01-19 07:51:42 +0000442 switch (TSFlags & ARMII::AddrModeMask) {
Bob Wilson84945262009-05-12 17:09:30 +0000443 default:
Evan Chenga8e29892007-01-19 07:51:42 +0000444 // Constant pool entries can reach anything.
445 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
446 continue;
Evan Cheng768c9f72007-04-27 08:14:15 +0000447 if (I->getOpcode() == ARM::tLEApcrel) {
448 Bits = 8; // Taking the address of a CP entry.
449 break;
450 }
Evan Chenga8e29892007-01-19 07:51:42 +0000451 assert(0 && "Unknown addressing mode for CP reference!");
452 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000453 Bits = 8;
454 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000455 break;
456 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000457 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000458 break;
459 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000460 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000461 break;
462 // addrmode4 has no immediate offset.
463 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000464 Bits = 8;
465 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000466 break;
Bob Wilson8b024a52009-07-01 23:16:05 +0000467 // addrmode6 has no immediate offset.
Evan Cheng055b0312009-06-29 07:51:04 +0000468 case ARMII::AddrModeT1_1:
Evan Chengb43216e2007-02-01 10:16:15 +0000469 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000470 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000471 case ARMII::AddrModeT1_2:
Evan Chengb43216e2007-02-01 10:16:15 +0000472 Bits = 5;
473 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000474 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000475 case ARMII::AddrModeT1_4:
Evan Chengb43216e2007-02-01 10:16:15 +0000476 Bits = 5;
477 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000478 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000479 case ARMII::AddrModeT1_s:
Evan Chengb43216e2007-02-01 10:16:15 +0000480 Bits = 8;
481 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000482 break;
Evan Cheng055b0312009-06-29 07:51:04 +0000483 case ARMII::AddrModeT2_pc:
484 Bits = 12; // +-offset_12
485 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000486 }
Evan Chengb43216e2007-02-01 10:16:15 +0000487
Evan Chenga8e29892007-01-19 07:51:42 +0000488 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000489 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000490 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilson84945262009-05-12 17:09:30 +0000491 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000492 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000493
494 // Increment corresponding CPEntry reference count.
495 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
496 assert(CPE && "Cannot find a corresponding CPEntry!");
497 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000498
Evan Chenga8e29892007-01-19 07:51:42 +0000499 // Instructions can only use one CP entry, don't bother scanning the
500 // rest of the operands.
501 break;
502 }
503 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000504
Dale Johannesen8593e412007-04-29 19:19:30 +0000505 // In thumb mode, if this block is a constpool island, we may need padding
506 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000507 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000508 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000509 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
510 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000511 MBBSize += 2;
512
Evan Chenga8e29892007-01-19 07:51:42 +0000513 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000514 BBOffsets.push_back(Offset);
515 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000516 }
517}
518
Evan Chenga8e29892007-01-19 07:51:42 +0000519/// GetOffsetOf - Return the current offset of the specified machine instruction
520/// from the start of the function. This offset changes as stuff is moved
521/// around inside the function.
522unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
523 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000524
Evan Chenga8e29892007-01-19 07:51:42 +0000525 // The offset is composed of two things: the sum of the sizes of all MBB's
526 // before this instruction's block, and the offset from the start of the block
527 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000528 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000529
Dale Johannesen8593e412007-04-29 19:19:30 +0000530 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
531 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000532 if (isThumb &&
533 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000534 Offset%4 != 0)
535 Offset += 2;
536
Evan Chenga8e29892007-01-19 07:51:42 +0000537 // Sum instructions before MI in MBB.
538 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
539 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
540 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000541 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000542 }
543}
544
545/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
546/// ID.
547static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
548 const MachineBasicBlock *RHS) {
549 return LHS->getNumber() < RHS->getNumber();
550}
551
552/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
553/// machine function, it upsets all of the block numbers. Renumber the blocks
554/// and update the arrays that parallel this numbering.
555void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
556 // Renumber the MBB's to keep them consequtive.
557 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000558
Evan Chenga8e29892007-01-19 07:51:42 +0000559 // Insert a size into BBSizes to align it properly with the (newly
560 // renumbered) block numbers.
561 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000562
563 // Likewise for BBOffsets.
564 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000565
566 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000567 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000568 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000569 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
570 CompareMBBNumbers);
571 WaterList.insert(IP, NewBB);
572}
573
574
575/// Split the basic block containing MI into two blocks, which are joined by
576/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000577/// account for this change and returns the newly created block.
578MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000579 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000580 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000581
582 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000583 MachineBasicBlock *NewBB =
584 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000585 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000586 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000587
Evan Chenga8e29892007-01-19 07:51:42 +0000588 // Splice the instructions starting with MI over to NewBB.
589 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000590
Evan Chenga8e29892007-01-19 07:51:42 +0000591 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000592 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000593 // There doesn't seem to be meaningful DebugInfo available; this doesn't
594 // correspond to anything in the source.
Evan Cheng58541fd2009-07-07 01:16:41 +0000595 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
596 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000597 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000598
Evan Chenga8e29892007-01-19 07:51:42 +0000599 // Update the CFG. All succs of OrigBB are now succs of NewBB.
600 while (!OrigBB->succ_empty()) {
601 MachineBasicBlock *Succ = *OrigBB->succ_begin();
602 OrigBB->removeSuccessor(Succ);
603 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000604
Evan Chenga8e29892007-01-19 07:51:42 +0000605 // This pass should be run after register allocation, so there should be no
606 // PHI nodes to update.
607 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
608 && "PHI nodes should be eliminated by now!");
609 }
Bob Wilson84945262009-05-12 17:09:30 +0000610
Evan Chenga8e29892007-01-19 07:51:42 +0000611 // OrigBB branches to NewBB.
612 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000613
Evan Chenga8e29892007-01-19 07:51:42 +0000614 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000615 // This is almost the same as UpdateForInsertedWaterBlock, except that
616 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000617 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000618
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000619 // Insert a size into BBSizes to align it properly with the (newly
620 // renumbered) block numbers.
621 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000622
Dale Johannesen99c49a42007-02-25 00:47:03 +0000623 // Likewise for BBOffsets.
624 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
625
Bob Wilson84945262009-05-12 17:09:30 +0000626 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000627 // available water after it (but not if it's already there, which happens
628 // when splitting before a conditional branch that is followed by an
629 // unconditional branch - in that case we want to insert NewBB).
630 std::vector<MachineBasicBlock*>::iterator IP =
631 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
632 CompareMBBNumbers);
633 MachineBasicBlock* WaterBB = *IP;
634 if (WaterBB == OrigBB)
635 WaterList.insert(next(IP), NewBB);
636 else
637 WaterList.insert(IP, OrigBB);
638
Dale Johannesen8593e412007-04-29 19:19:30 +0000639 // Figure out how large the first NewMBB is. (It cannot
640 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000641 unsigned NewBBSize = 0;
642 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
643 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000644 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000645
Dale Johannesen99c49a42007-02-25 00:47:03 +0000646 unsigned OrigBBI = OrigBB->getNumber();
647 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000648 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000649 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000650
Evan Chenga8e29892007-01-19 07:51:42 +0000651 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000652 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000653 unsigned delta = isThumb ? 2 : 4;
654 BBSizes[OrigBBI] -= NewBBSize - delta;
655
656 // ...and adjust BBOffsets for NewBB accordingly.
657 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
658
659 // All BBOffsets following these blocks must be modified.
660 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000661
662 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000663}
664
Dale Johannesen8593e412007-04-29 19:19:30 +0000665/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000666/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000667/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000668bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000669 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Bob Wilson84945262009-05-12 17:09:30 +0000670 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
671 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000672 // Effectively, the valid range of displacements is 2 bytes smaller for such
673 // references.
674 if (isThumb && UserOffset%4 !=0)
675 UserOffset -= 2;
676 // CPEs will be rounded up to a multiple of 4.
677 if (isThumb && TrialOffset%4 != 0)
678 TrialOffset += 2;
679
Dale Johannesen99c49a42007-02-25 00:47:03 +0000680 if (UserOffset <= TrialOffset) {
681 // User before the Trial.
682 if (TrialOffset-UserOffset <= MaxDisp)
683 return true;
684 } else if (NegativeOK) {
685 if (UserOffset-TrialOffset <= MaxDisp)
686 return true;
687 }
688 return false;
689}
690
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000691/// WaterIsInRange - Returns true if a CPE placed after the specified
692/// Water (a basic block) will be in range for the specific MI.
693
694bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000695 MachineBasicBlock* Water, CPUser &U)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000696{
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000697 unsigned MaxDisp = U.MaxDisp;
Dale Johannesen8593e412007-04-29 19:19:30 +0000698 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Bob Wilson84945262009-05-12 17:09:30 +0000699 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000700 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000701
Dale Johannesend959aa42007-04-02 20:31:06 +0000702 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000703 // the offset of the instruction. (Currently applies only to ARM, so
704 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000705 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000706 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000707
Dale Johannesen99c49a42007-02-25 00:47:03 +0000708 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000709}
710
711/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000712/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000713bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
714 MachineInstr *CPEMI,
715 unsigned MaxDisp, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000716 unsigned CPEOffset = GetOffsetOf(CPEMI);
717 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000718
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000719 if (DoDump) {
720 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
721 << " max delta=" << MaxDisp
722 << " insn address=" << UserOffset
723 << " CPE address=" << CPEOffset
724 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
725 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000726
Dale Johannesen99c49a42007-02-25 00:47:03 +0000727 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000728}
729
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000730#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000731/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
732/// unconditionally branches to its only successor.
733static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
734 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
735 return false;
736
737 MachineBasicBlock *Succ = *MBB->succ_begin();
738 MachineBasicBlock *Pred = *MBB->pred_begin();
739 MachineInstr *PredMI = &Pred->back();
David Goodwin5e47a9a2009-06-30 18:04:13 +0000740 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
741 || PredMI->getOpcode() == ARM::t2B)
Evan Chengc99ef082007-02-09 20:54:44 +0000742 return PredMI->getOperand(0).getMBB() == Succ;
743 return false;
744}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000745#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000746
Bob Wilson84945262009-05-12 17:09:30 +0000747void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000748 int delta) {
749 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
750 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000751 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000752 // If some existing blocks have padding, adjust the padding as needed, a
753 // bit tricky. delta can be negative so don't use % on that.
754 if (isThumb) {
755 MachineBasicBlock *MBB = MBBI;
756 if (!MBB->empty()) {
757 // Constant pool entries require padding.
758 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
759 unsigned oldOffset = BBOffsets[i] - delta;
760 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
761 // add new padding
762 BBSizes[i] += 2;
763 delta += 2;
764 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
765 // remove existing padding
766 BBSizes[i] -=2;
767 delta -= 2;
768 }
769 }
Dale Johannesen66a2a8f2007-07-12 16:45:35 +0000770 // Thumb jump tables require padding. They should be at the end;
771 // following unconditional branches are removed by AnalyzeBranch.
Dale Johannesen8593e412007-04-29 19:19:30 +0000772 MachineInstr *ThumbJTMI = NULL;
David Goodwin5e47a9a2009-06-30 18:04:13 +0000773 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
David Goodwinc9a59b52009-06-30 19:50:22 +0000774 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
775 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
776 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
Dale Johannesen8593e412007-04-29 19:19:30 +0000777 ThumbJTMI = prior(MBB->end());
Dale Johannesen8593e412007-04-29 19:19:30 +0000778 if (ThumbJTMI) {
779 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
780 unsigned oldMIOffset = newMIOffset - delta;
781 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
782 // remove existing padding
783 BBSizes[i] -= 2;
784 delta -= 2;
785 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
786 // add new padding
787 BBSizes[i] += 2;
788 delta += 2;
789 }
790 }
791 if (delta==0)
792 return;
793 }
794 MBBI = next(MBBI);
795 }
796 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000797}
798
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000799/// DecrementOldEntry - find the constant pool entry with index CPI
800/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000801/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000802/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000803
Evan Chenged884f32007-04-03 23:39:48 +0000804bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000805 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000806 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
807 assert(CPE && "Unexpected!");
808 if (--CPE->RefCount == 0) {
809 RemoveDeadCPEMI(CPEMI);
810 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000811 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000812 return true;
813 }
814 return false;
815}
816
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000817/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
818/// if not, see if an in-range clone of the CPE is in range, and if so,
819/// change the data structures so the user references the clone. Returns:
820/// 0 = no existing entry found
821/// 1 = entry found, and there were no code insertions or deletions
822/// 2 = entry found, and there were code insertions or deletions
823int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
824{
825 MachineInstr *UserMI = U.MI;
826 MachineInstr *CPEMI = U.CPEMI;
827
828 // Check to see if the CPE is already in-range.
Evan Cheng82020102007-07-10 22:00:16 +0000829 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
830 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000831 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000832 }
833
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000834 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000835 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000836 std::vector<CPEntry> &CPEs = CPEntries[CPI];
837 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
838 // We already tried this one
839 if (CPEs[i].CPEMI == CPEMI)
840 continue;
841 // Removing CPEs can leave empty entries, skip
842 if (CPEs[i].CPEMI == NULL)
843 continue;
844 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
845 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
846 // Point the CPUser node to the replacement
847 U.CPEMI = CPEs[i].CPEMI;
848 // Change the CPI in the instruction operand to refer to the clone.
849 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000850 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000851 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000852 break;
853 }
854 // Adjust the refcount of the clone...
855 CPEs[i].RefCount++;
856 // ...and the original. If we didn't remove the old entry, none of the
857 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000858 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000859 }
860 }
861 return 0;
862}
863
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000864/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
865/// the specific unconditional branch instruction.
866static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwin5e47a9a2009-06-30 18:04:13 +0000867 switch (Opc) {
868 case ARM::tB:
869 return ((1<<10)-1)*2;
870 case ARM::t2B:
871 return ((1<<23)-1)*2;
872 default:
873 break;
874 }
875
876 return ((1<<23)-1)*4;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000877}
878
Dale Johannesen8593e412007-04-29 19:19:30 +0000879/// AcceptWater - Small amount of common code factored out of the following.
880
Bob Wilson84945262009-05-12 17:09:30 +0000881MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000882 std::vector<MachineBasicBlock*>::iterator IP) {
883 DOUT << "found water in range\n";
884 // Remove the original WaterList entry; we want subsequent
885 // insertions in this vicinity to go after the one we're
886 // about to insert. This considerably reduces the number
887 // of times we have to move the same CPE more than once.
888 WaterList.erase(IP);
889 // CPE goes before following block (NewMBB).
890 return next(MachineFunction::iterator(WaterBB));
891}
892
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000893/// LookForWater - look for an existing entry in the WaterList in which
894/// we can place the CPE referenced from U so it's within range of U's MI.
895/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000896/// is set to the WaterList entry.
897/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
898/// water that will not introduce padding to water that will; within each
899/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000900
901bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000902 MachineBasicBlock** NewMBB) {
903 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
904 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000905 if (!WaterList.empty()) {
906 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
907 B = WaterList.begin();; --IP) {
908 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000909 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000910 if (isThumb &&
Bob Wilson84945262009-05-12 17:09:30 +0000911 (BBOffsets[WaterBB->getNumber()] +
Dale Johannesen8593e412007-04-29 19:19:30 +0000912 BBSizes[WaterBB->getNumber()])%4 != 0) {
913 // This is valid Water, but would introduce padding. Remember
914 // it in case we don't find any Water that doesn't do this.
915 if (!WaterBBThatWouldPad) {
916 WaterBBThatWouldPad = WaterBB;
917 IPThatWouldPad = IP;
918 }
919 } else {
920 *NewMBB = AcceptWater(WaterBB, IP);
921 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000922 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000923 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000924 if (IP == B)
925 break;
926 }
927 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000928 if (isThumb && WaterBBThatWouldPad) {
929 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
930 return true;
931 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000932 return false;
933}
934
Bob Wilson84945262009-05-12 17:09:30 +0000935/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000936/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
937/// block is used if in range, and the conditional branch munged so control
938/// flow is correct. Otherwise the block is split to create a hole with an
939/// unconditional branch around it. In either case *NewMBB is set to a
940/// block following which the new island can be inserted (the WaterList
941/// is not adjusted).
942
Bob Wilson84945262009-05-12 17:09:30 +0000943void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000944 unsigned UserOffset, MachineBasicBlock** NewMBB) {
945 CPUser &U = CPUsers[CPUserIndex];
946 MachineInstr *UserMI = U.MI;
947 MachineInstr *CPEMI = U.CPEMI;
948 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000949 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000950 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000951 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000952
953 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000954 // is within range, make new water there. (The addition below is
955 // for the unconditional branch we will be adding: 4 bytes on ARM,
956 // 2 on Thumb. Possible Thumb alignment padding is allowed for
957 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000958 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000959 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000960 if (&UserMBB->back() == UserMI ||
Dale Johannesen8593e412007-04-29 19:19:30 +0000961 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
962 U.MaxDisp, !isThumb)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000963 DOUT << "Split at end of block\n";
964 if (&UserMBB->back() == UserMI)
965 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
966 *NewMBB = next(MachineFunction::iterator(UserMBB));
967 // Add an unconditional branch from UserMBB to fallthrough block.
968 // Record it for branch lengthening; this new branch will not get out of
969 // range, but if the preceding conditional branch is out of range, the
970 // targets will be exchanged, and the altered branch may be out of
971 // range, so the machinery has to know about it.
David Goodwin5e47a9a2009-06-30 18:04:13 +0000972 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +0000973 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
974 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000975 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +0000976 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000977 MaxDisp, false, UncondBr));
978 int delta = isThumb ? 2 : 4;
979 BBSizes[UserMBB->getNumber()] += delta;
980 AdjustBBOffsetsAfter(UserMBB, delta);
981 } else {
982 // What a big block. Find a place within the block to split it.
983 // This is a little tricky on Thumb since instructions are 2 bytes
984 // and constant pool entries are 4 bytes: if instruction I references
985 // island CPE, and instruction I+1 references CPE', it will
986 // not work well to put CPE as far forward as possible, since then
987 // CPE' cannot immediately follow it (that location is 2 bytes
988 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +0000989 // a new island. So, we make a first guess, then walk through the
990 // instructions between the one currently being looked at and the
991 // possible insertion point, and make sure any other instructions
992 // that reference CPEs will be able to use the same island area;
993 // if not, we back up the insertion point.
994
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000995 // The 4 in the following is for the unconditional branch we'll be
Dale Johannesen8593e412007-04-29 19:19:30 +0000996 // inserting (allows for long branch on Thumb). Alignment of the
997 // island is handled inside OffsetIsInRange.
998 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000999 // This could point off the end of the block if we've already got
1000 // constant pool entries following this block; only the last one is
1001 // in the water list. Back past any possible branches (allow for a
1002 // conditional and a maximally long unconditional).
1003 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +00001004 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001005 (isThumb ? 6 : 8);
1006 unsigned EndInsertOffset = BaseInsertOffset +
1007 CPEMI->getOperand(2).getImm();
1008 MachineBasicBlock::iterator MI = UserMI;
1009 ++MI;
1010 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001011 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001012 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001013 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001014 MI = next(MI)) {
1015 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Bob Wilson84945262009-05-12 17:09:30 +00001016 if (!OffsetIsInRange(Offset, EndInsertOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001017 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1018 BaseInsertOffset -= (isThumb ? 2 : 4);
1019 EndInsertOffset -= (isThumb ? 2 : 4);
1020 }
1021 // This is overly conservative, as we don't account for CPEMIs
1022 // being reused within the block, but it doesn't matter much.
1023 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1024 CPUIndex++;
1025 }
1026 }
1027 DOUT << "Split in middle of big block\n";
1028 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1029 }
1030}
1031
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001032/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilson39bf0512009-05-12 17:35:29 +00001033/// is out-of-range. If so, pick up the constant pool value and move it some
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001034/// place in-range. Return true if we changed any addresses (thus must run
1035/// another pass of branch lengthening), false otherwise.
Bob Wilson84945262009-05-12 17:09:30 +00001036bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1037 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001038 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001039 MachineInstr *UserMI = U.MI;
1040 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001041 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001042 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001043 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001044 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilson39bf0512009-05-12 17:35:29 +00001045 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001046 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001047
Evan Cheng185ea1e2007-04-27 18:27:13 +00001048 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1049 // second instruction.
1050 if (UserMI->getOpcode() == ARM::tLEApcrel)
Evan Cheng768c9f72007-04-27 08:14:15 +00001051 UserOffset += 2;
Bob Wilson84945262009-05-12 17:09:30 +00001052
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001053 // See if the current entry is within range, or there is a clone of it
1054 // in range.
1055 int result = LookForExistingCPEntry(U, UserOffset);
1056 if (result==1) return false;
1057 else if (result==2) return true;
1058
1059 // No existing clone of this CPE is within range.
1060 // We will be generating a new clone. Get a UID for it.
Bob Wilson39bf0512009-05-12 17:35:29 +00001061 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001062
1063 // Look for water where we can place this CPE. We look for the farthest one
1064 // away that will work. Forward references only for now (although later
1065 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001066
Dale Johannesen8593e412007-04-29 19:19:30 +00001067 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001068 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001069 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001070 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001071 }
1072
1073 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001074 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1075 Fn.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001076
1077 // Update internal data structures to account for the newly inserted MBB.
1078 UpdateForInsertedWaterBlock(NewIsland);
1079
1080 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001081 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001082
1083 // Now that we have an island to add the CPE to, clone the original CPE and
1084 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001085 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1086 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001087 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001088 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001089 NumCPEs++;
1090
Dale Johannesen8593e412007-04-29 19:19:30 +00001091 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001092 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001093 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001094 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001095 // Increase the size of the island block to account for the new entry.
1096 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001097 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001098
Evan Chenga8e29892007-01-19 07:51:42 +00001099 // Finally, change the CPI in the instruction operand to be ID.
1100 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001101 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001102 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001103 break;
1104 }
Bob Wilson84945262009-05-12 17:09:30 +00001105
Evan Chengc99ef082007-02-09 20:54:44 +00001106 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001107
Evan Chenga8e29892007-01-19 07:51:42 +00001108 return true;
1109}
1110
Evan Chenged884f32007-04-03 23:39:48 +00001111/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1112/// sizes and offsets of impacted basic blocks.
1113void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1114 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001115 unsigned Size = CPEMI->getOperand(2).getImm();
1116 CPEMI->eraseFromParent();
1117 BBSizes[CPEBB->getNumber()] -= Size;
1118 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001119 if (CPEBB->empty()) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001120 // In thumb mode, the size of island may be padded by two to compensate for
1121 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001122 // empty, so fix this.
1123 // All succeeding offsets have the current size value added in, fix this.
1124 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001125 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001126 BBSizes[CPEBB->getNumber()] = 0;
1127 }
Evan Chenged884f32007-04-03 23:39:48 +00001128 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001129 AdjustBBOffsetsAfter(CPEBB, -Size);
1130 // An island has only one predecessor BB and one successor BB. Check if
1131 // this BB's predecessor jumps directly to this BB's successor. This
1132 // shouldn't happen currently.
1133 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1134 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001135}
1136
1137/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1138/// are zero.
1139bool ARMConstantIslands::RemoveUnusedCPEntries() {
1140 unsigned MadeChange = false;
1141 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1142 std::vector<CPEntry> &CPEs = CPEntries[i];
1143 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1144 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1145 RemoveDeadCPEMI(CPEs[j].CPEMI);
1146 CPEs[j].CPEMI = NULL;
1147 MadeChange = true;
1148 }
1149 }
Bob Wilson84945262009-05-12 17:09:30 +00001150 }
Evan Chenged884f32007-04-03 23:39:48 +00001151 return MadeChange;
1152}
1153
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001154/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001155/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001156bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1157 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001158 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001159 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001160 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001161
Evan Chengc99ef082007-02-09 20:54:44 +00001162 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1163 << " from BB#" << MI->getParent()->getNumber()
1164 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001165 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1166 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001167
Dale Johannesen8593e412007-04-29 19:19:30 +00001168 if (BrOffset <= DestOffset) {
1169 // Branch before the Dest.
1170 if (DestOffset-BrOffset <= MaxDisp)
1171 return true;
1172 } else {
1173 if (BrOffset-DestOffset <= MaxDisp)
1174 return true;
1175 }
1176 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001177}
1178
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001179/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1180/// away to fit in its displacement field.
1181bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001182 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001183 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001184
Evan Chengc0dbec72007-01-31 19:57:44 +00001185 // Check to see if the DestBB is already in-range.
1186 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001187 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001188
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001189 if (!Br.isCond)
1190 return FixUpUnconditionalBr(Fn, Br);
1191 return FixUpConditionalBr(Fn, Br);
1192}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001193
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001194/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1195/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001196/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilson39bf0512009-05-12 17:35:29 +00001197/// Otherwise, add an intermediate branch instruction to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001198bool
1199ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1200 MachineInstr *MI = Br.MI;
1201 MachineBasicBlock *MBB = MI->getParent();
David Goodwin5e47a9a2009-06-30 18:04:13 +00001202 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001203
1204 // Use BL to implement far jump.
1205 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001206 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001207 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001208 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001209 HasFarJump = true;
1210 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001211
Evan Chengc99ef082007-02-09 20:54:44 +00001212 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001213
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001214 return true;
1215}
1216
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001217/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001218/// far away to fit in its displacement field. It is converted to an inverse
1219/// conditional branch + an unconditional branch to the destination.
1220bool
1221ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1222 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001223 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001224
Bob Wilson39bf0512009-05-12 17:35:29 +00001225 // Add an unconditional branch to the destination and invert the branch
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001226 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001227 // blt L1
1228 // =>
1229 // bge L2
1230 // b L1
1231 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001232 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001233 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001234 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001235
1236 // If the branch is at the end of its MBB and that has a fall-through block,
1237 // direct the updated conditional branch to the fall-through block. Otherwise,
1238 // split the MBB before the next instruction.
1239 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001240 MachineInstr *BMI = &MBB->back();
1241 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001242
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001243 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001244 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001245 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001246 BMI->getOpcode() == Br.UncondBr) {
Bob Wilson39bf0512009-05-12 17:35:29 +00001247 // Last MI in the BB is an unconditional branch. Can we simply invert the
Evan Cheng43aeab62007-01-26 20:38:26 +00001248 // condition and swap destinations:
1249 // beq L1
1250 // b L2
1251 // =>
1252 // bne L2
1253 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001254 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001255 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001256 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001257 BMI->getOperand(0).setMBB(DestBB);
1258 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001259 MI->getOperand(1).setImm(CC);
1260 return true;
1261 }
1262 }
1263 }
1264
1265 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001266 SplitBlockBeforeInstr(MI);
Bob Wilson39bf0512009-05-12 17:35:29 +00001267 // No need for the branch to the next block. We're adding an unconditional
Evan Chengdd353b82007-01-26 02:02:39 +00001268 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001269 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001270 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001271 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1272 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001273 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001274 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001275 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001276 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001277
Evan Chengc99ef082007-02-09 20:54:44 +00001278 DOUT << " Insert B to BB#" << DestBB->getNumber()
1279 << " also invert condition and change dest. to BB#"
1280 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001281
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001282 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001283 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001284 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1285 TII->get(MI->getOpcode()))
1286 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001287 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001288 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001289 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001290 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001291 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001292 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001293
1294 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001295 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001296 MI->eraseFromParent();
1297
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001298 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001299 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001300 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001301 return true;
1302}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001303
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001304/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1305/// LR / restores LR to pc.
1306bool ARMConstantIslands::UndoLRSpillRestore() {
1307 bool MadeChange = false;
1308 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1309 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001310 if (MI->getOpcode() == ARM::tPOP_RET &&
1311 MI->getOperand(0).getReg() == ARM::PC &&
1312 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001313 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001314 MI->eraseFromParent();
1315 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001316 }
1317 }
1318 return MadeChange;
1319}