blob: 91c45db67a90f7d56c4945190932b376db28756e [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 {
50 /// NextUID - Assign unique ID's to CPE's.
51 unsigned NextUID;
Dale Johannesen99c49a42007-02-25 00:47:03 +000052
Evan Chenga8e29892007-01-19 07:51:42 +000053 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
54 /// by MBB Number.
Evan Chenge03cff62007-02-09 23:59:14 +000055 std::vector<unsigned> BBSizes;
Evan Chenga8e29892007-01-19 07:51:42 +000056
Dale Johannesen99c49a42007-02-25 00:47:03 +000057 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
58 std::vector<unsigned> BBOffsets;
59
Evan Chenga8e29892007-01-19 07:51:42 +000060 /// WaterList - A sorted list of basic blocks where islands could be placed
61 /// (i.e. blocks that don't fall through to the following block, due
62 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000063 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000064
Evan Chenga8e29892007-01-19 07:51:42 +000065 /// CPUser - One user of a constant pool, keeping the machine instruction
66 /// pointer, the constant pool being referenced, and the max displacement
67 /// allowed from the instruction to the CP.
68 struct CPUser {
69 MachineInstr *MI;
70 MachineInstr *CPEMI;
71 unsigned MaxDisp;
72 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
73 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
74 };
75
76 /// CPUsers - Keep track of all of the machine instructions that use various
77 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000078 std::vector<CPUser> CPUsers;
Evan Chengc99ef082007-02-09 20:54:44 +000079
80 /// CPEntry - One per constant pool entry, keeping the machine instruction
81 /// pointer, the constpool index, and the number of CPUser's which
82 /// reference this entry.
83 struct CPEntry {
84 MachineInstr *CPEMI;
85 unsigned CPI;
86 unsigned RefCount;
87 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
88 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
89 };
90
91 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +000092 /// instructions. For each original constpool index (i.e. those that
93 /// existed upon entry to this pass), it keeps a vector of entries.
94 /// Original elements are cloned as we go along; the clones are
95 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +000096 std::vector<std::vector<CPEntry> > CPEntries;
Evan Chenga8e29892007-01-19 07:51:42 +000097
Evan Chengaf5cbcb2007-01-25 03:12:46 +000098 /// ImmBranch - One per immediate branch, keeping the machine instruction
99 /// pointer, conditional or unconditional, the max displacement,
100 /// and (if isCond is true) the corresponding unconditional branch
101 /// opcode.
102 struct ImmBranch {
103 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000104 unsigned MaxDisp : 31;
105 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000106 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000107 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
108 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000109 };
110
Evan Chengc2854142007-01-25 23:18:59 +0000111 /// Branches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000112 ///
Evan Chenge03cff62007-02-09 23:59:14 +0000113 std::vector<ImmBranch> ImmBranches;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000114
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000115 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
116 ///
Evan Chengc99ef082007-02-09 20:54:44 +0000117 SmallVector<MachineInstr*, 4> PushPopMIs;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000118
119 /// HasFarJump - True if any far jump instruction has been emitted during
120 /// the branch fix up pass.
121 bool HasFarJump;
122
Evan Chenga8e29892007-01-19 07:51:42 +0000123 const TargetInstrInfo *TII;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000124 const ARMFunctionInfo *AFI;
Evan Chenga8e29892007-01-19 07:51:42 +0000125 public:
126 virtual bool runOnMachineFunction(MachineFunction &Fn);
127
128 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000129 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000130 }
131
132 private:
133 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000134 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000135 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000136 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000137 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000138 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000139 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000140 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000141 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI, unsigned Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000142 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000143 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000144 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
145 MachineInstr *CPEMI, unsigned Disp,
146 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000147 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000148 unsigned Disp);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000149 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
150 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000151 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000152 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
153 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
154 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
155 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000156
Evan Chenga8e29892007-01-19 07:51:42 +0000157 unsigned GetOffsetOf(MachineInstr *MI) const;
158 };
159}
160
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000161/// createARMConstantIslandPass - returns an instance of the constpool
162/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000163FunctionPass *llvm::createARMConstantIslandPass() {
164 return new ARMConstantIslands();
165}
166
167bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000168 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000169
170 TII = Fn.getTarget().getInstrInfo();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000171 AFI = Fn.getInfo<ARMFunctionInfo>();
172
173 HasFarJump = false;
174
Evan Chenga8e29892007-01-19 07:51:42 +0000175 // Renumber all of the machine basic blocks in the function, guaranteeing that
176 // the numbers agree with the position of the block in the function.
177 Fn.RenumberBlocks();
178
179 // Perform the initial placement of the constant pool entries. To start with,
180 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000181 std::vector<MachineInstr*> CPEMIs;
Evan Cheng7755fac2007-01-26 01:04:44 +0000182 if (!MCP.isEmpty())
183 DoInitialPlacement(Fn, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000184
185 /// The next UID to take is the first unused one.
186 NextUID = CPEMIs.size();
187
188 // Do the initial scan of the function, building up information about the
189 // sizes of each block, the location of all the water, and finding all of the
190 // constant pool users.
191 InitialFunctionScan(Fn, CPEMIs);
192 CPEMIs.clear();
193
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000194 // Iteratively place constant pool entries and fix up branches until there
195 // is no change.
196 bool MadeChange = false;
197 while (true) {
198 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000199 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000200 Change |= HandleConstantPoolUser(Fn, i);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000201 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000202 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
203 if (!Change)
204 break;
205 MadeChange = true;
206 }
Evan Chenga8e29892007-01-19 07:51:42 +0000207
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000208 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
209 // Undo the spill / restore of LR if possible.
210 if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
211 MadeChange |= UndoLRSpillRestore();
212
Evan Chenga8e29892007-01-19 07:51:42 +0000213 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000214 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000215 WaterList.clear();
216 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000217 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000218 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000219 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000220
221 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000222}
223
224/// DoInitialPlacement - Perform the initial placement of the constant pool
225/// entries. To start with, we put them all at the end of the function.
226void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000227 std::vector<MachineInstr*> &CPEMIs){
Evan Chenga8e29892007-01-19 07:51:42 +0000228 // Create the basic block to hold the CPE's.
229 MachineBasicBlock *BB = new MachineBasicBlock();
230 Fn.getBasicBlockList().push_back(BB);
231
232 // Add all of the constants from the constant pool to the end block, use an
233 // identity mapping of CPI's to CPE's.
234 const std::vector<MachineConstantPoolEntry> &CPs =
235 Fn.getConstantPool()->getConstants();
236
237 const TargetData &TD = *Fn.getTarget().getTargetData();
238 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
239 unsigned Size = TD.getTypeSize(CPs[i].getType());
240 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
241 // we would have to pad them out or something so that instructions stay
242 // aligned.
243 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
244 MachineInstr *CPEMI =
245 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
246 .addImm(i).addConstantPoolIndex(i).addImm(Size);
247 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000248
249 // Add a new CPEntry, but no corresponding CPUser yet.
250 std::vector<CPEntry> CPEs;
251 CPEs.push_back(CPEntry(CPEMI, i));
252 CPEntries.push_back(CPEs);
253 NumCPEs++;
254 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000255 }
256}
257
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000258/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000259/// into the block immediately after it.
260static bool BBHasFallthrough(MachineBasicBlock *MBB) {
261 // Get the next machine basic block in the function.
262 MachineFunction::iterator MBBI = MBB;
263 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
264 return false;
265
266 MachineBasicBlock *NextBB = next(MBBI);
267 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
268 E = MBB->succ_end(); I != E; ++I)
269 if (*I == NextBB)
270 return true;
271
272 return false;
273}
274
Evan Chengc99ef082007-02-09 20:54:44 +0000275/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
276/// look up the corresponding CPEntry.
277ARMConstantIslands::CPEntry
278*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
279 const MachineInstr *CPEMI) {
280 std::vector<CPEntry> &CPEs = CPEntries[CPI];
281 // Number of entries per constpool index should be small, just do a
282 // linear search.
283 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
284 if (CPEs[i].CPEMI == CPEMI)
285 return &CPEs[i];
286 }
287 return NULL;
288}
289
Evan Chenga8e29892007-01-19 07:51:42 +0000290/// InitialFunctionScan - Do the initial scan of the function, building up
291/// information about the sizes of each block, the location of all the water,
292/// and finding all of the constant pool users.
293void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000294 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000295 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000296 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
297 MBBI != E; ++MBBI) {
298 MachineBasicBlock &MBB = *MBBI;
299
300 // If this block doesn't fall through into the next MBB, then this is
301 // 'water' that a constant pool island could be placed.
302 if (!BBHasFallthrough(&MBB))
303 WaterList.push_back(&MBB);
304
305 unsigned MBBSize = 0;
306 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
307 I != E; ++I) {
308 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000309 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000310
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000311 int Opc = I->getOpcode();
312 if (TII->isBranch(Opc)) {
313 bool isCond = false;
314 unsigned Bits = 0;
315 unsigned Scale = 1;
316 int UOpc = Opc;
317 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000318 default:
319 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000320 case ARM::Bcc:
321 isCond = true;
322 UOpc = ARM::B;
323 // Fallthrough
324 case ARM::B:
325 Bits = 24;
326 Scale = 4;
327 break;
328 case ARM::tBcc:
329 isCond = true;
330 UOpc = ARM::tB;
331 Bits = 8;
332 Scale = 2;
333 break;
334 case ARM::tB:
335 Bits = 11;
336 Scale = 2;
337 break;
338 }
Evan Chengb43216e2007-02-01 10:16:15 +0000339
340 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000341 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000342 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000343 }
344
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000345 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
346 PushPopMIs.push_back(I);
347
Evan Chenga8e29892007-01-19 07:51:42 +0000348 // Scan the instructions for constant pool operands.
349 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
350 if (I->getOperand(op).isConstantPoolIndex()) {
351 // We found one. The addressing mode tells us the max displacement
352 // from the PC that this instruction permits.
Evan Chenga8e29892007-01-19 07:51:42 +0000353
354 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000355 unsigned Bits = 0;
356 unsigned Scale = 1;
Evan Chenga8e29892007-01-19 07:51:42 +0000357 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
358 switch (TSFlags & ARMII::AddrModeMask) {
359 default:
360 // Constant pool entries can reach anything.
361 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
362 continue;
363 assert(0 && "Unknown addressing mode for CP reference!");
364 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000365 Bits = 8;
366 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000367 break;
368 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000369 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000370 break;
371 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000372 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000373 break;
374 // addrmode4 has no immediate offset.
375 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000376 Bits = 8;
377 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000378 break;
379 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000380 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000381 break;
382 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000383 Bits = 5;
384 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000385 break;
386 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000387 Bits = 5;
388 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000389 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000390 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000391 Bits = 8;
392 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000393 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000394 }
Evan Chengb43216e2007-02-01 10:16:15 +0000395
Evan Chenga8e29892007-01-19 07:51:42 +0000396 // Remember that this is a user of a CP entry.
Evan Chengc99ef082007-02-09 20:54:44 +0000397 unsigned CPI = I->getOperand(op).getConstantPoolIndex();
398 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng556f33c2007-02-01 20:44:52 +0000399 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000400 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000401
402 // Increment corresponding CPEntry reference count.
403 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
404 assert(CPE && "Cannot find a corresponding CPEntry!");
405 CPE->RefCount++;
Evan Chenga8e29892007-01-19 07:51:42 +0000406
407 // Instructions can only use one CP entry, don't bother scanning the
408 // rest of the operands.
409 break;
410 }
411 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000412
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000413 // In thumb mode, if this block is a constpool island, pessimistically
414 // assume it needs to be padded by two byte so it's aligned on 4 byte
415 // boundary.
Evan Cheng2021abe2007-02-01 01:09:47 +0000416 if (AFI->isThumbFunction() &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000417 !MBB.empty() &&
Evan Cheng2021abe2007-02-01 01:09:47 +0000418 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
419 MBBSize += 2;
420
Evan Chenga8e29892007-01-19 07:51:42 +0000421 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000422 BBOffsets.push_back(Offset);
423 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000424 }
425}
426
Evan Chenga8e29892007-01-19 07:51:42 +0000427/// GetOffsetOf - Return the current offset of the specified machine instruction
428/// from the start of the function. This offset changes as stuff is moved
429/// around inside the function.
430unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
431 MachineBasicBlock *MBB = MI->getParent();
432
433 // The offset is composed of two things: the sum of the sizes of all MBB's
434 // before this instruction's block, and the offset from the start of the block
435 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000436 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000437
438 // Sum instructions before MI in MBB.
439 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
440 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
441 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000442 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000443 }
444}
445
446/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
447/// ID.
448static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
449 const MachineBasicBlock *RHS) {
450 return LHS->getNumber() < RHS->getNumber();
451}
452
453/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
454/// machine function, it upsets all of the block numbers. Renumber the blocks
455/// and update the arrays that parallel this numbering.
456void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
457 // Renumber the MBB's to keep them consequtive.
458 NewBB->getParent()->RenumberBlocks(NewBB);
459
460 // Insert a size into BBSizes to align it properly with the (newly
461 // renumbered) block numbers.
462 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000463
464 // Likewise for BBOffsets.
465 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Evan Chenga8e29892007-01-19 07:51:42 +0000466
467 // Next, update WaterList. Specifically, we need to add NewMBB as having
468 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000469 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000470 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
471 CompareMBBNumbers);
472 WaterList.insert(IP, NewBB);
473}
474
475
476/// Split the basic block containing MI into two blocks, which are joined by
477/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000478/// account for this change and returns the newly created block.
479MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000480 MachineBasicBlock *OrigBB = MI->getParent();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000481 bool isThumb = AFI->isThumbFunction();
Evan Chenga8e29892007-01-19 07:51:42 +0000482
483 // Create a new MBB for the code after the OrigBB.
484 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
485 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
486 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
487
488 // Splice the instructions starting with MI over to NewBB.
489 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
490
491 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000492 // Note the new unconditional branch is not being recorded.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000493 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000494 NumSplit++;
495
496 // Update the CFG. All succs of OrigBB are now succs of NewBB.
497 while (!OrigBB->succ_empty()) {
498 MachineBasicBlock *Succ = *OrigBB->succ_begin();
499 OrigBB->removeSuccessor(Succ);
500 NewBB->addSuccessor(Succ);
501
502 // This pass should be run after register allocation, so there should be no
503 // PHI nodes to update.
504 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
505 && "PHI nodes should be eliminated by now!");
506 }
507
508 // OrigBB branches to NewBB.
509 OrigBB->addSuccessor(NewBB);
510
511 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000512 // This is almost the same as UpdateForInsertedWaterBlock, except that
513 // the Water goes after OrigBB, not NewBB.
514 NewBB->getParent()->RenumberBlocks(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000515
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000516 // Insert a size into BBSizes to align it properly with the (newly
517 // renumbered) block numbers.
518 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
519
Dale Johannesen99c49a42007-02-25 00:47:03 +0000520 // Likewise for BBOffsets.
521 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
522
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000523 // Next, update WaterList. Specifically, we need to add OrigMBB as having
524 // available water after it (but not if it's already there, which happens
525 // when splitting before a conditional branch that is followed by an
526 // unconditional branch - in that case we want to insert NewBB).
527 std::vector<MachineBasicBlock*>::iterator IP =
528 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
529 CompareMBBNumbers);
530 MachineBasicBlock* WaterBB = *IP;
531 if (WaterBB == OrigBB)
532 WaterList.insert(next(IP), NewBB);
533 else
534 WaterList.insert(IP, OrigBB);
535
Evan Chenga8e29892007-01-19 07:51:42 +0000536 // Figure out how large the first NewMBB is.
537 unsigned NewBBSize = 0;
538 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
539 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000540 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000541
Dale Johannesen99c49a42007-02-25 00:47:03 +0000542 unsigned OrigBBI = OrigBB->getNumber();
543 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000544 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000545 BBSizes[NewBBI] = NewBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000546
547 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000548 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000549 unsigned delta = isThumb ? 2 : 4;
550 BBSizes[OrigBBI] -= NewBBSize - delta;
551
552 // ...and adjust BBOffsets for NewBB accordingly.
553 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
554
555 // All BBOffsets following these blocks must be modified.
556 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000557
558 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000559}
560
Dale Johannesence74de42007-02-25 18:31:31 +0000561/// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
Dale Johannesen99c49a42007-02-25 00:47:03 +0000562/// TrialOffset.
563bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
564 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
565 if (UserOffset <= TrialOffset) {
566 // User before the Trial.
567 if (TrialOffset-UserOffset <= MaxDisp)
568 return true;
569 } else if (NegativeOK) {
570 if (UserOffset-TrialOffset <= MaxDisp)
571 return true;
572 }
573 return false;
574}
575
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000576/// WaterIsInRange - Returns true if a CPE placed after the specified
577/// Water (a basic block) will be in range for the specific MI.
578
579bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000580 MachineBasicBlock* Water, unsigned MaxDisp)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000581{
Dale Johannesen99c49a42007-02-25 00:47:03 +0000582 bool isThumb = AFI->isThumbFunction();
583 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000584 BBSizes[Water->getNumber()];
585 // If the Water is a constpool island, it has already been aligned.
586 // If not, align it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000587 if (isThumb &&
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000588 (Water->empty() ||
589 Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
590 CPEOffset += 2;
591
Dale Johannesen99c49a42007-02-25 00:47:03 +0000592 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000593}
594
595/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000596/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000597bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
598 MachineInstr *CPEMI,
599 unsigned MaxDisp, bool DoDump) {
600 // In thumb mode, pessimistically assumes the .align 2 before the first CPE
Evan Cheng2021abe2007-02-01 01:09:47 +0000601 // in the island adds two byte padding.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000602 bool isThumb = AFI->isThumbFunction();
603 unsigned AlignAdj = isThumb ? 2 : 0;
Evan Cheng2021abe2007-02-01 01:09:47 +0000604 unsigned CPEOffset = GetOffsetOf(CPEMI) + AlignAdj;
605
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000606 if (DoDump) {
607 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
608 << " max delta=" << MaxDisp
609 << " insn address=" << UserOffset
610 << " CPE address=" << CPEOffset
611 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
612 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000613
Dale Johannesen99c49a42007-02-25 00:47:03 +0000614 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000615}
616
Evan Chengc99ef082007-02-09 20:54:44 +0000617/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
618/// unconditionally branches to its only successor.
619static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
620 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
621 return false;
622
623 MachineBasicBlock *Succ = *MBB->succ_begin();
624 MachineBasicBlock *Pred = *MBB->pred_begin();
625 MachineInstr *PredMI = &Pred->back();
626 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
627 return PredMI->getOperand(0).getMBB() == Succ;
628 return false;
629}
630
Dale Johannesen99c49a42007-02-25 00:47:03 +0000631void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
632{
633 MachineFunction::iterator MBBI = BB->getParent()->end();
Dale Johannesence74de42007-02-25 18:31:31 +0000634 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++)
Dale Johannesen99c49a42007-02-25 00:47:03 +0000635 BBOffsets[i] += delta;
636}
637
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000638/// DecrementOldEntry - find the constant pool entry with index CPI
639/// and instruction CPEMI, and decrement its refcount. If the refcount
640/// becomes 0 remove the entry and instruction. Returns true if we removed
641/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000642
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000643bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI,
644 unsigned Size) {
Evan Chengc99ef082007-02-09 20:54:44 +0000645 // Find the old entry. Eliminate it if it is no longer used.
646 CPEntry *OldCPE = findConstPoolEntry(CPI, CPEMI);
647 assert(OldCPE && "Unexpected!");
648 if (--OldCPE->RefCount == 0) {
649 MachineBasicBlock *OldCPEBB = OldCPE->CPEMI->getParent();
650 if (OldCPEBB->empty()) {
651 // In thumb mode, the size of island is padded by two to compensate for
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000652 // the alignment requirement. Thus it will now be 2 when the block is
653 // empty, so fix this.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000654 // All succeeding offsets have the current size value added in, fix this.
655 if (BBSizes[OldCPEBB->getNumber()] != 0) {
656 AdjustBBOffsetsAfter(OldCPEBB, -BBSizes[OldCPEBB->getNumber()]);
657 BBSizes[OldCPEBB->getNumber()] = 0;
658 }
Evan Chengc99ef082007-02-09 20:54:44 +0000659 // An island has only one predecessor BB and one successor BB. Check if
660 // this BB's predecessor jumps directly to this BB's successor. This
661 // shouldn't happen currently.
662 assert(!BBIsJumpedOver(OldCPEBB) && "How did this happen?");
663 // FIXME: remove the empty blocks after all the work is done?
Dale Johannesen99c49a42007-02-25 00:47:03 +0000664 } else {
Evan Chengc99ef082007-02-09 20:54:44 +0000665 BBSizes[OldCPEBB->getNumber()] -= Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000666 // All succeeding offsets have the current size value added in, fix this.
667 AdjustBBOffsetsAfter(OldCPEBB, -Size);
668 }
Evan Chengc99ef082007-02-09 20:54:44 +0000669 OldCPE->CPEMI->eraseFromParent();
670 OldCPE->CPEMI = NULL;
671 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000672 return true;
673 }
674 return false;
675}
676
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000677/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
678/// if not, see if an in-range clone of the CPE is in range, and if so,
679/// change the data structures so the user references the clone. Returns:
680/// 0 = no existing entry found
681/// 1 = entry found, and there were no code insertions or deletions
682/// 2 = entry found, and there were code insertions or deletions
683int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
684{
685 MachineInstr *UserMI = U.MI;
686 MachineInstr *CPEMI = U.CPEMI;
687
688 // Check to see if the CPE is already in-range.
689 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
690 DOUT << "In range\n";
691 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000692 }
693
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000694 // No. Look for previously created clones of the CPE that are in range.
695 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
696 std::vector<CPEntry> &CPEs = CPEntries[CPI];
697 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
698 // We already tried this one
699 if (CPEs[i].CPEMI == CPEMI)
700 continue;
701 // Removing CPEs can leave empty entries, skip
702 if (CPEs[i].CPEMI == NULL)
703 continue;
704 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
705 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
706 // Point the CPUser node to the replacement
707 U.CPEMI = CPEs[i].CPEMI;
708 // Change the CPI in the instruction operand to refer to the clone.
709 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
710 if (UserMI->getOperand(j).isConstantPoolIndex()) {
711 UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
712 break;
713 }
714 // Adjust the refcount of the clone...
715 CPEs[i].RefCount++;
716 // ...and the original. If we didn't remove the old entry, none of the
717 // addresses changed, so we don't need another pass.
718 unsigned Size = CPEMI->getOperand(2).getImm();
719 return DecrementOldEntry(CPI, CPEMI, Size) ? 2 : 1;
720 }
721 }
722 return 0;
723}
724
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000725/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
726/// the specific unconditional branch instruction.
727static inline unsigned getUnconditionalBrDisp(int Opc) {
728 return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
729}
730
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000731/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
732/// is out-of-range. If so, pick it up the constant pool value and move it some
733/// place in-range. Return true if we changed any addresses (thus must run
734/// another pass of branch lengthening), false otherwise.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000735bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
736 unsigned CPUserIndex){
737 CPUser &U = CPUsers[CPUserIndex];
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000738 MachineInstr *UserMI = U.MI;
739 MachineInstr *CPEMI = U.CPEMI;
740 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
741 unsigned Size = CPEMI->getOperand(2).getImm();
742 bool isThumb = AFI->isThumbFunction();
743 MachineBasicBlock *NewMBB;
744 // Compute this only once, it's expensive
745 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
746
747 // See if the current entry is within range, or there is a clone of it
748 // in range.
749 int result = LookForExistingCPEntry(U, UserOffset);
750 if (result==1) return false;
751 else if (result==2) return true;
752
753 // No existing clone of this CPE is within range.
754 // We will be generating a new clone. Get a UID for it.
755 unsigned ID = NextUID++;
756
757 // Look for water where we can place this CPE. We look for the farthest one
758 // away that will work. Forward references only for now (although later
759 // we might find some that are backwards).
760 bool WaterFound = false;
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000761 bool PadNewWater = true;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000762 if (!WaterList.empty()) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000763 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
764 B = WaterList.begin();; --IP) {
765 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000766 if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000767 WaterFound = true;
768 DOUT << "found water in range\n";
769 // CPE goes before following block (NewMBB).
770 NewMBB = next(MachineFunction::iterator(WaterBB));
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000771 // If WaterBB is an island, don't pad the new island.
772 // If WaterBB is empty, go backwards until we find something that
773 // isn't. WaterBB may become empty if it's an island whose
774 // contents were moved farther back.
775 if (isThumb) {
776 MachineBasicBlock* BB = WaterBB;
777 while (BB->empty())
778 BB = BB->Prev;
779 if (BB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
780 PadNewWater = false;
781 }
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000782 // Remove the original WaterList entry; we want subsequent
783 // insertions in this vicinity to go after the one we're
784 // about to insert. This considerably reduces the number
785 // of times we have to move the same CPE more than once.
786 WaterList.erase(IP);
787 break;
788 }
789 if (IP == B)
790 break;
791 }
792 }
793
794 if (!WaterFound) {
795 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000796
797 DOUT << "No water found\n";
798 MachineBasicBlock *UserMBB = UserMI->getParent();
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000799 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
800 BBSizes[UserMBB->getNumber()];
801 assert(OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()+1]);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000802
Dale Johannesen99c49a42007-02-25 00:47:03 +0000803 // If the use is at the end of the block, or the end of the block
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000804 // is within range, make new water there. (The +2 or 4 below is
805 // for the unconditional branch we will be adding. If the block ends in
Dale Johannesen99c49a42007-02-25 00:47:03 +0000806 // an unconditional branch already, it is water, and is known to
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000807 // be out of range, so we'll always be adding one.)
Dale Johannesen99c49a42007-02-25 00:47:03 +0000808 if (&UserMBB->back() == UserMI ||
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000809 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2 : 4),
810 U.MaxDisp, !isThumb)) {
811 DOUT << "Split at end of block\n";
Dale Johannesen99c49a42007-02-25 00:47:03 +0000812 if (&UserMBB->back() == UserMI)
813 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000814 NewMBB = next(MachineFunction::iterator(UserMBB));
815 // Add an unconditional branch from UserMBB to fallthrough block.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000816 // Record it for branch lengthening; this new branch will not get out of
817 // range, but if the preceding conditional branch is out of range, the
818 // targets will be exchanged, and the altered branch may be out of
819 // range, so the machinery has to know about it.
820 int UncondBr = isThumb ? ARM::tB : ARM::B;
821 BuildMI(UserMBB, TII->get(UncondBr)).addMBB(NewMBB);
822 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
823 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
824 MaxDisp, false, UncondBr));
Dale Johannesen99c49a42007-02-25 00:47:03 +0000825 int delta = isThumb ? 2 : 4;
826 BBSizes[UserMBB->getNumber()] += delta;
827 AdjustBBOffsetsAfter(UserMBB, delta);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000828 } else {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000829 // What a big block. Find a place within the block to split it.
830 // This is a little tricky on Thumb since instructions are 2 bytes
831 // and constant pool entries are 4 bytes: if instruction I references
832 // island CPE, and instruction I+1 references CPE', it will
833 // not work well to put CPE as far forward as possible, since then
834 // CPE' cannot immediately follow it (that location is 2 bytes
835 // farther away from I+1 than CPE was from I) and we'd need to create
836 // a new island.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000837 // The 4 in the following is for the unconditional branch we'll be
838 // inserting (allows for long branch on Thumb). The 2 or 0 is for
839 // alignment of the island.
840 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4 + (isThumb ? 2 : 0);
841 // This could point off the end of the block if we've already got
842 // constant pool entries following this block; only the last one is
843 // in the water list. Back past any possible branches.
844 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
845 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] - 6;
846 unsigned EndInsertOffset = BaseInsertOffset +
847 CPEMI->getOperand(2).getImm();
848 MachineBasicBlock::iterator MI = UserMI; ++MI;
849 unsigned CPUIndex = CPUserIndex+1;
850 for (unsigned Offset = UserOffset+ARM::GetInstSize(UserMI);
851 Offset < BaseInsertOffset;
852 Offset += ARM::GetInstSize(MI),
853 MI = next(MI)) {
854 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
855 if (!OffsetIsInRange(Offset, EndInsertOffset,
856 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
857 BaseInsertOffset -= (isThumb ? 2 : 4);
858 EndInsertOffset -= (isThumb ? 2 : 4);
859 }
860 // This is overly conservative, as we don't account for CPEMIs
861 // being reused within the block, but it doesn't matter much.
862 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
863 CPUIndex++;
864 }
865 }
866 DOUT << "Split in middle of big block\n";
867 NewMBB = SplitBlockBeforeInstr(prior(MI));
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000868 }
869 }
870
871 // Okay, we know we can put an island before NewMBB now, do it!
872 MachineBasicBlock *NewIsland = new MachineBasicBlock();
873 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
874
875 // Update internal data structures to account for the newly inserted MBB.
876 UpdateForInsertedWaterBlock(NewIsland);
877
878 // Decrement the old entry, and remove it if refcount becomes 0.
879 DecrementOldEntry(CPI, CPEMI, Size);
880
881 // Now that we have an island to add the CPE to, clone the original CPE and
882 // add it to the island.
Evan Chenga8e29892007-01-19 07:51:42 +0000883 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
884 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000885 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +0000886 NumCPEs++;
887
Evan Chengb43216e2007-02-01 10:16:15 +0000888 // Compensate for .align 2 in thumb mode.
Dale Johannesenf1b214d2007-02-28 18:41:23 +0000889 if (isThumb && PadNewWater) Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +0000890 // Increase the size of the island block to account for the new entry.
891 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000892 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
893 AdjustBBOffsetsAfter(NewIsland, Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000894
895 // Finally, change the CPI in the instruction operand to be ID.
896 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
897 if (UserMI->getOperand(i).isConstantPoolIndex()) {
898 UserMI->getOperand(i).setConstantPoolIndex(ID);
899 break;
900 }
901
Evan Chengc99ef082007-02-09 20:54:44 +0000902 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Evan Chenga8e29892007-01-19 07:51:42 +0000903
904 return true;
905}
906
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000907/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +0000908/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +0000909bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
910 unsigned MaxDisp) {
911 unsigned PCAdj = AFI->isThumbFunction() ? 4 : 8;
912 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000913 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +0000914
Evan Chengc99ef082007-02-09 20:54:44 +0000915 DOUT << "Branch of destination BB#" << DestBB->getNumber()
916 << " from BB#" << MI->getParent()->getNumber()
917 << " max delta=" << MaxDisp
918 << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +0000919
Dale Johannesen99c49a42007-02-25 00:47:03 +0000920 return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
Evan Cheng43aeab62007-01-26 20:38:26 +0000921}
922
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000923/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
924/// away to fit in its displacement field.
925bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000926 MachineInstr *MI = Br.MI;
927 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
928
Evan Chengc0dbec72007-01-31 19:57:44 +0000929 // Check to see if the DestBB is already in-range.
930 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +0000931 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000932
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000933 if (!Br.isCond)
934 return FixUpUnconditionalBr(Fn, Br);
935 return FixUpConditionalBr(Fn, Br);
936}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000937
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000938/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
939/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000940/// spilled in the epilogue, then we can use BL to implement a far jump.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000941/// Otherwise, add an intermediate branch instruction to to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000942bool
943ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
944 MachineInstr *MI = Br.MI;
945 MachineBasicBlock *MBB = MI->getParent();
946 assert(AFI->isThumbFunction() && "Expected a Thumb function!");
947
948 // Use BL to implement far jump.
949 Br.MaxDisp = (1 << 21) * 2;
950 MI->setInstrDescriptor(TII->get(ARM::tBfar));
951 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000952 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000953 HasFarJump = true;
954 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +0000955
Evan Chengc99ef082007-02-09 20:54:44 +0000956 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +0000957
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000958 return true;
959}
960
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000961/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000962/// far away to fit in its displacement field. It is converted to an inverse
963/// conditional branch + an unconditional branch to the destination.
964bool
965ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
966 MachineInstr *MI = Br.MI;
967 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
968
969 // Add a unconditional branch to the destination and invert the branch
970 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000971 // blt L1
972 // =>
973 // bge L2
974 // b L1
975 // L2:
976 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
977 CC = ARMCC::getOppositeCondition(CC);
978
979 // If the branch is at the end of its MBB and that has a fall-through block,
980 // direct the updated conditional branch to the fall-through block. Otherwise,
981 // split the MBB before the next instruction.
982 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +0000983 MachineInstr *BMI = &MBB->back();
984 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +0000985
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000986 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +0000987 if (BMI != MI) {
Evan Cheng43aeab62007-01-26 20:38:26 +0000988 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
Evan Chengbd5d3db2007-02-03 02:08:34 +0000989 BMI->getOpcode() == Br.UncondBr) {
Evan Cheng43aeab62007-01-26 20:38:26 +0000990 // Last MI in the BB is a unconditional branch. Can we simply invert the
991 // condition and swap destinations:
992 // beq L1
993 // b L2
994 // =>
995 // bne L2
996 // b L1
Evan Chengbd5d3db2007-02-03 02:08:34 +0000997 MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
Evan Chengc0dbec72007-01-31 19:57:44 +0000998 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +0000999 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Evan Chengbd5d3db2007-02-03 02:08:34 +00001000 BMI->getOperand(0).setMachineBasicBlock(DestBB);
Evan Cheng43aeab62007-01-26 20:38:26 +00001001 MI->getOperand(0).setMachineBasicBlock(NewDest);
1002 MI->getOperand(1).setImm(CC);
1003 return true;
1004 }
1005 }
1006 }
1007
1008 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001009 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +00001010 // No need for the branch to the next block. We're adding a unconditional
1011 // branch to the destination.
1012 MBB->back().eraseFromParent();
1013 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001014 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Evan Chengbd5d3db2007-02-03 02:08:34 +00001015
Evan Chengc99ef082007-02-09 20:54:44 +00001016 DOUT << " Insert B to BB#" << DestBB->getNumber()
1017 << " also invert condition and change dest. to BB#"
1018 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001019
1020 // Insert a unconditional branch and replace the conditional branch.
1021 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +00001022 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001023 Br.MI = &MBB->back();
1024 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Evan Chenga9b8b8d2007-01-31 18:29:27 +00001025 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +00001026 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001027 MI->eraseFromParent();
1028
1029 // Increase the size of MBB to account for the new unconditional branch.
Dale Johannesen99c49a42007-02-25 00:47:03 +00001030 int delta = ARM::GetInstSize(&MBB->back());
1031 BBSizes[MBB->getNumber()] += delta;
1032 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +00001033 return true;
1034}
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001035
Evan Chengd1b2c1e2007-01-30 01:18:38 +00001036/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1037/// LR / restores LR to pc.
1038bool ARMConstantIslands::UndoLRSpillRestore() {
1039 bool MadeChange = false;
1040 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1041 MachineInstr *MI = PushPopMIs[i];
1042 if (MI->getNumOperands() == 1) {
1043 if (MI->getOpcode() == ARM::tPOP_RET &&
1044 MI->getOperand(0).getReg() == ARM::PC)
1045 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
1046 MI->eraseFromParent();
1047 MadeChange = true;
1048 }
1049 }
1050 return MadeChange;
1051}