blob: 71633cd09da31b35681d041868d1e3b7883f3db1 [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.
Dale Johannesen99c49a42007-02-25 00:47:03 +00007// Substantial modifications by Evan Cheng and Dale Johannesen.
Evan Chenga8e29892007-01-19 07:51:42 +00008//
9//===----------------------------------------------------------------------===//
10//
11// This file contains a pass that splits the constant pool up into 'islands'
12// which are scattered through-out the function. This is required due to the
13// limited pc-relative displacements that ARM has.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "arm-cp-islands"
18#include "ARM.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000019#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000020#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Chenga8e29892007-01-19 07:51:42 +000024#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Debug.h"
Evan Chengc99ef082007-02-09 20:54:44 +000028#include "llvm/ADT/SmallVector.h"
Evan Chenga8e29892007-01-19 07:51:42 +000029#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Statistic.h"
Evan Chenga8e29892007-01-19 07:51:42 +000031using namespace llvm;
32
Evan Chengc99ef082007-02-09 20:54:44 +000033STATISTIC(NumCPEs, "Number of constpool entries");
Evan Chengd1b2c1e2007-01-30 01:18:38 +000034STATISTIC(NumSplit, "Number of uncond branches inserted");
35STATISTIC(NumCBrFixed, "Number of cond branches fixed");
36STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Evan Chenga8e29892007-01-19 07:51:42 +000037
38namespace {
Dale Johannesen88e37ae2007-02-23 05:02:36 +000039 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
Evan Chenga8e29892007-01-19 07:51:42 +000040 /// requires constant pool entries to be scattered among the instructions
41 /// inside a function. To do this, it completely ignores the normal LLVM
Dale Johannesen88e37ae2007-02-23 05:02:36 +000042 /// constant pool; instead, it places constants wherever it feels like with
Evan Chenga8e29892007-01-19 07:51:42 +000043 /// special instructions.
44 ///
45 /// The terminology used in this pass includes:
46 /// Islands - Clumps of constants placed in the function.
47 /// Water - Potential places where an island could be formed.
48 /// CPE - A constant pool entry that has been placed somewhere, which
49 /// tracks a list of users.
50 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
51 /// NextUID - Assign unique ID's to CPE's.
52 unsigned NextUID;
Dale Johannesen99c49a42007-02-25 00:47:03 +000053
Evan Chenga8e29892007-01-19 07:51:42 +000054 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
55 /// by MBB Number.
Evan Chenge03cff62007-02-09 23:59:14 +000056 std::vector<unsigned> BBSizes;
Evan Chenga8e29892007-01-19 07:51:42 +000057
Dale Johannesen99c49a42007-02-25 00:47:03 +000058 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
59 std::vector<unsigned> BBOffsets;
60
Evan Chenga8e29892007-01-19 07:51:42 +000061 /// WaterList - A sorted list of basic blocks where islands could be placed
62 /// (i.e. blocks that don't fall through to the following block, due
63 /// to a return, unreachable, or unconditional branch).
Evan Chenge03cff62007-02-09 23:59:14 +000064 std::vector<MachineBasicBlock*> WaterList;
Evan Chengc99ef082007-02-09 20:54:44 +000065
Evan Chenga8e29892007-01-19 07:51:42 +000066 /// CPUser - One user of a constant pool, keeping the machine instruction
67 /// pointer, the constant pool being referenced, and the max displacement
68 /// allowed from the instruction to the CP.
69 struct CPUser {
70 MachineInstr *MI;
71 MachineInstr *CPEMI;
72 unsigned MaxDisp;
73 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
74 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
75 };
76
77 /// CPUsers - Keep track of all of the machine instructions that use various
78 /// constant pools and their max displacement.
Evan Chenge03cff62007-02-09 23:59:14 +000079 std::vector<CPUser> CPUsers;
Evan Chengc99ef082007-02-09 20:54:44 +000080
81 /// CPEntry - One per constant pool entry, keeping the machine instruction
82 /// pointer, the constpool index, and the number of CPUser's which
83 /// reference this entry.
84 struct CPEntry {
85 MachineInstr *CPEMI;
86 unsigned CPI;
87 unsigned RefCount;
88 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
89 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
90 };
91
92 /// CPEntries - Keep track of all of the constant pool entry machine
Dale Johannesen88e37ae2007-02-23 05:02:36 +000093 /// instructions. For each original constpool index (i.e. those that
94 /// existed upon entry to this pass), it keeps a vector of entries.
95 /// Original elements are cloned as we go along; the clones are
96 /// put in the vector of the original element, but have distinct CPIs.
Evan Chengc99ef082007-02-09 20:54:44 +000097 std::vector<std::vector<CPEntry> > CPEntries;
Evan Chenga8e29892007-01-19 07:51:42 +000098
Evan Chengaf5cbcb2007-01-25 03:12:46 +000099 /// ImmBranch - One per immediate branch, keeping the machine instruction
100 /// pointer, conditional or unconditional, the max displacement,
101 /// and (if isCond is true) the corresponding unconditional branch
102 /// opcode.
103 struct ImmBranch {
104 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +0000105 unsigned MaxDisp : 31;
106 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000107 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +0000108 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
109 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000110 };
111
Evan Chengc2854142007-01-25 23:18:59 +0000112 /// Branches - 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;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000125 const ARMFunctionInfo *AFI;
Evan Chenga8e29892007-01-19 07:51:42 +0000126 public:
127 virtual bool runOnMachineFunction(MachineFunction &Fn);
128
129 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000130 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000131 }
132
133 private:
134 void DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000135 std::vector<MachineInstr*> &CPEMIs);
Evan Chengc99ef082007-02-09 20:54:44 +0000136 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000137 void InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000138 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000139 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000140 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000141 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000142 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI, unsigned Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000143 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000144 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000145 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
146 MachineInstr *CPEMI, unsigned Disp,
147 bool DoDump);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000148 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000149 unsigned Disp);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000150 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
151 unsigned Disp, bool NegativeOK);
Evan Chengc0dbec72007-01-31 19:57:44 +0000152 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000153 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
154 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
155 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
156 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000157
Evan Chenga8e29892007-01-19 07:51:42 +0000158 unsigned GetOffsetOf(MachineInstr *MI) const;
159 };
160}
161
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000162/// createARMConstantIslandPass - returns an instance of the constpool
163/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000164FunctionPass *llvm::createARMConstantIslandPass() {
165 return new ARMConstantIslands();
166}
167
168bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000169 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000170
171 TII = Fn.getTarget().getInstrInfo();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000172 AFI = Fn.getInfo<ARMFunctionInfo>();
173
174 HasFarJump = false;
175
Evan Chenga8e29892007-01-19 07:51:42 +0000176 // Renumber all of the machine basic blocks in the function, guaranteeing that
177 // the numbers agree with the position of the block in the function.
178 Fn.RenumberBlocks();
179
180 // Perform the initial placement of the constant pool entries. To start with,
181 // we put them all at the end of the function.
Evan Chenge03cff62007-02-09 23:59:14 +0000182 std::vector<MachineInstr*> CPEMIs;
Evan Cheng7755fac2007-01-26 01:04:44 +0000183 if (!MCP.isEmpty())
184 DoInitialPlacement(Fn, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000185
186 /// The next UID to take is the first unused one.
187 NextUID = CPEMIs.size();
188
189 // Do the initial scan of the function, building up information about the
190 // sizes of each block, the location of all the water, and finding all of the
191 // constant pool users.
192 InitialFunctionScan(Fn, CPEMIs);
193 CPEMIs.clear();
194
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000195 // Iteratively place constant pool entries and fix up branches until there
196 // is no change.
197 bool MadeChange = false;
198 while (true) {
199 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000200 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000201 Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000202 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000203 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
204 if (!Change)
205 break;
206 MadeChange = true;
207 }
Evan Chenga8e29892007-01-19 07:51:42 +0000208
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000209 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
210 // Undo the spill / restore of LR if possible.
211 if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
212 MadeChange |= UndoLRSpillRestore();
213
Evan Chenga8e29892007-01-19 07:51:42 +0000214 BBSizes.clear();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000215 BBOffsets.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000216 WaterList.clear();
217 CPUsers.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000218 CPEntries.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000219 ImmBranches.clear();
Evan Chengc99ef082007-02-09 20:54:44 +0000220 PushPopMIs.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000221
222 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000223}
224
225/// DoInitialPlacement - Perform the initial placement of the constant pool
226/// entries. To start with, we put them all at the end of the function.
227void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000228 std::vector<MachineInstr*> &CPEMIs){
Evan Chenga8e29892007-01-19 07:51:42 +0000229 // Create the basic block to hold the CPE's.
230 MachineBasicBlock *BB = new MachineBasicBlock();
231 Fn.getBasicBlockList().push_back(BB);
232
233 // Add all of the constants from the constant pool to the end block, use an
234 // identity mapping of CPI's to CPE's.
235 const std::vector<MachineConstantPoolEntry> &CPs =
236 Fn.getConstantPool()->getConstants();
237
238 const TargetData &TD = *Fn.getTarget().getTargetData();
239 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
240 unsigned Size = TD.getTypeSize(CPs[i].getType());
241 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
242 // we would have to pad them out or something so that instructions stay
243 // aligned.
244 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
245 MachineInstr *CPEMI =
246 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
247 .addImm(i).addConstantPoolIndex(i).addImm(Size);
248 CPEMIs.push_back(CPEMI);
Evan Chengc99ef082007-02-09 20:54:44 +0000249
250 // Add a new CPEntry, but no corresponding CPUser yet.
251 std::vector<CPEntry> CPEs;
252 CPEs.push_back(CPEntry(CPEMI, i));
253 CPEntries.push_back(CPEs);
254 NumCPEs++;
255 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
Evan Chenga8e29892007-01-19 07:51:42 +0000256 }
257}
258
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000259/// BBHasFallthrough - Return true if the specified basic block can fallthrough
Evan Chenga8e29892007-01-19 07:51:42 +0000260/// into the block immediately after it.
261static bool BBHasFallthrough(MachineBasicBlock *MBB) {
262 // Get the next machine basic block in the function.
263 MachineFunction::iterator MBBI = MBB;
264 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
265 return false;
266
267 MachineBasicBlock *NextBB = next(MBBI);
268 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
269 E = MBB->succ_end(); I != E; ++I)
270 if (*I == NextBB)
271 return true;
272
273 return false;
274}
275
Evan Chengc99ef082007-02-09 20:54:44 +0000276/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
277/// look up the corresponding CPEntry.
278ARMConstantIslands::CPEntry
279*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
280 const MachineInstr *CPEMI) {
281 std::vector<CPEntry> &CPEs = CPEntries[CPI];
282 // Number of entries per constpool index should be small, just do a
283 // linear search.
284 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
285 if (CPEs[i].CPEMI == CPEMI)
286 return &CPEs[i];
287 }
288 return NULL;
289}
290
Evan Chenga8e29892007-01-19 07:51:42 +0000291/// InitialFunctionScan - Do the initial scan of the function, building up
292/// information about the sizes of each block, the location of all the water,
293/// and finding all of the constant pool users.
294void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
Evan Chenge03cff62007-02-09 23:59:14 +0000295 const std::vector<MachineInstr*> &CPEMIs) {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000296 unsigned Offset = 0;
Evan Chenga8e29892007-01-19 07:51:42 +0000297 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
298 MBBI != E; ++MBBI) {
299 MachineBasicBlock &MBB = *MBBI;
300
301 // If this block doesn't fall through into the next MBB, then this is
302 // 'water' that a constant pool island could be placed.
303 if (!BBHasFallthrough(&MBB))
304 WaterList.push_back(&MBB);
305
306 unsigned MBBSize = 0;
307 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
308 I != E; ++I) {
309 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000310 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000311
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000312 int Opc = I->getOpcode();
313 if (TII->isBranch(Opc)) {
314 bool isCond = false;
315 unsigned Bits = 0;
316 unsigned Scale = 1;
317 int UOpc = Opc;
318 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000319 default:
320 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000321 case ARM::Bcc:
322 isCond = true;
323 UOpc = ARM::B;
324 // Fallthrough
325 case ARM::B:
326 Bits = 24;
327 Scale = 4;
328 break;
329 case ARM::tBcc:
330 isCond = true;
331 UOpc = ARM::tB;
332 Bits = 8;
333 Scale = 2;
334 break;
335 case ARM::tB:
336 Bits = 11;
337 Scale = 2;
338 break;
339 }
Evan Chengb43216e2007-02-01 10:16:15 +0000340
341 // Record this immediate branch.
Evan Chengbd5d3db2007-02-03 02:08:34 +0000342 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
Evan Chengb43216e2007-02-01 10:16:15 +0000343 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000344 }
345
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000346 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
347 PushPopMIs.push_back(I);
348
Evan Chenga8e29892007-01-19 07:51:42 +0000349 // Scan the instructions for constant pool operands.
350 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
351 if (I->getOperand(op).isConstantPoolIndex()) {
352 // We found one. The addressing mode tells us the max displacement
353 // from the PC that this instruction permits.
Evan Chenga8e29892007-01-19 07:51:42 +0000354
355 // Basic size info comes from the TSFlags field.
Evan Chengb43216e2007-02-01 10:16:15 +0000356 unsigned Bits = 0;
357 unsigned Scale = 1;
Evan Chenga8e29892007-01-19 07:51:42 +0000358 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
359 switch (TSFlags & ARMII::AddrModeMask) {
360 default:
361 // Constant pool entries can reach anything.
362 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
363 continue;
364 assert(0 && "Unknown addressing mode for CP reference!");
365 case ARMII::AddrMode1: // AM1: 8 bits << 2
Evan Chengb43216e2007-02-01 10:16:15 +0000366 Bits = 8;
367 Scale = 4; // Taking the address of a CP entry.
Evan Chenga8e29892007-01-19 07:51:42 +0000368 break;
369 case ARMII::AddrMode2:
Evan Cheng556f33c2007-02-01 20:44:52 +0000370 Bits = 12; // +-offset_12
Evan Chenga8e29892007-01-19 07:51:42 +0000371 break;
372 case ARMII::AddrMode3:
Evan Cheng556f33c2007-02-01 20:44:52 +0000373 Bits = 8; // +-offset_8
Evan Chenga8e29892007-01-19 07:51:42 +0000374 break;
375 // addrmode4 has no immediate offset.
376 case ARMII::AddrMode5:
Evan Chengb43216e2007-02-01 10:16:15 +0000377 Bits = 8;
378 Scale = 4; // +-(offset_8*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000379 break;
380 case ARMII::AddrModeT1:
Evan Chengb43216e2007-02-01 10:16:15 +0000381 Bits = 5; // +offset_5
Evan Chenga8e29892007-01-19 07:51:42 +0000382 break;
383 case ARMII::AddrModeT2:
Evan Chengb43216e2007-02-01 10:16:15 +0000384 Bits = 5;
385 Scale = 2; // +(offset_5*2)
Evan Chenga8e29892007-01-19 07:51:42 +0000386 break;
387 case ARMII::AddrModeT4:
Evan Chengb43216e2007-02-01 10:16:15 +0000388 Bits = 5;
389 Scale = 4; // +(offset_5*4)
Evan Chenga8e29892007-01-19 07:51:42 +0000390 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000391 case ARMII::AddrModeTs:
Evan Chengb43216e2007-02-01 10:16:15 +0000392 Bits = 8;
393 Scale = 4; // +(offset_8*4)
Evan Cheng012f2d92007-01-24 08:53:17 +0000394 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000395 }
Evan Chengb43216e2007-02-01 10:16:15 +0000396
Evan Chenga8e29892007-01-19 07:51:42 +0000397 // Remember that this is a user of a CP entry.
Evan Chengc99ef082007-02-09 20:54:44 +0000398 unsigned CPI = I->getOperand(op).getConstantPoolIndex();
399 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Cheng556f33c2007-02-01 20:44:52 +0000400 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chenga8e29892007-01-19 07:51:42 +0000401 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
Evan Chengc99ef082007-02-09 20:54:44 +0000402
403 // Increment corresponding CPEntry reference count.
404 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
405 assert(CPE && "Cannot find a corresponding CPEntry!");
406 CPE->RefCount++;
Evan Chenga8e29892007-01-19 07:51:42 +0000407
408 // Instructions can only use one CP entry, don't bother scanning the
409 // rest of the operands.
410 break;
411 }
412 }
Evan Cheng2021abe2007-02-01 01:09:47 +0000413
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000414 // In thumb mode, if this block is a constpool island, pessimistically
415 // assume it needs to be padded by two byte so it's aligned on 4 byte
416 // boundary.
Evan Cheng2021abe2007-02-01 01:09:47 +0000417 if (AFI->isThumbFunction() &&
Evan Cheng05cc4242007-02-02 19:09:19 +0000418 !MBB.empty() &&
Evan Cheng2021abe2007-02-01 01:09:47 +0000419 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
420 MBBSize += 2;
421
Evan Chenga8e29892007-01-19 07:51:42 +0000422 BBSizes.push_back(MBBSize);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000423 BBOffsets.push_back(Offset);
424 Offset += MBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000425 }
426}
427
Evan Chenga8e29892007-01-19 07:51:42 +0000428/// GetOffsetOf - Return the current offset of the specified machine instruction
429/// from the start of the function. This offset changes as stuff is moved
430/// around inside the function.
431unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
432 MachineBasicBlock *MBB = MI->getParent();
433
434 // The offset is composed of two things: the sum of the sizes of all MBB's
435 // before this instruction's block, and the offset from the start of the block
436 // it is in.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000437 unsigned Offset = BBOffsets[MBB->getNumber()];
Evan Chenga8e29892007-01-19 07:51:42 +0000438
439 // Sum instructions before MI in MBB.
440 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
441 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
442 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000443 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000444 }
445}
446
447/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
448/// ID.
449static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
450 const MachineBasicBlock *RHS) {
451 return LHS->getNumber() < RHS->getNumber();
452}
453
454/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
455/// machine function, it upsets all of the block numbers. Renumber the blocks
456/// and update the arrays that parallel this numbering.
457void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
458 // Renumber the MBB's to keep them consequtive.
459 NewBB->getParent()->RenumberBlocks(NewBB);
460
461 // Insert a size into BBSizes to align it properly with the (newly
462 // renumbered) block numbers.
463 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000464
465 // Likewise for BBOffsets.
466 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Evan Chenga8e29892007-01-19 07:51:42 +0000467
468 // Next, update WaterList. Specifically, we need to add NewMBB as having
469 // available water after it.
Evan Chenge03cff62007-02-09 23:59:14 +0000470 std::vector<MachineBasicBlock*>::iterator IP =
Evan Chenga8e29892007-01-19 07:51:42 +0000471 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
472 CompareMBBNumbers);
473 WaterList.insert(IP, NewBB);
474}
475
476
477/// Split the basic block containing MI into two blocks, which are joined by
478/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000479/// account for this change and returns the newly created block.
480MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000481 MachineBasicBlock *OrigBB = MI->getParent();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000482 bool isThumb = AFI->isThumbFunction();
Evan Chenga8e29892007-01-19 07:51:42 +0000483
484 // Create a new MBB for the code after the OrigBB.
485 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
486 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
487 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
488
489 // Splice the instructions starting with MI over to NewBB.
490 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
491
492 // Add an unconditional branch from OrigBB to NewBB.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000493 // Note the new unconditional branch is not being recorded.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000494 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000495 NumSplit++;
496
497 // Update the CFG. All succs of OrigBB are now succs of NewBB.
498 while (!OrigBB->succ_empty()) {
499 MachineBasicBlock *Succ = *OrigBB->succ_begin();
500 OrigBB->removeSuccessor(Succ);
501 NewBB->addSuccessor(Succ);
502
503 // This pass should be run after register allocation, so there should be no
504 // PHI nodes to update.
505 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
506 && "PHI nodes should be eliminated by now!");
507 }
508
509 // OrigBB branches to NewBB.
510 OrigBB->addSuccessor(NewBB);
511
512 // Update internal data structures to account for the newly inserted MBB.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000513 // This is almost the same as UpdateForInsertedWaterBlock, except that
514 // the Water goes after OrigBB, not NewBB.
515 NewBB->getParent()->RenumberBlocks(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000516
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000517 // Insert a size into BBSizes to align it properly with the (newly
518 // renumbered) block numbers.
519 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
520
Dale Johannesen99c49a42007-02-25 00:47:03 +0000521 // Likewise for BBOffsets.
522 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
523
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000524 // Next, update WaterList. Specifically, we need to add OrigMBB as having
525 // available water after it (but not if it's already there, which happens
526 // when splitting before a conditional branch that is followed by an
527 // unconditional branch - in that case we want to insert NewBB).
528 std::vector<MachineBasicBlock*>::iterator IP =
529 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
530 CompareMBBNumbers);
531 MachineBasicBlock* WaterBB = *IP;
532 if (WaterBB == OrigBB)
533 WaterList.insert(next(IP), NewBB);
534 else
535 WaterList.insert(IP, OrigBB);
536
Evan Chenga8e29892007-01-19 07:51:42 +0000537 // Figure out how large the first NewMBB is.
538 unsigned NewBBSize = 0;
539 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
540 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000541 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000542
Dale Johannesen99c49a42007-02-25 00:47:03 +0000543 unsigned OrigBBI = OrigBB->getNumber();
544 unsigned NewBBI = NewBB->getNumber();
Evan Chenga8e29892007-01-19 07:51:42 +0000545 // Set the size of NewBB in BBSizes.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000546 BBSizes[NewBBI] = NewBBSize;
Evan Chenga8e29892007-01-19 07:51:42 +0000547
548 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000549 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000550 unsigned delta = isThumb ? 2 : 4;
551 BBSizes[OrigBBI] -= NewBBSize - delta;
552
553 // ...and adjust BBOffsets for NewBB accordingly.
554 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
555
556 // All BBOffsets following these blocks must be modified.
557 AdjustBBOffsetsAfter(NewBB, delta);
Evan Cheng0c615842007-01-31 02:22:22 +0000558
559 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000560}
561
Dale Johannesen99c49a42007-02-25 00:47:03 +0000562//// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
563/// TrialOffset.
564bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
565 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
566 if (UserOffset <= TrialOffset) {
567 // User before the Trial.
568 if (TrialOffset-UserOffset <= MaxDisp)
569 return true;
570 } else if (NegativeOK) {
571 if (UserOffset-TrialOffset <= MaxDisp)
572 return true;
573 }
574 return false;
575}
576
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000577/// WaterIsInRange - Returns true if a CPE placed after the specified
578/// Water (a basic block) will be in range for the specific MI.
579
580bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Dale Johannesen99c49a42007-02-25 00:47:03 +0000581 MachineBasicBlock* Water, unsigned MaxDisp)
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000582{
Dale Johannesen99c49a42007-02-25 00:47:03 +0000583 bool isThumb = AFI->isThumbFunction();
584 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000585 BBSizes[Water->getNumber()];
586 // If the Water is a constpool island, it has already been aligned.
587 // If not, align it.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000588 if (isThumb &&
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000589 (Water->empty() ||
590 Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
591 CPEOffset += 2;
592
Dale Johannesen99c49a42007-02-25 00:47:03 +0000593 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000594}
595
596/// CPEIsInRange - Returns true if the distance between specific MI and
Evan Chengc0dbec72007-01-31 19:57:44 +0000597/// specific ConstPool entry instruction can fit in MI's displacement field.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000598bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
599 MachineInstr *CPEMI,
600 unsigned MaxDisp, bool DoDump) {
601 // In thumb mode, pessimistically assumes the .align 2 before the first CPE
Evan Cheng2021abe2007-02-01 01:09:47 +0000602 // in the island adds two byte padding.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000603 bool isThumb = AFI->isThumbFunction();
604 unsigned AlignAdj = isThumb ? 2 : 0;
Evan Cheng2021abe2007-02-01 01:09:47 +0000605 unsigned CPEOffset = GetOffsetOf(CPEMI) + AlignAdj;
606
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000607 if (DoDump) {
608 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
609 << " max delta=" << MaxDisp
610 << " insn address=" << UserOffset
611 << " CPE address=" << CPEOffset
612 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
613 }
Evan Chengc0dbec72007-01-31 19:57:44 +0000614
Dale Johannesen99c49a42007-02-25 00:47:03 +0000615 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
Evan Chengc0dbec72007-01-31 19:57:44 +0000616}
617
Evan Chengc99ef082007-02-09 20:54:44 +0000618/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
619/// unconditionally branches to its only successor.
620static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
621 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
622 return false;
623
624 MachineBasicBlock *Succ = *MBB->succ_begin();
625 MachineBasicBlock *Pred = *MBB->pred_begin();
626 MachineInstr *PredMI = &Pred->back();
627 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
628 return PredMI->getOperand(0).getMBB() == Succ;
629 return false;
630}
631
Dale Johannesen99c49a42007-02-25 00:47:03 +0000632void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
633{
634 MachineFunction::iterator MBBI = BB->getParent()->end();
635 for(int i=BB->getNumber()+1; i<=prior(MBBI)->getNumber(); i++)
636 BBOffsets[i] += delta;
637}
638
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000639/// DecrementOldEntry - find the constant pool entry with index CPI
640/// and instruction CPEMI, and decrement its refcount. If the refcount
641/// becomes 0 remove the entry and instruction. Returns true if we removed
642/// the entry, false if we didn't.
Evan Chenga8e29892007-01-19 07:51:42 +0000643
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000644bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI,
645 unsigned Size) {
Evan Chengc99ef082007-02-09 20:54:44 +0000646 // Find the old entry. Eliminate it if it is no longer used.
647 CPEntry *OldCPE = findConstPoolEntry(CPI, CPEMI);
648 assert(OldCPE && "Unexpected!");
649 if (--OldCPE->RefCount == 0) {
650 MachineBasicBlock *OldCPEBB = OldCPE->CPEMI->getParent();
651 if (OldCPEBB->empty()) {
652 // In thumb mode, the size of island is padded by two to compensate for
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000653 // the alignment requirement. Thus it will now be 2 when the block is
654 // empty, so fix this.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000655 // All succeeding offsets have the current size value added in, fix this.
656 if (BBSizes[OldCPEBB->getNumber()] != 0) {
657 AdjustBBOffsetsAfter(OldCPEBB, -BBSizes[OldCPEBB->getNumber()]);
658 BBSizes[OldCPEBB->getNumber()] = 0;
659 }
Evan Chengc99ef082007-02-09 20:54:44 +0000660 // An island has only one predecessor BB and one successor BB. Check if
661 // this BB's predecessor jumps directly to this BB's successor. This
662 // shouldn't happen currently.
663 assert(!BBIsJumpedOver(OldCPEBB) && "How did this happen?");
664 // FIXME: remove the empty blocks after all the work is done?
Dale Johannesen99c49a42007-02-25 00:47:03 +0000665 } else {
Evan Chengc99ef082007-02-09 20:54:44 +0000666 BBSizes[OldCPEBB->getNumber()] -= Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000667 // All succeeding offsets have the current size value added in, fix this.
668 AdjustBBOffsetsAfter(OldCPEBB, -Size);
669 }
Evan Chengc99ef082007-02-09 20:54:44 +0000670 OldCPE->CPEMI->eraseFromParent();
671 OldCPE->CPEMI = NULL;
672 NumCPEs--;
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000673 return true;
674 }
675 return false;
676}
677
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000678/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
679/// if not, see if an in-range clone of the CPE is in range, and if so,
680/// change the data structures so the user references the clone. Returns:
681/// 0 = no existing entry found
682/// 1 = entry found, and there were no code insertions or deletions
683/// 2 = entry found, and there were code insertions or deletions
684int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
685{
686 MachineInstr *UserMI = U.MI;
687 MachineInstr *CPEMI = U.CPEMI;
688
689 // Check to see if the CPE is already in-range.
690 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
691 DOUT << "In range\n";
692 return 1;
Evan Chengc99ef082007-02-09 20:54:44 +0000693 }
694
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000695 // No. Look for previously created clones of the CPE that are in range.
696 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
697 std::vector<CPEntry> &CPEs = CPEntries[CPI];
698 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
699 // We already tried this one
700 if (CPEs[i].CPEMI == CPEMI)
701 continue;
702 // Removing CPEs can leave empty entries, skip
703 if (CPEs[i].CPEMI == NULL)
704 continue;
705 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
706 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
707 // Point the CPUser node to the replacement
708 U.CPEMI = CPEs[i].CPEMI;
709 // Change the CPI in the instruction operand to refer to the clone.
710 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
711 if (UserMI->getOperand(j).isConstantPoolIndex()) {
712 UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
713 break;
714 }
715 // Adjust the refcount of the clone...
716 CPEs[i].RefCount++;
717 // ...and the original. If we didn't remove the old entry, none of the
718 // addresses changed, so we don't need another pass.
719 unsigned Size = CPEMI->getOperand(2).getImm();
720 return DecrementOldEntry(CPI, CPEMI, Size) ? 2 : 1;
721 }
722 }
723 return 0;
724}
725
726/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
727/// is out-of-range. If so, pick it up the constant pool value and move it some
728/// place in-range. Return true if we changed any addresses (thus must run
729/// another pass of branch lengthening), false otherwise.
730bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
731 MachineInstr *UserMI = U.MI;
732 MachineInstr *CPEMI = U.CPEMI;
733 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
734 unsigned Size = CPEMI->getOperand(2).getImm();
735 bool isThumb = AFI->isThumbFunction();
736 MachineBasicBlock *NewMBB;
737 // Compute this only once, it's expensive
738 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
739
740 // See if the current entry is within range, or there is a clone of it
741 // in range.
742 int result = LookForExistingCPEntry(U, UserOffset);
743 if (result==1) return false;
744 else if (result==2) return true;
745
746 // No existing clone of this CPE is within range.
747 // We will be generating a new clone. Get a UID for it.
748 unsigned ID = NextUID++;
749
750 // Look for water where we can place this CPE. We look for the farthest one
751 // away that will work. Forward references only for now (although later
752 // we might find some that are backwards).
753 bool WaterFound = false;
754 if (!WaterList.empty()) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000755 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
756 B = WaterList.begin();; --IP) {
757 MachineBasicBlock* WaterBB = *IP;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000758 if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000759 WaterFound = true;
760 DOUT << "found water in range\n";
761 // CPE goes before following block (NewMBB).
762 NewMBB = next(MachineFunction::iterator(WaterBB));
763 // Remove the original WaterList entry; we want subsequent
764 // insertions in this vicinity to go after the one we're
765 // about to insert. This considerably reduces the number
766 // of times we have to move the same CPE more than once.
767 WaterList.erase(IP);
768 break;
769 }
770 if (IP == B)
771 break;
772 }
773 }
774
775 if (!WaterFound) {
776 // No water found.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000777
778 DOUT << "No water found\n";
779 MachineBasicBlock *UserMBB = UserMI->getParent();
Dale Johannesen99c49a42007-02-25 00:47:03 +0000780 unsigned TrialOffset = BBOffsets[UserMBB->getNumber()] +
781 BBSizes[UserMBB->getNumber()] +
782 isThumb ? 2 : 4; /* for branch to be added */
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000783
Dale Johannesen99c49a42007-02-25 00:47:03 +0000784 // If the use is at the end of the block, or the end of the block
785 // is within range, make new water there. (If the block ends in
786 // an unconditional branch already, it is water, and is known to
787 // be out of range; so it's OK to assume above we'll be adding a Br.)
788 if (&UserMBB->back() == UserMI ||
789 OffsetIsInRange(UserOffset, TrialOffset, U.MaxDisp, !isThumb)) {
790 if (&UserMBB->back() == UserMI)
791 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000792 NewMBB = next(MachineFunction::iterator(UserMBB));
793 // Add an unconditional branch from UserMBB to fallthrough block.
794 // Note the new unconditional branch is not being recorded.
795 BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
Dale Johannesen99c49a42007-02-25 00:47:03 +0000796 int delta = isThumb ? 2 : 4;
797 BBSizes[UserMBB->getNumber()] += delta;
798 AdjustBBOffsetsAfter(UserMBB, delta);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000799 } else {
Dale Johannesen99c49a42007-02-25 00:47:03 +0000800 // What a big block. Find a place within the block to split it.
801 // This is a little tricky on Thumb since instructions are 2 bytes
802 // and constant pool entries are 4 bytes: if instruction I references
803 // island CPE, and instruction I+1 references CPE', it will
804 // not work well to put CPE as far forward as possible, since then
805 // CPE' cannot immediately follow it (that location is 2 bytes
806 // farther away from I+1 than CPE was from I) and we'd need to create
807 // a new island.
808
809 // Solution of last resort: split the user's MBB right after the user
810 // and insert a clone of the CPE into the newly created water.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000811 MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
812 NewMBB = SplitBlockBeforeInstr(NextMI);
813 }
814 }
815
816 // Okay, we know we can put an island before NewMBB now, do it!
817 MachineBasicBlock *NewIsland = new MachineBasicBlock();
818 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
819
820 // Update internal data structures to account for the newly inserted MBB.
821 UpdateForInsertedWaterBlock(NewIsland);
822
823 // Decrement the old entry, and remove it if refcount becomes 0.
824 DecrementOldEntry(CPI, CPEMI, Size);
825
826 // Now that we have an island to add the CPE to, clone the original CPE and
827 // add it to the island.
Evan Chenga8e29892007-01-19 07:51:42 +0000828 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
829 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000830 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
Evan Chengc99ef082007-02-09 20:54:44 +0000831 NumCPEs++;
832
Evan Chengb43216e2007-02-01 10:16:15 +0000833 // Compensate for .align 2 in thumb mode.
834 if (isThumb) Size += 2;
Evan Chenga8e29892007-01-19 07:51:42 +0000835 // Increase the size of the island block to account for the new entry.
836 BBSizes[NewIsland->getNumber()] += Size;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000837 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
838 AdjustBBOffsetsAfter(NewIsland, Size);
Evan Chenga8e29892007-01-19 07:51:42 +0000839
840 // Finally, change the CPI in the instruction operand to be ID.
841 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
842 if (UserMI->getOperand(i).isConstantPoolIndex()) {
843 UserMI->getOperand(i).setConstantPoolIndex(ID);
844 break;
845 }
846
Evan Chengc99ef082007-02-09 20:54:44 +0000847 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Evan Chenga8e29892007-01-19 07:51:42 +0000848
849 return true;
850}
851
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000852/// BBIsInRange - Returns true if the distance between specific MI and
Evan Cheng43aeab62007-01-26 20:38:26 +0000853/// specific BB can fit in MI's displacement field.
Evan Chengc0dbec72007-01-31 19:57:44 +0000854bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
855 unsigned MaxDisp) {
856 unsigned PCAdj = AFI->isThumbFunction() ? 4 : 8;
857 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000858 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
Evan Cheng43aeab62007-01-26 20:38:26 +0000859
Evan Chengc99ef082007-02-09 20:54:44 +0000860 DOUT << "Branch of destination BB#" << DestBB->getNumber()
861 << " from BB#" << MI->getParent()->getNumber()
862 << " max delta=" << MaxDisp
863 << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
Evan Chengc0dbec72007-01-31 19:57:44 +0000864
Dale Johannesen99c49a42007-02-25 00:47:03 +0000865 return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
Evan Cheng43aeab62007-01-26 20:38:26 +0000866}
867
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000868/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
869/// away to fit in its displacement field.
870bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000871 MachineInstr *MI = Br.MI;
872 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
873
Evan Chengc0dbec72007-01-31 19:57:44 +0000874 // Check to see if the DestBB is already in-range.
875 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
Evan Cheng43aeab62007-01-26 20:38:26 +0000876 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000877
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000878 if (!Br.isCond)
879 return FixUpUnconditionalBr(Fn, Br);
880 return FixUpConditionalBr(Fn, Br);
881}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000882
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000883/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
884/// too far away to fit in its displacement field. If the LR register has been
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000885/// spilled in the epilogue, then we can use BL to implement a far jump.
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000886/// Otherwise, add an intermediate branch instruction to to a branch.
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000887bool
888ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
889 MachineInstr *MI = Br.MI;
890 MachineBasicBlock *MBB = MI->getParent();
891 assert(AFI->isThumbFunction() && "Expected a Thumb function!");
892
893 // Use BL to implement far jump.
894 Br.MaxDisp = (1 << 21) * 2;
895 MI->setInstrDescriptor(TII->get(ARM::tBfar));
896 BBSizes[MBB->getNumber()] += 2;
Dale Johannesen99c49a42007-02-25 00:47:03 +0000897 AdjustBBOffsetsAfter(MBB, 2);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000898 HasFarJump = true;
899 NumUBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +0000900
Evan Chengc99ef082007-02-09 20:54:44 +0000901 DOUT << " Changed B to long jump " << *MI;
Evan Chengbd5d3db2007-02-03 02:08:34 +0000902
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000903 return true;
904}
905
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000906/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
907/// the specific unconditional branch instruction.
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000908static inline unsigned getUnconditionalBrDisp(int Opc) {
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000909 return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
910}
911
Dale Johannesen88e37ae2007-02-23 05:02:36 +0000912/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000913/// far away to fit in its displacement field. It is converted to an inverse
914/// conditional branch + an unconditional branch to the destination.
915bool
916ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
917 MachineInstr *MI = Br.MI;
918 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
919
920 // Add a unconditional branch to the destination and invert the branch
921 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000922 // blt L1
923 // =>
924 // bge L2
925 // b L1
926 // L2:
927 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
928 CC = ARMCC::getOppositeCondition(CC);
929
930 // If the branch is at the end of its MBB and that has a fall-through block,
931 // direct the updated conditional branch to the fall-through block. Otherwise,
932 // split the MBB before the next instruction.
933 MachineBasicBlock *MBB = MI->getParent();
Evan Chengbd5d3db2007-02-03 02:08:34 +0000934 MachineInstr *BMI = &MBB->back();
935 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
Evan Cheng43aeab62007-01-26 20:38:26 +0000936
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000937 NumCBrFixed++;
Evan Chengbd5d3db2007-02-03 02:08:34 +0000938 if (BMI != MI) {
Evan Cheng43aeab62007-01-26 20:38:26 +0000939 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
Evan Chengbd5d3db2007-02-03 02:08:34 +0000940 BMI->getOpcode() == Br.UncondBr) {
Evan Cheng43aeab62007-01-26 20:38:26 +0000941 // Last MI in the BB is a unconditional branch. Can we simply invert the
942 // condition and swap destinations:
943 // beq L1
944 // b L2
945 // =>
946 // bne L2
947 // b L1
Evan Chengbd5d3db2007-02-03 02:08:34 +0000948 MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
Evan Chengc0dbec72007-01-31 19:57:44 +0000949 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
Evan Chengc99ef082007-02-09 20:54:44 +0000950 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Evan Chengbd5d3db2007-02-03 02:08:34 +0000951 BMI->getOperand(0).setMachineBasicBlock(DestBB);
Evan Cheng43aeab62007-01-26 20:38:26 +0000952 MI->getOperand(0).setMachineBasicBlock(NewDest);
953 MI->getOperand(1).setImm(CC);
954 return true;
955 }
956 }
957 }
958
959 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000960 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +0000961 // No need for the branch to the next block. We're adding a unconditional
962 // branch to the destination.
963 MBB->back().eraseFromParent();
964 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000965 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Evan Chengbd5d3db2007-02-03 02:08:34 +0000966
Evan Chengc99ef082007-02-09 20:54:44 +0000967 DOUT << " Insert B to BB#" << DestBB->getNumber()
968 << " also invert condition and change dest. to BB#"
969 << NextBB->getNumber() << "\n";
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000970
971 // Insert a unconditional branch and replace the conditional branch.
972 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +0000973 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000974 Br.MI = &MBB->back();
975 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Evan Chenga9b8b8d2007-01-31 18:29:27 +0000976 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +0000977 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000978 MI->eraseFromParent();
979
980 // Increase the size of MBB to account for the new unconditional branch.
Dale Johannesen99c49a42007-02-25 00:47:03 +0000981 int delta = ARM::GetInstSize(&MBB->back());
982 BBSizes[MBB->getNumber()] += delta;
983 AdjustBBOffsetsAfter(MBB, delta);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000984 return true;
985}
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000986
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000987/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
988/// LR / restores LR to pc.
989bool ARMConstantIslands::UndoLRSpillRestore() {
990 bool MadeChange = false;
991 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
992 MachineInstr *MI = PushPopMIs[i];
993 if (MI->getNumOperands() == 1) {
994 if (MI->getOpcode() == ARM::tPOP_RET &&
995 MI->getOperand(0).getReg() == ARM::PC)
996 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
997 MI->eraseFromParent();
998 MadeChange = true;
999 }
1000 }
1001 return MadeChange;
1002}