blob: c67141c8ddb45de0fdac03e4fa8d370f4bcb6175 [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;
Evan Chenga8e29892007-01-19 07:51:42 +0000127 public:
Devang Patel19974732007-05-03 01:11:54 +0000128 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000129 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000130
Evan Chenga8e29892007-01-19 07:51:42 +0000131 virtual bool runOnMachineFunction(MachineFunction &Fn);
132
133 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000134 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000135 }
Bob Wilson84945262009-05-12 17:09:30 +0000136
Evan Chenga8e29892007-01-19 07:51:42 +0000137 private:
138 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000139 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000140 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000141 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000142 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000143 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000144 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000145 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Evan Chenged884f32007-04-03 23:39:48 +0000146 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000147 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilson84945262009-05-12 17:09:30 +0000148 bool LookForWater(CPUser&U, unsigned UserOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000149 MachineBasicBlock** NewMBB);
Bob Wilson84945262009-05-12 17:09:30 +0000150 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000151 std::vector<MachineBasicBlock*>::iterator IP);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000152 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
153 MachineBasicBlock** NewMBB);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000154 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Evan Chenged884f32007-04-03 23:39:48 +0000155 void RemoveDeadCPEMI(MachineInstr *CPEMI);
156 bool RemoveUnusedCPEntries();
Bob Wilson84945262009-05-12 17:09:30 +0000157 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000158 MachineInstr *CPEMI, unsigned Disp,
159 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000160 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000161 CPUser &U);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000162 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
163 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000164 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000165 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
166 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
167 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
168 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000169
Evan Chenga8e29892007-01-19 07:51:42 +0000170 unsigned GetOffsetOf(MachineInstr *MI) const;
Dale Johannesen8593e412007-04-29 19:19:30 +0000171 void dumpBBs();
172 void verify(MachineFunction &Fn);
Evan Chenga8e29892007-01-19 07:51:42 +0000173 };
Devang Patel19974732007-05-03 01:11:54 +0000174 char ARMConstantIslands::ID = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000175}
176
Dale Johannesen8593e412007-04-29 19:19:30 +0000177/// verify - check BBOffsets, BBSizes, alignment of islands
178void ARMConstantIslands::verify(MachineFunction &Fn) {
179 assert(BBOffsets.size() == BBSizes.size());
180 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
181 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
182 if (isThumb) {
183 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
184 MBBI != E; ++MBBI) {
185 MachineBasicBlock *MBB = MBBI;
186 if (!MBB->empty() &&
187 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
188 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
189 BBSizes[MBB->getNumber()]%4 == 0) ||
190 (BBOffsets[MBB->getNumber()]%4 != 0 &&
191 BBSizes[MBB->getNumber()]%4 != 0));
192 }
193 }
194}
195
196/// print block size and offset information - debugging
197void ARMConstantIslands::dumpBBs() {
198 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilson84945262009-05-12 17:09:30 +0000199 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000200 " size " << BBSizes[J] << "\n";
Dale Johannesen8593e412007-04-29 19:19:30 +0000201 }
202}
203
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000204/// createARMConstantIslandPass - returns an instance of the constpool
205/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000206FunctionPass *llvm::createARMConstantIslandPass() {
207 return new ARMConstantIslands();
208}
209
210bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000211 MachineConstantPool &MCP = *Fn.getConstantPool();
Bob Wilson84945262009-05-12 17:09:30 +0000212
Evan Chenga8e29892007-01-19 07:51:42 +0000213 TII = Fn.getTarget().getInstrInfo();
Dale Johannesen8593e412007-04-29 19:19:30 +0000214 AFI = Fn.getInfo<ARMFunctionInfo>();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000215 isThumb = AFI->isThumbFunction();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000216
217 HasFarJump = false;
218
Evan Chenga8e29892007-01-19 07:51:42 +0000219 // Renumber all of the machine basic blocks in the function, guaranteeing that
220 // the numbers agree with the position of the block in the function.
221 Fn.RenumberBlocks();
222
Bob Wilson84945262009-05-12 17:09:30 +0000223 /// Thumb functions containing constant pools get 2-byte alignment.
224 /// This is so we can keep exact track of where the alignment padding goes.
225 /// Set default.
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000226 AFI->setAlign(isThumb ? 1U : 2U);
227
Evan Chenga8e29892007-01-19 07:51:42 +0000228 // Perform the initial placement of the constant pool entries. To start with,
229 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000230 std::vector<MachineInstr*> CPEMIs;
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000231 if (!MCP.isEmpty()) {
Evan Cheng7755fac2007-01-26 01:04:44 +0000232 DoInitialPlacement(Fn, CPEMIs);
Dale Johannesen56c42ef2007-04-23 20:09:04 +0000233 if (isThumb)
234 AFI->setAlign(2U);
235 }
Bob Wilson84945262009-05-12 17:09:30 +0000236
Evan Chenga8e29892007-01-19 07:51:42 +0000237 /// The next UID to take is the first unused one.
Evan Chengf1bbb952008-11-08 00:51:41 +0000238 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilson84945262009-05-12 17:09:30 +0000239
Evan Chenga8e29892007-01-19 07:51:42 +0000240 // Do the initial scan of the function, building up information about the
241 // sizes of each block, the location of all the water, and finding all of the
242 // constant pool users.
243 InitialFunctionScan(Fn, CPEMIs);
244 CPEMIs.clear();
Bob Wilson84945262009-05-12 17:09:30 +0000245
Evan Chenged884f32007-04-03 23:39:48 +0000246 /// Remove dead constant pool entries.
247 RemoveUnusedCPEntries();
248
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000249 // Iteratively place constant pool entries and fix up branches until there
250 // is no change.
251 bool MadeChange = false;
252 while (true) {
253 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000254 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000255 Change |= HandleConstantPoolUser(Fn, i);
Evan Cheng82020102007-07-10 22:00:16 +0000256 DEBUG(dumpBBs());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000257 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000258 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
Evan Cheng82020102007-07-10 22:00:16 +0000259 DEBUG(dumpBBs());
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000260 if (!Change)
261 break;
262 MadeChange = true;
263 }
Evan Chenged884f32007-04-03 23:39:48 +0000264
Dale Johannesen8593e412007-04-29 19:19:30 +0000265 // After a while, this might be made debug-only, but it is not expensive.
266 verify(Fn);
267
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000268 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
269 // Undo the spill / restore of LR if possible.
Evan Chengf49407b2007-03-01 08:26:31 +0000270 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000271 MadeChange |= UndoLRSpillRestore();
272
Evan Chenga8e29892007-01-19 07:51:42 +0000273 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000274 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000275 WaterList.clear();
276 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000277 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000278 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000279 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000280
281 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000282}
283
284/// DoInitialPlacement - Perform the initial placement of the constant pool
285/// entries. To start with, we put them all at the end of the function.
286void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Bob Wilson84945262009-05-12 17:09:30 +0000287 std::vector<MachineInstr*> &CPEMIs) {
Evan Chenga8e29892007-01-19 07:51:42 +0000288 // Create the basic block to hold the CPE's.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000289 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
290 Fn.push_back(BB);
Bob Wilson84945262009-05-12 17:09:30 +0000291
Evan Chenga8e29892007-01-19 07:51:42 +0000292 // Add all of the constants from the constant pool to the end block, use an
293 // identity mapping of CPI's to CPE's.
294 const std::vector<MachineConstantPoolEntry> &CPs =
295 Fn.getConstantPool()->getConstants();
Bob Wilson84945262009-05-12 17:09:30 +0000296
Evan Chenga8e29892007-01-19 07:51:42 +0000297 const TargetData &TD = *Fn.getTarget().getTargetData();
298 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sands777d2302009-05-09 07:06:46 +0000299 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Evan Chenga8e29892007-01-19 07:51:42 +0000300 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
301 // we would have to pad them out or something so that instructions stay
302 // aligned.
303 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
304 MachineInstr *CPEMI =
Dale Johannesenb6728402009-02-13 02:25:56 +0000305 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +0000306 .addImm(i).addConstantPoolIndex(i).addImm(Size);
307 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000308
309 // Add a new CPEntry, but no corresponding CPUser yet.
310 std::vector<CPEntry> CPEs;
311 CPEs.push_back(CPEntry(CPEMI, i));
312 CPEntries.push_back(CPEs);
313 NumCPEs++;
314 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000315 }
316}
317
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000318/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000319/// into the block immediately after it.
320static bool BBHasFallthrough(MachineBasicBlock *MBB) {
321 // Get the next machine basic block in the function.
322 MachineFunction::iterator MBBI = MBB;
323 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
324 return false;
Bob Wilson84945262009-05-12 17:09:30 +0000325
Evan Chenga8e29892007-01-19 07:51:42 +0000326 MachineBasicBlock *NextBB = next(MBBI);
327 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
328 E = MBB->succ_end(); I != E; ++I)
329 if (*I == NextBB)
330 return true;
Bob Wilson84945262009-05-12 17:09:30 +0000331
Evan Chenga8e29892007-01-19 07:51:42 +0000332 return false;
333}
334
Evan Chengc99ef082007-02-09 20:54:44 +0000335/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
336/// look up the corresponding CPEntry.
337ARMConstantIslands::CPEntry
338*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
339 const MachineInstr *CPEMI) {
340 std::vector<CPEntry> &CPEs = CPEntries[CPI];
341 // Number of entries per constpool index should be small, just do a
342 // linear search.
343 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
344 if (CPEs[i].CPEMI == CPEMI)
345 return &CPEs[i];
346 }
347 return NULL;
348}
349
Evan Chenga8e29892007-01-19 07:51:42 +0000350/// InitialFunctionScan - Do the initial scan of the function, building up
351/// information about the sizes of each block, the location of all the water,
352/// and finding all of the constant pool users.
353void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000354 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000355 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000356 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
357 MBBI != E; ++MBBI) {
358 MachineBasicBlock &MBB = *MBBI;
Bob Wilson84945262009-05-12 17:09:30 +0000359
Evan Chenga8e29892007-01-19 07:51:42 +0000360 // If this block doesn't fall through into the next MBB, then this is
361 // 'water' that a constant pool island could be placed.
362 if (!BBHasFallthrough(&MBB))
363 WaterList.push_back(&MBB);
Bob Wilson84945262009-05-12 17:09:30 +0000364
Evan Chenga8e29892007-01-19 07:51:42 +0000365 unsigned MBBSize = 0;
366 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
367 I != E; ++I) {
368 // Add instruction size to MBBSize.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000369 MBBSize += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000370
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000371 int Opc = I->getOpcode();
Chris Lattner749c6f62008-01-07 07:27:27 +0000372 if (I->getDesc().isBranch()) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000373 bool isCond = false;
374 unsigned Bits = 0;
375 unsigned Scale = 1;
376 int UOpc = Opc;
377 switch (Opc) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000378 case ARM::tBR_JTr:
379 // A Thumb table jump may involve padding; for the offsets to
380 // be right, functions containing these must be 4-byte aligned.
381 AFI->setAlign(2U);
382 if ((Offset+MBBSize)%4 != 0)
383 MBBSize += 2; // padding
384 continue; // Does not get an entry in ImmBranches
Evan Cheng743fa032007-01-25 19:43:52 +0000385 default:
Dale Johannesen8593e412007-04-29 19:19:30 +0000386 continue; // Ignore other JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000387 case ARM::Bcc:
388 isCond = true;
389 UOpc = ARM::B;
390 // Fallthrough
391 case ARM::B:
392 Bits = 24;
393 Scale = 4;
394 break;
395 case ARM::tBcc:
396 isCond = true;
397 UOpc = ARM::tB;
398 Bits = 8;
399 Scale = 2;
400 break;
401 case ARM::tB:
402 Bits = 11;
403 Scale = 2;
404 break;
405 }
Evan Chengb43216e2007-02-01 10:16:15 +0000406
407 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000408 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000409 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000410 }
411
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000412 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
413 PushPopMIs.push_back(I);
414
Evan Chenga8e29892007-01-19 07:51:42 +0000415 // Scan the instructions for constant pool operands.
416 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmand735b802008-10-03 15:45:36 +0000417 if (I->getOperand(op).isCPI()) {
Evan Chenga8e29892007-01-19 07:51:42 +0000418 // We found one. The addressing mode tells us the max displacement
419 // from the PC that this instruction permits.
Bob Wilson84945262009-05-12 17:09:30 +0000420
Evan Chenga8e29892007-01-19 07:51:42 +0000421 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000422 unsigned Bits = 0;
423 unsigned Scale = 1;
Chris Lattner749c6f62008-01-07 07:27:27 +0000424 unsigned TSFlags = I->getDesc().TSFlags;
Evan Chenga8e29892007-01-19 07:51:42 +0000425 switch (TSFlags & ARMII::AddrModeMask) {
Bob Wilson84945262009-05-12 17:09:30 +0000426 default:
Evan Chenga8e29892007-01-19 07:51:42 +0000427 // Constant pool entries can reach anything.
428 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
429 continue;
Evan Cheng768c9f72007-04-27 08:14:15 +0000430 if (I->getOpcode() == ARM::tLEApcrel) {
431 Bits = 8; // Taking the address of a CP entry.
432 break;
433 }
Evan Chenga8e29892007-01-19 07:51:42 +0000434 assert(0 && "Unknown addressing mode for CP reference!");
435 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000436 Bits = 8;
437 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000438 break;
439 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000440 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000441 break;
442 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000443 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000444 break;
445 // addrmode4 has no immediate offset.
446 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000447 Bits = 8;
448 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000449 break;
450 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000451 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000452 break;
453 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000454 Bits = 5;
455 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000456 break;
457 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000458 Bits = 5;
459 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000460 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000461 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000462 Bits = 8;
463 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000464 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000465 }
Evan Chengb43216e2007-02-01 10:16:15 +0000466
Evan Chenga8e29892007-01-19 07:51:42 +0000467 // Remember that this is a user of a CP entry.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000468 unsigned CPI = I->getOperand(op).getIndex();
Evan Chengc99ef082007-02-09 20:54:44 +0000469 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilson84945262009-05-12 17:09:30 +0000470 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000471 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000472
473 // Increment corresponding CPEntry reference count.
474 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
475 assert(CPE && "Cannot find a corresponding CPEntry!");
476 CPE->RefCount++;
Bob Wilson84945262009-05-12 17:09:30 +0000477
Evan Chenga8e29892007-01-19 07:51:42 +0000478 // Instructions can only use one CP entry, don't bother scanning the
479 // rest of the operands.
480 break;
481 }
482 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000483
Dale Johannesen8593e412007-04-29 19:19:30 +0000484 // In thumb mode, if this block is a constpool island, we may need padding
485 // so it's aligned on 4 byte boundary.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000486 if (isThumb &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000487 !MBB.empty() &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000488 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
489 (Offset%4) != 0)
Evan Cheng2021abe2007-02-01 01:09:47 +0000490 MBBSize += 2;
491
Evan Chenga8e29892007-01-19 07:51:42 +0000492 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000493 BBOffsets.push_back(Offset);
494 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000495 }
496}
497
Evan Chenga8e29892007-01-19 07:51:42 +0000498/// GetOffsetOf - Return the current offset of the specified machine instruction
499/// from the start of the function. This offset changes as stuff is moved
500/// around inside the function.
501unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
502 MachineBasicBlock *MBB = MI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000503
Evan Chenga8e29892007-01-19 07:51:42 +0000504 // The offset is composed of two things: the sum of the sizes of all MBB's
505 // before this instruction's block, and the offset from the start of the block
506 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000507 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000508
Dale Johannesen8593e412007-04-29 19:19:30 +0000509 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
510 // alignment padding, and compensate if so.
Bob Wilson84945262009-05-12 17:09:30 +0000511 if (isThumb &&
512 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dale Johannesen8593e412007-04-29 19:19:30 +0000513 Offset%4 != 0)
514 Offset += 2;
515
Evan Chenga8e29892007-01-19 07:51:42 +0000516 // Sum instructions before MI in MBB.
517 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
518 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
519 if (&*I == MI) return Offset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000520 Offset += TII->GetInstSizeInBytes(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000521 }
522}
523
524/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
525/// ID.
526static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
527 const MachineBasicBlock *RHS) {
528 return LHS->getNumber() < RHS->getNumber();
529}
530
531/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
532/// machine function, it upsets all of the block numbers. Renumber the blocks
533/// and update the arrays that parallel this numbering.
534void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
535 // Renumber the MBB's to keep them consequtive.
536 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000537
Evan Chenga8e29892007-01-19 07:51:42 +0000538 // Insert a size into BBSizes to align it properly with the (newly
539 // renumbered) block numbers.
540 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000541
542 // Likewise for BBOffsets.
543 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000544
545 // Next, update WaterList. Specifically, we need to add NewMBB as having
Evan Chenga8e29892007-01-19 07:51:42 +0000546 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000547 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000548 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
549 CompareMBBNumbers);
550 WaterList.insert(IP, NewBB);
551}
552
553
554/// Split the basic block containing MI into two blocks, which are joined by
555/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000556/// account for this change and returns the newly created block.
557MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000558 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000559 MachineFunction &MF = *OrigBB->getParent();
Evan Chenga8e29892007-01-19 07:51:42 +0000560
561 // Create a new MBB for the code after the OrigBB.
Bob Wilson84945262009-05-12 17:09:30 +0000562 MachineBasicBlock *NewBB =
563 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Evan Chenga8e29892007-01-19 07:51:42 +0000564 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000565 MF.insert(MBBI, NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000566
Evan Chenga8e29892007-01-19 07:51:42 +0000567 // Splice the instructions starting with MI over to NewBB.
568 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilson84945262009-05-12 17:09:30 +0000569
Evan Chenga8e29892007-01-19 07:51:42 +0000570 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000571 // Note the new unconditional branch is not being recorded.
Dale Johannesenb6728402009-02-13 02:25:56 +0000572 // There doesn't seem to be meaningful DebugInfo available; this doesn't
573 // correspond to anything in the source.
574 BuildMI(OrigBB, DebugLoc::getUnknownLoc(),
575 TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000576 NumSplit++;
Bob Wilson84945262009-05-12 17:09:30 +0000577
Evan Chenga8e29892007-01-19 07:51:42 +0000578 // Update the CFG. All succs of OrigBB are now succs of NewBB.
579 while (!OrigBB->succ_empty()) {
580 MachineBasicBlock *Succ = *OrigBB->succ_begin();
581 OrigBB->removeSuccessor(Succ);
582 NewBB->addSuccessor(Succ);
Bob Wilson84945262009-05-12 17:09:30 +0000583
Evan Chenga8e29892007-01-19 07:51:42 +0000584 // This pass should be run after register allocation, so there should be no
585 // PHI nodes to update.
586 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
587 && "PHI nodes should be eliminated by now!");
588 }
Bob Wilson84945262009-05-12 17:09:30 +0000589
Evan Chenga8e29892007-01-19 07:51:42 +0000590 // OrigBB branches to NewBB.
591 OrigBB->addSuccessor(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000592
Evan Chenga8e29892007-01-19 07:51:42 +0000593 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000594 // This is almost the same as UpdateForInsertedWaterBlock, except that
595 // the Water goes after OrigBB, not NewBB.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000596 MF.RenumberBlocks(NewBB);
Bob Wilson84945262009-05-12 17:09:30 +0000597
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000598 // Insert a size into BBSizes to align it properly with the (newly
599 // renumbered) block numbers.
600 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilson84945262009-05-12 17:09:30 +0000601
Dale Johannesen99c49a42007-02-25 00:47:03 +0000602 // Likewise for BBOffsets.
603 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
604
Bob Wilson84945262009-05-12 17:09:30 +0000605 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000606 // available water after it (but not if it's already there, which happens
607 // when splitting before a conditional branch that is followed by an
608 // unconditional branch - in that case we want to insert NewBB).
609 std::vector<MachineBasicBlock*>::iterator IP =
610 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
611 CompareMBBNumbers);
612 MachineBasicBlock* WaterBB = *IP;
613 if (WaterBB == OrigBB)
614 WaterList.insert(next(IP), NewBB);
615 else
616 WaterList.insert(IP, OrigBB);
617
Dale Johannesen8593e412007-04-29 19:19:30 +0000618 // Figure out how large the first NewMBB is. (It cannot
619 // contain a constpool_entry or tablejump.)
Evan Chenga8e29892007-01-19 07:51:42 +0000620 unsigned NewBBSize = 0;
621 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
622 I != E; ++I)
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000623 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilson84945262009-05-12 17:09:30 +0000624
Dale Johannesen99c49a42007-02-25 00:47:03 +0000625 unsigned OrigBBI = OrigBB->getNumber();
626 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000627 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000628 BBSizes[NewBBI] = NewBBSize;
Bob Wilson84945262009-05-12 17:09:30 +0000629
Evan Chenga8e29892007-01-19 07:51:42 +0000630 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000631 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000632 unsigned delta = isThumb ? 2 : 4;
633 BBSizes[OrigBBI] -= NewBBSize - delta;
634
635 // ...and adjust BBOffsets for NewBB accordingly.
636 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
637
638 // All BBOffsets following these blocks must be modified.
639 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000640
641 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000642}
643
Dale Johannesen8593e412007-04-29 19:19:30 +0000644/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilson84945262009-05-12 17:09:30 +0000645/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dale Johannesen8593e412007-04-29 19:19:30 +0000646/// constant pool entry).
Bob Wilson84945262009-05-12 17:09:30 +0000647bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000648 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
Bob Wilson84945262009-05-12 17:09:30 +0000649 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
650 // purposes of the displacement computation; compensate for that here.
Dale Johannesen8593e412007-04-29 19:19:30 +0000651 // Effectively, the valid range of displacements is 2 bytes smaller for such
652 // references.
653 if (isThumb && UserOffset%4 !=0)
654 UserOffset -= 2;
655 // CPEs will be rounded up to a multiple of 4.
656 if (isThumb && TrialOffset%4 != 0)
657 TrialOffset += 2;
658
Dale Johannesen99c49a42007-02-25 00:47:03 +0000659 if (UserOffset <= TrialOffset) {
660 // User before the Trial.
661 if (TrialOffset-UserOffset <= MaxDisp)
662 return true;
663 } else if (NegativeOK) {
664 if (UserOffset-TrialOffset <= MaxDisp)
665 return true;
666 }
667 return false;
668}
669
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000670/// WaterIsInRange - Returns true if a CPE placed after the specified
671/// Water (a basic block) will be in range for the specific MI.
672
673bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000674 MachineBasicBlock* Water, CPUser &U)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000675{
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000676 unsigned MaxDisp = U.MaxDisp;
Dale Johannesen8593e412007-04-29 19:19:30 +0000677 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
Bob Wilson84945262009-05-12 17:09:30 +0000678 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000679 BBSizes[Water->getNumber()];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000680
Dale Johannesend959aa42007-04-02 20:31:06 +0000681 // If the CPE is to be inserted before the instruction, that will raise
Dale Johannesen8593e412007-04-29 19:19:30 +0000682 // the offset of the instruction. (Currently applies only to ARM, so
683 // no alignment compensation attempted here.)
Dale Johannesend959aa42007-04-02 20:31:06 +0000684 if (CPEOffset < UserOffset)
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000685 UserOffset += U.CPEMI->getOperand(2).getImm();
Dale Johannesend959aa42007-04-02 20:31:06 +0000686
Dale Johannesen99c49a42007-02-25 00:47:03 +0000687 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000688}
689
690/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000691/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000692bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
693 MachineInstr *CPEMI,
694 unsigned MaxDisp, bool DoDump) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000695 unsigned CPEOffset = GetOffsetOf(CPEMI);
696 assert(CPEOffset%4 == 0 && "Misaligned CPE");
Evan Cheng2021abe2007-02-01 01:09:47 +0000697
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000698 if (DoDump) {
699 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
700 << " max delta=" << MaxDisp
701 << " insn address=" << UserOffset
702 << " CPE address=" << CPEOffset
703 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
704 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000705
Dale Johannesen99c49a42007-02-25 00:47:03 +0000706 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000707}
708
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000709#ifndef NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000710/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
711/// unconditionally branches to its only successor.
712static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
713 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
714 return false;
715
716 MachineBasicBlock *Succ = *MBB->succ_begin();
717 MachineBasicBlock *Pred = *MBB->pred_begin();
718 MachineInstr *PredMI = &Pred->back();
719 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
720 return PredMI->getOperand(0).getMBB() == Succ;
721 return false;
722}
Evan Chengd1e7d9a2009-01-28 00:53:34 +0000723#endif // NDEBUG
Evan Chengc99ef082007-02-09 20:54:44 +0000724
Bob Wilson84945262009-05-12 17:09:30 +0000725void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000726 int delta) {
727 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
728 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000729 BBOffsets[i] += delta;
Dale Johannesen8593e412007-04-29 19:19:30 +0000730 // If some existing blocks have padding, adjust the padding as needed, a
731 // bit tricky. delta can be negative so don't use % on that.
732 if (isThumb) {
733 MachineBasicBlock *MBB = MBBI;
734 if (!MBB->empty()) {
735 // Constant pool entries require padding.
736 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
737 unsigned oldOffset = BBOffsets[i] - delta;
738 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
739 // add new padding
740 BBSizes[i] += 2;
741 delta += 2;
742 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
743 // remove existing padding
744 BBSizes[i] -=2;
745 delta -= 2;
746 }
747 }
Dale Johannesen66a2a8f2007-07-12 16:45:35 +0000748 // Thumb jump tables require padding. They should be at the end;
749 // following unconditional branches are removed by AnalyzeBranch.
Dale Johannesen8593e412007-04-29 19:19:30 +0000750 MachineInstr *ThumbJTMI = NULL;
751 if (prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
752 ThumbJTMI = prior(MBB->end());
Dale Johannesen8593e412007-04-29 19:19:30 +0000753 if (ThumbJTMI) {
754 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
755 unsigned oldMIOffset = newMIOffset - delta;
756 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
757 // remove existing padding
758 BBSizes[i] -= 2;
759 delta -= 2;
760 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
761 // add new padding
762 BBSizes[i] += 2;
763 delta += 2;
764 }
765 }
766 if (delta==0)
767 return;
768 }
769 MBBI = next(MBBI);
770 }
771 }
Dale Johannesen99c49a42007-02-25 00:47:03 +0000772}
773
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000774/// DecrementOldEntry - find the constant pool entry with index CPI
775/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilson84945262009-05-12 17:09:30 +0000776/// becomes 0 remove the entry and instruction. Returns true if we removed
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000777/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000778
Evan Chenged884f32007-04-03 23:39:48 +0000779bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
Evan Chengc99ef082007-02-09 20:54:44 +0000780 // Find the old entry. Eliminate it if it is no longer used.
Evan Chenged884f32007-04-03 23:39:48 +0000781 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
782 assert(CPE && "Unexpected!");
783 if (--CPE->RefCount == 0) {
784 RemoveDeadCPEMI(CPEMI);
785 CPE->CPEMI = NULL;
Evan Chengc99ef082007-02-09 20:54:44 +0000786 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000787 return true;
788 }
789 return false;
790}
791
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000792/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
793/// if not, see if an in-range clone of the CPE is in range, and if so,
794/// change the data structures so the user references the clone. Returns:
795/// 0 = no existing entry found
796/// 1 = entry found, and there were no code insertions or deletions
797/// 2 = entry found, and there were code insertions or deletions
798int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
799{
800 MachineInstr *UserMI = U.MI;
801 MachineInstr *CPEMI = U.CPEMI;
802
803 // Check to see if the CPE is already in-range.
Evan Cheng82020102007-07-10 22:00:16 +0000804 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
805 DOUT << "In range\n";
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000806 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000807 }
808
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000809 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner8aa797a2007-12-30 23:10:15 +0000810 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000811 std::vector<CPEntry> &CPEs = CPEntries[CPI];
812 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
813 // We already tried this one
814 if (CPEs[i].CPEMI == CPEMI)
815 continue;
816 // Removing CPEs can leave empty entries, skip
817 if (CPEs[i].CPEMI == NULL)
818 continue;
819 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
820 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
821 // Point the CPUser node to the replacement
822 U.CPEMI = CPEs[i].CPEMI;
823 // Change the CPI in the instruction operand to refer to the clone.
824 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmand735b802008-10-03 15:45:36 +0000825 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +0000826 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000827 break;
828 }
829 // Adjust the refcount of the clone...
830 CPEs[i].RefCount++;
831 // ...and the original. If we didn't remove the old entry, none of the
832 // addresses changed, so we don't need another pass.
Evan Chenged884f32007-04-03 23:39:48 +0000833 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000834 }
835 }
836 return 0;
837}
838
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000839/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
840/// the specific unconditional branch instruction.
841static inline unsigned getUnconditionalBrDisp(int Opc) {
842 return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
843}
844
Dale Johannesen8593e412007-04-29 19:19:30 +0000845/// AcceptWater - Small amount of common code factored out of the following.
846
Bob Wilson84945262009-05-12 17:09:30 +0000847MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dale Johannesen8593e412007-04-29 19:19:30 +0000848 std::vector<MachineBasicBlock*>::iterator IP) {
849 DOUT << "found water in range\n";
850 // Remove the original WaterList entry; we want subsequent
851 // insertions in this vicinity to go after the one we're
852 // about to insert. This considerably reduces the number
853 // of times we have to move the same CPE more than once.
854 WaterList.erase(IP);
855 // CPE goes before following block (NewMBB).
856 return next(MachineFunction::iterator(WaterBB));
857}
858
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000859/// LookForWater - look for an existing entry in the WaterList in which
860/// we can place the CPE referenced from U so it's within range of U's MI.
861/// Returns true if found, false if not. If it returns true, *NewMBB
Dale Johannesen8593e412007-04-29 19:19:30 +0000862/// is set to the WaterList entry.
863/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
864/// water that will not introduce padding to water that will; within each
865/// group, prefer the water that's farthest away.
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000866
867bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
Dale Johannesen8593e412007-04-29 19:19:30 +0000868 MachineBasicBlock** NewMBB) {
869 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
870 MachineBasicBlock* WaterBBThatWouldPad = NULL;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000871 if (!WaterList.empty()) {
872 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
873 B = WaterList.begin();; --IP) {
874 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen5d9c4b62007-07-11 18:32:38 +0000875 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Dale Johannesen8593e412007-04-29 19:19:30 +0000876 if (isThumb &&
Bob Wilson84945262009-05-12 17:09:30 +0000877 (BBOffsets[WaterBB->getNumber()] +
Dale Johannesen8593e412007-04-29 19:19:30 +0000878 BBSizes[WaterBB->getNumber()])%4 != 0) {
879 // This is valid Water, but would introduce padding. Remember
880 // it in case we don't find any Water that doesn't do this.
881 if (!WaterBBThatWouldPad) {
882 WaterBBThatWouldPad = WaterBB;
883 IPThatWouldPad = IP;
884 }
885 } else {
886 *NewMBB = AcceptWater(WaterBB, IP);
887 return true;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000888 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000889 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000890 if (IP == B)
891 break;
892 }
893 }
Dale Johannesen8593e412007-04-29 19:19:30 +0000894 if (isThumb && WaterBBThatWouldPad) {
895 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
896 return true;
897 }
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000898 return false;
899}
900
Bob Wilson84945262009-05-12 17:09:30 +0000901/// CreateNewWater - No existing WaterList entry will work for
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000902/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
903/// block is used if in range, and the conditional branch munged so control
904/// flow is correct. Otherwise the block is split to create a hole with an
905/// unconditional branch around it. In either case *NewMBB is set to a
906/// block following which the new island can be inserted (the WaterList
907/// is not adjusted).
908
Bob Wilson84945262009-05-12 17:09:30 +0000909void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000910 unsigned UserOffset, MachineBasicBlock** NewMBB) {
911 CPUser &U = CPUsers[CPUserIndex];
912 MachineInstr *UserMI = U.MI;
913 MachineInstr *CPEMI = U.CPEMI;
914 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilson84945262009-05-12 17:09:30 +0000915 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000916 BBSizes[UserMBB->getNumber()];
Dale Johannesen8593e412007-04-29 19:19:30 +0000917 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000918
919 // If the use is at the end of the block, or the end of the block
Dale Johannesen8593e412007-04-29 19:19:30 +0000920 // is within range, make new water there. (The addition below is
921 // for the unconditional branch we will be adding: 4 bytes on ARM,
922 // 2 on Thumb. Possible Thumb alignment padding is allowed for
923 // inside OffsetIsInRange.
Bob Wilson84945262009-05-12 17:09:30 +0000924 // If the block ends in an unconditional branch already, it is water,
Dale Johannesen8593e412007-04-29 19:19:30 +0000925 // and is known to be out of range, so we'll always be adding a branch.)
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000926 if (&UserMBB->back() == UserMI ||
Dale Johannesen8593e412007-04-29 19:19:30 +0000927 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
928 U.MaxDisp, !isThumb)) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000929 DOUT << "Split at end of block\n";
930 if (&UserMBB->back() == UserMI)
931 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
932 *NewMBB = next(MachineFunction::iterator(UserMBB));
933 // Add an unconditional branch from UserMBB to fallthrough block.
934 // Record it for branch lengthening; this new branch will not get out of
935 // range, but if the preceding conditional branch is out of range, the
936 // targets will be exchanged, and the altered branch may be out of
937 // range, so the machinery has to know about it.
938 int UncondBr = isThumb ? ARM::tB : ARM::B;
Dale Johannesenb6728402009-02-13 02:25:56 +0000939 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
940 TII->get(UncondBr)).addMBB(*NewMBB);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000941 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilson84945262009-05-12 17:09:30 +0000942 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000943 MaxDisp, false, UncondBr));
944 int delta = isThumb ? 2 : 4;
945 BBSizes[UserMBB->getNumber()] += delta;
946 AdjustBBOffsetsAfter(UserMBB, delta);
947 } else {
948 // What a big block. Find a place within the block to split it.
949 // This is a little tricky on Thumb since instructions are 2 bytes
950 // and constant pool entries are 4 bytes: if instruction I references
951 // island CPE, and instruction I+1 references CPE', it will
952 // not work well to put CPE as far forward as possible, since then
953 // CPE' cannot immediately follow it (that location is 2 bytes
954 // farther away from I+1 than CPE was from I) and we'd need to create
Dale Johannesen8593e412007-04-29 19:19:30 +0000955 // a new island. So, we make a first guess, then walk through the
956 // instructions between the one currently being looked at and the
957 // possible insertion point, and make sure any other instructions
958 // that reference CPEs will be able to use the same island area;
959 // if not, we back up the insertion point.
960
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000961 // The 4 in the following is for the unconditional branch we'll be
Dale Johannesen8593e412007-04-29 19:19:30 +0000962 // inserting (allows for long branch on Thumb). Alignment of the
963 // island is handled inside OffsetIsInRange.
964 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000965 // This could point off the end of the block if we've already got
966 // constant pool entries following this block; only the last one is
967 // in the water list. Back past any possible branches (allow for a
968 // conditional and a maximally long unconditional).
969 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilson84945262009-05-12 17:09:30 +0000970 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000971 (isThumb ? 6 : 8);
972 unsigned EndInsertOffset = BaseInsertOffset +
973 CPEMI->getOperand(2).getImm();
974 MachineBasicBlock::iterator MI = UserMI;
975 ++MI;
976 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000977 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000978 Offset < BaseInsertOffset;
Nicolas Geoffray52e724a2008-04-16 20:10:13 +0000979 Offset += TII->GetInstSizeInBytes(MI),
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000980 MI = next(MI)) {
981 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Bob Wilson84945262009-05-12 17:09:30 +0000982 if (!OffsetIsInRange(Offset, EndInsertOffset,
Dale Johannesenb71aa2b2007-02-28 23:20:38 +0000983 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
984 BaseInsertOffset -= (isThumb ? 2 : 4);
985 EndInsertOffset -= (isThumb ? 2 : 4);
986 }
987 // This is overly conservative, as we don't account for CPEMIs
988 // being reused within the block, but it doesn't matter much.
989 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
990 CPUIndex++;
991 }
992 }
993 DOUT << "Split in middle of big block\n";
994 *NewMBB = SplitBlockBeforeInstr(prior(MI));
995 }
996}
997
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000998/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
999/// is out-of-range. If so, pick it up the constant pool value and move it some
1000/// place in-range. Return true if we changed any addresses (thus must run
1001/// another pass of branch lengthening), false otherwise.
Bob Wilson84945262009-05-12 17:09:30 +00001002bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1003 unsigned CPUserIndex) {
Dale Johannesenf1b214d2007-02-28 18:41:23 +00001004 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001005 MachineInstr *UserMI = U.MI;
1006 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001007 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001008 unsigned Size = CPEMI->getOperand(2).getImm();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001009 MachineBasicBlock *NewMBB;
Dale Johannesen8593e412007-04-29 19:19:30 +00001010 // Compute this only once, it's expensive. The 4 or 8 is the value the
1011 // hardware keeps in the PC (2 insns ahead of the reference).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001012 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
Evan Cheng768c9f72007-04-27 08:14:15 +00001013
Evan Cheng185ea1e2007-04-27 18:27:13 +00001014 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1015 // second instruction.
1016 if (UserMI->getOpcode() == ARM::tLEApcrel)
Evan Cheng768c9f72007-04-27 08:14:15 +00001017 UserOffset += 2;
Bob Wilson84945262009-05-12 17:09:30 +00001018
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001019 // See if the current entry is within range, or there is a clone of it
1020 // in range.
1021 int result = LookForExistingCPEntry(U, UserOffset);
1022 if (result==1) return false;
1023 else if (result==2) return true;
1024
1025 // No existing clone of this CPE is within range.
1026 // We will be generating a new clone. Get a UID for it.
Evan Chengf1bbb952008-11-08 00:51:41 +00001027 unsigned ID = AFI->createConstPoolEntryUId();
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001028
1029 // Look for water where we can place this CPE. We look for the farthest one
1030 // away that will work. Forward references only for now (although later
1031 // we might find some that are backwards).
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001032
Dale Johannesen8593e412007-04-29 19:19:30 +00001033 if (!LookForWater(U, UserOffset, &NewMBB)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001034 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001035 DOUT << "No water found\n";
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001036 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001037 }
1038
1039 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001040 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1041 Fn.insert(NewMBB, NewIsland);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001042
1043 // Update internal data structures to account for the newly inserted MBB.
1044 UpdateForInsertedWaterBlock(NewIsland);
1045
1046 // Decrement the old entry, and remove it if refcount becomes 0.
Evan Chenged884f32007-04-03 23:39:48 +00001047 DecrementOldEntry(CPI, CPEMI);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001048
1049 // Now that we have an island to add the CPE to, clone the original CPE and
1050 // add it to the island.
Dale Johannesenb6728402009-02-13 02:25:56 +00001051 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1052 TII->get(ARM::CONSTPOOL_ENTRY))
Evan Chenga8e29892007-01-19 07:51:42 +00001053 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001054 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +00001055 NumCPEs++;
1056
Dale Johannesen8593e412007-04-29 19:19:30 +00001057 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
Evan Chengb43216e2007-02-01 10:16:15 +00001058 // Compensate for .align 2 in thumb mode.
Bob Wilson84945262009-05-12 17:09:30 +00001059 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dale Johannesen8593e412007-04-29 19:19:30 +00001060 Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +00001061 // Increase the size of the island block to account for the new entry.
1062 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001063 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilson84945262009-05-12 17:09:30 +00001064
Evan Chenga8e29892007-01-19 07:51:42 +00001065 // Finally, change the CPI in the instruction operand to be ID.
1066 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmand735b802008-10-03 15:45:36 +00001067 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner8aa797a2007-12-30 23:10:15 +00001068 UserMI->getOperand(i).setIndex(ID);
Evan Chenga8e29892007-01-19 07:51:42 +00001069 break;
1070 }
Bob Wilson84945262009-05-12 17:09:30 +00001071
Evan Chengc99ef082007-02-09 20:54:44 +00001072 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilson84945262009-05-12 17:09:30 +00001073
Evan Chenga8e29892007-01-19 07:51:42 +00001074 return true;
1075}
1076
Evan Chenged884f32007-04-03 23:39:48 +00001077/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1078/// sizes and offsets of impacted basic blocks.
1079void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1080 MachineBasicBlock *CPEBB = CPEMI->getParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001081 unsigned Size = CPEMI->getOperand(2).getImm();
1082 CPEMI->eraseFromParent();
1083 BBSizes[CPEBB->getNumber()] -= Size;
1084 // All succeeding offsets have the current size value added in, fix this.
Evan Chenged884f32007-04-03 23:39:48 +00001085 if (CPEBB->empty()) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001086 // In thumb mode, the size of island may be padded by two to compensate for
1087 // the alignment requirement. Then it will now be 2 when the block is
Evan Chenged884f32007-04-03 23:39:48 +00001088 // empty, so fix this.
1089 // All succeeding offsets have the current size value added in, fix this.
1090 if (BBSizes[CPEBB->getNumber()] != 0) {
Dale Johannesen8593e412007-04-29 19:19:30 +00001091 Size += BBSizes[CPEBB->getNumber()];
Evan Chenged884f32007-04-03 23:39:48 +00001092 BBSizes[CPEBB->getNumber()] = 0;
1093 }
Evan Chenged884f32007-04-03 23:39:48 +00001094 }
Dale Johannesen8593e412007-04-29 19:19:30 +00001095 AdjustBBOffsetsAfter(CPEBB, -Size);
1096 // An island has only one predecessor BB and one successor BB. Check if
1097 // this BB's predecessor jumps directly to this BB's successor. This
1098 // shouldn't happen currently.
1099 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1100 // FIXME: remove the empty blocks after all the work is done?
Evan Chenged884f32007-04-03 23:39:48 +00001101}
1102
1103/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1104/// are zero.
1105bool ARMConstantIslands::RemoveUnusedCPEntries() {
1106 unsigned MadeChange = false;
1107 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1108 std::vector<CPEntry> &CPEs = CPEntries[i];
1109 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1110 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1111 RemoveDeadCPEMI(CPEs[j].CPEMI);
1112 CPEs[j].CPEMI = NULL;
1113 MadeChange = true;
1114 }
1115 }
Bob Wilson84945262009-05-12 17:09:30 +00001116 }
Evan Chenged884f32007-04-03 23:39:48 +00001117 return MadeChange;
1118}
1119
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001120/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +00001121/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +00001122bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1123 unsigned MaxDisp) {
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001124 unsigned PCAdj = isThumb ? 4 : 8;
Evan Chengc0dbec72007-01-31 19:57:44 +00001125 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001126 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +00001127
Evan Chengc99ef082007-02-09 20:54:44 +00001128 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1129 << " from BB#" << MI->getParent()->getNumber()
1130 << " max delta=" << MaxDisp
Dale Johannesen8593e412007-04-29 19:19:30 +00001131 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1132 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +00001133
Dale Johannesen8593e412007-04-29 19:19:30 +00001134 if (BrOffset <= DestOffset) {
1135 // Branch before the Dest.
1136 if (DestOffset-BrOffset <= MaxDisp)
1137 return true;
1138 } else {
1139 if (BrOffset-DestOffset <= MaxDisp)
1140 return true;
1141 }
1142 return false;
Evan Cheng43aeab62007-01-26 20:38:26 +00001143}
1144
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001145/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1146/// away to fit in its displacement field.
1147bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001148 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001149 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001150
Evan Chengc0dbec72007-01-31 19:57:44 +00001151 // Check to see if the DestBB is already in-range.
1152 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +00001153 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001154
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001155 if (!Br.isCond)
1156 return FixUpUnconditionalBr(Fn, Br);
1157 return FixUpConditionalBr(Fn, Br);
1158}
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001159
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001160/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1161/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001162/// spilled in the epilogue, then we can use BL to implement a far jump.
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001163/// Otherwise, add an intermediate branch instruction to to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001164bool
1165ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1166 MachineInstr *MI = Br.MI;
1167 MachineBasicBlock *MBB = MI->getParent();
Dale Johannesenb71aa2b2007-02-28 23:20:38 +00001168 assert(isThumb && "Expected a Thumb function!");
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001169
1170 // Use BL to implement far jump.
1171 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner5080f4d2008-01-11 18:10:50 +00001172 MI->setDesc(TII->get(ARM::tBfar));
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001173 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +00001174 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001175 HasFarJump = true;
1176 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001177
Evan Chengc99ef082007-02-09 20:54:44 +00001178 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001179
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001180 return true;
1181}
1182
Dale Johannesen88e37ae2007-02-23 05:02:36 +00001183/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001184/// far away to fit in its displacement field. It is converted to an inverse
1185/// conditional branch + an unconditional branch to the destination.
1186bool
1187ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1188 MachineInstr *MI = Br.MI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001189 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001190
1191 // Add a unconditional branch to the destination and invert the branch
1192 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001193 // blt L1
1194 // =>
1195 // bge L2
1196 // b L1
1197 // L2:
Chris Lattner9a1ceae2007-12-30 20:49:49 +00001198 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001199 CC = ARMCC::getOppositeCondition(CC);
Evan Cheng0e1d3792007-07-05 07:18:20 +00001200 unsigned CCReg = MI->getOperand(2).getReg();
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001201
1202 // If the branch is at the end of its MBB and that has a fall-through block,
1203 // direct the updated conditional branch to the fall-through block. Otherwise,
1204 // split the MBB before the next instruction.
1205 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +00001206 MachineInstr *BMI = &MBB->back();
1207 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001208
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001209 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001210 if (BMI != MI) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001211 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Evan Chengbd5d3db2007-02-03 02:08:34 +00001212 BMI->getOpcode() == Br.UncondBr) {
Evan Cheng43aeab62007-01-26 20:38:26 +00001213 // Last MI in the BB is a unconditional branch. Can we simply invert the
1214 // condition and swap destinations:
1215 // beq L1
1216 // b L2
1217 // =>
1218 // bne L2
1219 // b L1
Chris Lattner8aa797a2007-12-30 23:10:15 +00001220 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Evan Chengc0dbec72007-01-31 19:57:44 +00001221 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +00001222 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner8aa797a2007-12-30 23:10:15 +00001223 BMI->getOperand(0).setMBB(DestBB);
1224 MI->getOperand(0).setMBB(NewDest);
Evan Cheng43aeab62007-01-26 20:38:26 +00001225 MI->getOperand(1).setImm(CC);
1226 return true;
1227 }
1228 }
1229 }
1230
1231 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001232 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +00001233 // No need for the branch to the next block. We're adding a unconditional
1234 // branch to the destination.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001235 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001236 BBSizes[MBB->getNumber()] -= delta;
Dale Johannesen8593e412007-04-29 19:19:30 +00001237 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1238 AdjustBBOffsetsAfter(SplitBB, -delta);
Evan Chengdd353b82007-01-26 02:02:39 +00001239 MBB->back().eraseFromParent();
Dale Johannesen8593e412007-04-29 19:19:30 +00001240 // BBOffsets[SplitBB] is wrong temporarily, fixed below
Evan Chengdd353b82007-01-26 02:02:39 +00001241 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001242 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilson84945262009-05-12 17:09:30 +00001243
Evan Chengc99ef082007-02-09 20:54:44 +00001244 DOUT << " Insert B to BB#" << DestBB->getNumber()
1245 << " also invert condition and change dest. to BB#"
1246 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001247
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001248 // Insert a new conditional branch and a new unconditional branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001249 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesenb6728402009-02-13 02:25:56 +00001250 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1251 TII->get(MI->getOpcode()))
1252 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001253 Br.MI = &MBB->back();
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001254 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesenb6728402009-02-13 02:25:56 +00001255 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001256 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001257 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001258 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001259
1260 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001261 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001262 MI->eraseFromParent();
1263
Dale Johannesen56c42ef2007-04-23 20:09:04 +00001264 // The net size change is an addition of one unconditional branch.
Nicolas Geoffray52e724a2008-04-16 20:10:13 +00001265 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesen99c49a42007-02-25 00:47:03 +00001266 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001267 return true;
1268}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001269
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001270/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1271/// LR / restores LR to pc.
1272bool ARMConstantIslands::UndoLRSpillRestore() {
1273 bool MadeChange = false;
1274 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1275 MachineInstr *MI = PushPopMIs[i];
Evan Cheng44bec522007-05-15 01:29:07 +00001276 if (MI->getOpcode() == ARM::tPOP_RET &&
1277 MI->getOperand(0).getReg() == ARM::PC &&
1278 MI->getNumExplicitOperands() == 1) {
Dale Johannesenb6728402009-02-13 02:25:56 +00001279 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Evan Cheng44bec522007-05-15 01:29:07 +00001280 MI->eraseFromParent();
1281 MadeChange = true;
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001282 }
1283 }
1284 return MadeChange;
1285}