blob: 1f584d4e3ef0fef3ee323097804f611a948e73b0 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengf6e7e692009-07-23 18:27:47 +000018#include "ARMAddressingModes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "ARMMachineFunctionInfo.h"
20#include "ARMInstrInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000028#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/Statistic.h"
32using namespace llvm;
33
34STATISTIC(NumCPEs, "Number of constpool entries");
35STATISTIC(NumSplit, "Number of uncond branches inserted");
36STATISTIC(NumCBrFixed, "Number of cond branches fixed");
37STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
38
39namespace {
40 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
41 /// requires constant pool entries to be scattered among the instructions
42 /// inside a function. To do this, it completely ignores the normal LLVM
43 /// constant pool; instead, it places constants wherever it feels like with
44 /// special instructions.
45 ///
46 /// The terminology used in this pass includes:
47 /// Islands - Clumps of constants placed in the function.
48 /// Water - Potential places where an island could be formed.
49 /// CPE - A constant pool entry that has been placed somewhere, which
50 /// tracks a list of users.
51 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
53 /// by MBB Number. The two-byte pads required for Thumb alignment are
54 /// counted as part of the following block (i.e., the offset and size for
55 /// a padded block will both be ==2 mod 4).
56 std::vector<unsigned> BBSizes;
Bob Wilsonec92b492009-05-12 17:09:30 +000057
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
59 /// The two-byte pads required for Thumb alignment are counted as part of
60 /// the following block.
61 std::vector<unsigned> BBOffsets;
62
63 /// WaterList - A sorted list of basic blocks where islands could be placed
64 /// (i.e. blocks that don't fall through to the following block, due
65 /// to a return, unreachable, or unconditional branch).
66 std::vector<MachineBasicBlock*> WaterList;
67
68 /// CPUser - One user of a constant pool, keeping the machine instruction
69 /// pointer, the constant pool being referenced, and the max displacement
70 /// allowed from the instruction to the CP.
71 struct CPUser {
72 MachineInstr *MI;
73 MachineInstr *CPEMI;
74 unsigned MaxDisp;
Evan Chengbf2498c2009-07-21 23:56:01 +000075 bool NegOk;
Evan Chengf6e7e692009-07-23 18:27:47 +000076 bool IsSoImm;
77 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
78 bool neg, bool soimm)
79 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080 };
Bob Wilsonec92b492009-05-12 17:09:30 +000081
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 /// CPUsers - Keep track of all of the machine instructions that use various
83 /// constant pools and their max displacement.
84 std::vector<CPUser> CPUsers;
Bob Wilsonec92b492009-05-12 17:09:30 +000085
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 /// CPEntry - One per constant pool entry, keeping the machine instruction
87 /// pointer, the constpool index, and the number of CPUser's which
88 /// reference this entry.
89 struct CPEntry {
90 MachineInstr *CPEMI;
91 unsigned CPI;
92 unsigned RefCount;
93 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
94 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
95 };
96
97 /// CPEntries - Keep track of all of the constant pool entry machine
98 /// instructions. For each original constpool index (i.e. those that
99 /// existed upon entry to this pass), it keeps a vector of entries.
100 /// Original elements are cloned as we go along; the clones are
101 /// put in the vector of the original element, but have distinct CPIs.
102 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilsonec92b492009-05-12 17:09:30 +0000103
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 /// ImmBranch - One per immediate branch, keeping the machine instruction
105 /// pointer, conditional or unconditional, the max displacement,
106 /// and (if isCond is true) the corresponding unconditional branch
107 /// opcode.
108 struct ImmBranch {
109 MachineInstr *MI;
110 unsigned MaxDisp : 31;
111 bool isCond : 1;
112 int UncondBr;
113 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
114 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
115 };
116
117 /// ImmBranches - Keep track of all the immediate branch instructions.
118 ///
119 std::vector<ImmBranch> ImmBranches;
120
121 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
122 ///
123 SmallVector<MachineInstr*, 4> PushPopMIs;
124
125 /// HasFarJump - True if any far jump instruction has been emitted during
126 /// the branch fix up pass.
127 bool HasFarJump;
128
129 const TargetInstrInfo *TII;
130 ARMFunctionInfo *AFI;
131 bool isThumb;
Evan Chengf6e7e692009-07-23 18:27:47 +0000132 bool isThumb1;
David Goodwinf6154702009-06-30 18:04:13 +0000133 bool isThumb2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 public:
135 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +0000136 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
138 virtual bool runOnMachineFunction(MachineFunction &Fn);
139
140 virtual const char *getPassName() const {
141 return "ARM constant island placement and branch shortening pass";
142 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000143
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 private:
145 void DoInitialPlacement(MachineFunction &Fn,
146 std::vector<MachineInstr*> &CPEMIs);
147 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
148 void InitialFunctionScan(MachineFunction &Fn,
149 const std::vector<MachineInstr*> &CPEMIs);
150 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
151 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
152 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
153 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
154 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonec92b492009-05-12 17:09:30 +0000155 bool LookForWater(CPUser&U, unsigned UserOffset,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 MachineBasicBlock** NewMBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000157 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 std::vector<MachineBasicBlock*>::iterator IP);
159 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
160 MachineBasicBlock** NewMBB);
161 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
162 void RemoveDeadCPEMI(MachineInstr *CPEMI);
163 bool RemoveUnusedCPEntries();
Bob Wilsonec92b492009-05-12 17:09:30 +0000164 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000165 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
166 bool DoDump = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
168 CPUser &U);
169 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000170 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
172 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
173 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
174 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
175 bool UndoLRSpillRestore();
176
177 unsigned GetOffsetOf(MachineInstr *MI) const;
178 void dumpBBs();
179 void verify(MachineFunction &Fn);
180 };
181 char ARMConstantIslands::ID = 0;
182}
183
184/// verify - check BBOffsets, BBSizes, alignment of islands
185void ARMConstantIslands::verify(MachineFunction &Fn) {
186 assert(BBOffsets.size() == BBSizes.size());
187 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
188 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengf6e7e692009-07-23 18:27:47 +0000189 if (!isThumb)
190 return;
191#ifndef NDEBUG
192 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
193 MBBI != E; ++MBBI) {
194 MachineBasicBlock *MBB = MBBI;
195 if (!MBB->empty() &&
196 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
197 unsigned MBBId = MBB->getNumber();
198 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
199 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 }
201 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000202#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203}
204
205/// print block size and offset information - debugging
206void ARMConstantIslands::dumpBBs() {
207 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000208 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 " size " << BBSizes[J] << "\n";
210 }
211}
212
213/// createARMConstantIslandPass - returns an instance of the constpool
214/// island pass.
215FunctionPass *llvm::createARMConstantIslandPass() {
216 return new ARMConstantIslands();
217}
218
219bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
220 MachineConstantPool &MCP = *Fn.getConstantPool();
Bob Wilsonec92b492009-05-12 17:09:30 +0000221
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 TII = Fn.getTarget().getInstrInfo();
223 AFI = Fn.getInfo<ARMFunctionInfo>();
224 isThumb = AFI->isThumbFunction();
Evan Chengf6e7e692009-07-23 18:27:47 +0000225 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwinf6154702009-06-30 18:04:13 +0000226 isThumb2 = AFI->isThumb2Function();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227
228 HasFarJump = false;
229
230 // Renumber all of the machine basic blocks in the function, guaranteeing that
231 // the numbers agree with the position of the block in the function.
232 Fn.RenumberBlocks();
233
Evan Chengf6e7e692009-07-23 18:27:47 +0000234 // Thumb1 functions containing constant pools get 2-byte alignment.
235 // This is so we can keep exact track of where the alignment padding goes.
236
237 // Set default. Thumb1 function is 1-byte aligned, ARM and Thumb2 are 2-byte
238 // aligned.
239 AFI->setAlign(isThumb1 ? 1U : 2U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240
241 // Perform the initial placement of the constant pool entries. To start with,
242 // we put them all at the end of the function.
243 std::vector<MachineInstr*> CPEMIs;
244 if (!MCP.isEmpty()) {
245 DoInitialPlacement(Fn, CPEMIs);
Evan Chengf6e7e692009-07-23 18:27:47 +0000246 if (isThumb1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 AFI->setAlign(2U);
248 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000249
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 /// The next UID to take is the first unused one.
Evan Chengd3c573a2008-11-08 00:51:41 +0000251 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilsonec92b492009-05-12 17:09:30 +0000252
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 // Do the initial scan of the function, building up information about the
254 // sizes of each block, the location of all the water, and finding all of the
255 // constant pool users.
256 InitialFunctionScan(Fn, CPEMIs);
257 CPEMIs.clear();
Bob Wilsonec92b492009-05-12 17:09:30 +0000258
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 /// Remove dead constant pool entries.
260 RemoveUnusedCPEntries();
261
262 // Iteratively place constant pool entries and fix up branches until there
263 // is no change.
264 bool MadeChange = false;
265 while (true) {
266 bool Change = false;
267 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
268 Change |= HandleConstantPoolUser(Fn, i);
269 DEBUG(dumpBBs());
270 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
271 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
272 DEBUG(dumpBBs());
273 if (!Change)
274 break;
275 MadeChange = true;
276 }
277
278 // After a while, this might be made debug-only, but it is not expensive.
279 verify(Fn);
280
281 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
282 // Undo the spill / restore of LR if possible.
283 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
284 MadeChange |= UndoLRSpillRestore();
285
286 BBSizes.clear();
287 BBOffsets.clear();
288 WaterList.clear();
289 CPUsers.clear();
290 CPEntries.clear();
291 ImmBranches.clear();
292 PushPopMIs.clear();
293
294 return MadeChange;
295}
296
297/// DoInitialPlacement - Perform the initial placement of the constant pool
298/// entries. To start with, we put them all at the end of the function.
299void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
Bob Wilsonec92b492009-05-12 17:09:30 +0000300 std::vector<MachineInstr*> &CPEMIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 // Create the basic block to hold the CPE's.
Dan Gohman221a4372008-07-07 23:14:23 +0000302 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
303 Fn.push_back(BB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000304
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 // Add all of the constants from the constant pool to the end block, use an
306 // identity mapping of CPI's to CPE's.
307 const std::vector<MachineConstantPoolEntry> &CPs =
308 Fn.getConstantPool()->getConstants();
Bob Wilsonec92b492009-05-12 17:09:30 +0000309
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310 const TargetData &TD = *Fn.getTarget().getTargetData();
311 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000312 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
314 // we would have to pad them out or something so that instructions stay
315 // aligned.
316 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
317 MachineInstr *CPEMI =
Dale Johannesene8a10c42009-02-13 02:25:56 +0000318 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 .addImm(i).addConstantPoolIndex(i).addImm(Size);
320 CPEMIs.push_back(CPEMI);
321
322 // Add a new CPEntry, but no corresponding CPUser yet.
323 std::vector<CPEntry> CPEs;
324 CPEs.push_back(CPEntry(CPEMI, i));
325 CPEntries.push_back(CPEs);
326 NumCPEs++;
327 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
328 }
329}
330
331/// BBHasFallthrough - Return true if the specified basic block can fallthrough
332/// into the block immediately after it.
333static bool BBHasFallthrough(MachineBasicBlock *MBB) {
334 // Get the next machine basic block in the function.
335 MachineFunction::iterator MBBI = MBB;
336 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
337 return false;
Bob Wilsonec92b492009-05-12 17:09:30 +0000338
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 MachineBasicBlock *NextBB = next(MBBI);
340 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
341 E = MBB->succ_end(); I != E; ++I)
342 if (*I == NextBB)
343 return true;
Bob Wilsonec92b492009-05-12 17:09:30 +0000344
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 return false;
346}
347
348/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
349/// look up the corresponding CPEntry.
350ARMConstantIslands::CPEntry
351*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
352 const MachineInstr *CPEMI) {
353 std::vector<CPEntry> &CPEs = CPEntries[CPI];
354 // Number of entries per constpool index should be small, just do a
355 // linear search.
356 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
357 if (CPEs[i].CPEMI == CPEMI)
358 return &CPEs[i];
359 }
360 return NULL;
361}
362
363/// InitialFunctionScan - Do the initial scan of the function, building up
364/// information about the sizes of each block, the location of all the water,
365/// and finding all of the constant pool users.
366void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
367 const std::vector<MachineInstr*> &CPEMIs) {
368 unsigned Offset = 0;
369 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
370 MBBI != E; ++MBBI) {
371 MachineBasicBlock &MBB = *MBBI;
Bob Wilsonec92b492009-05-12 17:09:30 +0000372
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373 // If this block doesn't fall through into the next MBB, then this is
374 // 'water' that a constant pool island could be placed.
375 if (!BBHasFallthrough(&MBB))
376 WaterList.push_back(&MBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000377
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 unsigned MBBSize = 0;
379 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
380 I != E; ++I) {
381 // Add instruction size to MBBSize.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000382 MBBSize += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383
384 int Opc = I->getOpcode();
Chris Lattner5b930372008-01-07 07:27:27 +0000385 if (I->getDesc().isBranch()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 bool isCond = false;
387 unsigned Bits = 0;
388 unsigned Scale = 1;
389 int UOpc = Opc;
390 switch (Opc) {
391 case ARM::tBR_JTr:
David Goodwinf6154702009-06-30 18:04:13 +0000392 case ARM::t2BR_JTr:
David Goodwin13d2f4e2009-06-30 19:50:22 +0000393 case ARM::t2BR_JTm:
394 case ARM::t2BR_JTadd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 // A Thumb table jump may involve padding; for the offsets to
396 // be right, functions containing these must be 4-byte aligned.
397 AFI->setAlign(2U);
398 if ((Offset+MBBSize)%4 != 0)
399 MBBSize += 2; // padding
400 continue; // Does not get an entry in ImmBranches
401 default:
402 continue; // Ignore other JT branches
403 case ARM::Bcc:
404 isCond = true;
405 UOpc = ARM::B;
406 // Fallthrough
407 case ARM::B:
408 Bits = 24;
409 Scale = 4;
410 break;
411 case ARM::tBcc:
412 isCond = true;
413 UOpc = ARM::tB;
414 Bits = 8;
415 Scale = 2;
416 break;
417 case ARM::tB:
418 Bits = 11;
419 Scale = 2;
420 break;
David Goodwinf6154702009-06-30 18:04:13 +0000421 case ARM::t2Bcc:
422 isCond = true;
423 UOpc = ARM::t2B;
424 Bits = 20;
425 Scale = 2;
426 break;
427 case ARM::t2B:
428 Bits = 24;
429 Scale = 2;
430 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 }
432
433 // Record this immediate branch.
434 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
435 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
436 }
437
438 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
439 PushPopMIs.push_back(I);
440
Evan Chengf6e7e692009-07-23 18:27:47 +0000441 if (Opc == ARM::CONSTPOOL_ENTRY)
442 continue;
443
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 // Scan the instructions for constant pool operands.
445 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000446 if (I->getOperand(op).isCPI()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000447 // We found one. The addressing mode tells us the max displacement
448 // from the PC that this instruction permits.
Bob Wilsonec92b492009-05-12 17:09:30 +0000449
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 // Basic size info comes from the TSFlags field.
451 unsigned Bits = 0;
452 unsigned Scale = 1;
Evan Chengbf2498c2009-07-21 23:56:01 +0000453 bool NegOk = false;
Evan Chengf6e7e692009-07-23 18:27:47 +0000454 bool IsSoImm = false;
455
456 switch (Opc) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000457 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000458 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengf6e7e692009-07-23 18:27:47 +0000459 break;
460
461 // Taking the address of a CP entry.
462 case ARM::LEApcrel:
463 // This takes a SoImm, which is 8 bit immediate rotated. We'll
464 // pretend the maximum offset is 255 * 4. Since each instruction
465 // 4 byte wide, this is always correct. We'llc heck for other
466 // displacements that fits in a SoImm as well.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 Bits = 8;
Evan Chengf6e7e692009-07-23 18:27:47 +0000468 Scale = 4;
469 NegOk = true;
470 IsSoImm = true;
471 break;
472 case ARM::t2LEApcrel:
473 Bits = 12;
Evan Chengbf2498c2009-07-21 23:56:01 +0000474 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000476 case ARM::tLEApcrel:
477 Bits = 8;
478 Scale = 4;
479 break;
480
481 case ARM::LDR:
482 case ARM::LDRcp:
483 case ARM::t2LDRpci:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 Bits = 12; // +-offset_12
Evan Chengbf2498c2009-07-21 23:56:01 +0000485 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000487
488 case ARM::tLDRpci:
489 case ARM::tLDRcp:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490 Bits = 8;
491 Scale = 4; // +(offset_8*4)
492 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000493
494 case ARM::FLDD:
495 case ARM::FLDS:
496 Bits = 8;
497 Scale = 4; // +-(offset_8*4)
498 NegOk = true;
Evan Cheng532cdc52009-06-29 07:51:04 +0000499 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 }
501
502 // Remember that this is a user of a CP entry.
Chris Lattner6017d482007-12-30 23:10:15 +0000503 unsigned CPI = I->getOperand(op).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 MachineInstr *CPEMI = CPEMIs[CPI];
Bob Wilsonec92b492009-05-12 17:09:30 +0000505 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengf6e7e692009-07-23 18:27:47 +0000506 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507
508 // Increment corresponding CPEntry reference count.
509 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
510 assert(CPE && "Cannot find a corresponding CPEntry!");
511 CPE->RefCount++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000512
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 // Instructions can only use one CP entry, don't bother scanning the
514 // rest of the operands.
515 break;
516 }
517 }
518
519 // In thumb mode, if this block is a constpool island, we may need padding
520 // so it's aligned on 4 byte boundary.
521 if (isThumb &&
522 !MBB.empty() &&
523 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
524 (Offset%4) != 0)
525 MBBSize += 2;
526
527 BBSizes.push_back(MBBSize);
528 BBOffsets.push_back(Offset);
529 Offset += MBBSize;
530 }
531}
532
533/// GetOffsetOf - Return the current offset of the specified machine instruction
534/// from the start of the function. This offset changes as stuff is moved
535/// around inside the function.
536unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
537 MachineBasicBlock *MBB = MI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000538
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 // The offset is composed of two things: the sum of the sizes of all MBB's
540 // before this instruction's block, and the offset from the start of the block
541 // it is in.
542 unsigned Offset = BBOffsets[MBB->getNumber()];
543
544 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
545 // alignment padding, and compensate if so.
Bob Wilsonec92b492009-05-12 17:09:30 +0000546 if (isThumb &&
547 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 Offset%4 != 0)
549 Offset += 2;
550
551 // Sum instructions before MI in MBB.
552 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
553 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
554 if (&*I == MI) return Offset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000555 Offset += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 }
557}
558
559/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
560/// ID.
561static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
562 const MachineBasicBlock *RHS) {
563 return LHS->getNumber() < RHS->getNumber();
564}
565
566/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
567/// machine function, it upsets all of the block numbers. Renumber the blocks
568/// and update the arrays that parallel this numbering.
569void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
570 // Renumber the MBB's to keep them consequtive.
571 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000572
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573 // Insert a size into BBSizes to align it properly with the (newly
574 // renumbered) block numbers.
575 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
576
577 // Likewise for BBOffsets.
578 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000579
580 // Next, update WaterList. Specifically, we need to add NewMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 // available water after it.
582 std::vector<MachineBasicBlock*>::iterator IP =
583 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
584 CompareMBBNumbers);
585 WaterList.insert(IP, NewBB);
586}
587
588
589/// Split the basic block containing MI into two blocks, which are joined by
590/// an unconditional branch. Update datastructures and renumber blocks to
591/// account for this change and returns the newly created block.
592MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
593 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman221a4372008-07-07 23:14:23 +0000594 MachineFunction &MF = *OrigBB->getParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595
596 // Create a new MBB for the code after the OrigBB.
Bob Wilsonec92b492009-05-12 17:09:30 +0000597 MachineBasicBlock *NewBB =
598 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman221a4372008-07-07 23:14:23 +0000600 MF.insert(MBBI, NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000601
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 // Splice the instructions starting with MI over to NewBB.
603 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilsonec92b492009-05-12 17:09:30 +0000604
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 // Add an unconditional branch from OrigBB to NewBB.
606 // Note the new unconditional branch is not being recorded.
Dale Johannesene8a10c42009-02-13 02:25:56 +0000607 // There doesn't seem to be meaningful DebugInfo available; this doesn't
608 // correspond to anything in the source.
Evan Cheng451192e2009-07-07 01:16:41 +0000609 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
610 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 NumSplit++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000612
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 // Update the CFG. All succs of OrigBB are now succs of NewBB.
614 while (!OrigBB->succ_empty()) {
615 MachineBasicBlock *Succ = *OrigBB->succ_begin();
616 OrigBB->removeSuccessor(Succ);
617 NewBB->addSuccessor(Succ);
Bob Wilsonec92b492009-05-12 17:09:30 +0000618
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 // This pass should be run after register allocation, so there should be no
620 // PHI nodes to update.
621 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
622 && "PHI nodes should be eliminated by now!");
623 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000624
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 // OrigBB branches to NewBB.
626 OrigBB->addSuccessor(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000627
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 // Update internal data structures to account for the newly inserted MBB.
629 // This is almost the same as UpdateForInsertedWaterBlock, except that
630 // the Water goes after OrigBB, not NewBB.
Dan Gohman221a4372008-07-07 23:14:23 +0000631 MF.RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000632
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 // Insert a size into BBSizes to align it properly with the (newly
634 // renumbered) block numbers.
635 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000636
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 // Likewise for BBOffsets.
638 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
639
Bob Wilsonec92b492009-05-12 17:09:30 +0000640 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 // available water after it (but not if it's already there, which happens
642 // when splitting before a conditional branch that is followed by an
643 // unconditional branch - in that case we want to insert NewBB).
644 std::vector<MachineBasicBlock*>::iterator IP =
645 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
646 CompareMBBNumbers);
647 MachineBasicBlock* WaterBB = *IP;
648 if (WaterBB == OrigBB)
649 WaterList.insert(next(IP), NewBB);
650 else
651 WaterList.insert(IP, OrigBB);
652
653 // Figure out how large the first NewMBB is. (It cannot
654 // contain a constpool_entry or tablejump.)
655 unsigned NewBBSize = 0;
656 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
657 I != E; ++I)
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000658 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilsonec92b492009-05-12 17:09:30 +0000659
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 unsigned OrigBBI = OrigBB->getNumber();
661 unsigned NewBBI = NewBB->getNumber();
662 // Set the size of NewBB in BBSizes.
663 BBSizes[NewBBI] = NewBBSize;
Bob Wilsonec92b492009-05-12 17:09:30 +0000664
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 // We removed instructions from UserMBB, subtract that off from its size.
666 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Chengf6e7e692009-07-23 18:27:47 +0000667 unsigned delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 BBSizes[OrigBBI] -= NewBBSize - delta;
669
670 // ...and adjust BBOffsets for NewBB accordingly.
671 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
672
673 // All BBOffsets following these blocks must be modified.
674 AdjustBBOffsetsAfter(NewBB, delta);
675
676 return NewBB;
677}
678
679/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilsonec92b492009-05-12 17:09:30 +0000680/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681/// constant pool entry).
Bob Wilsonec92b492009-05-12 17:09:30 +0000682bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000683 unsigned TrialOffset, unsigned MaxDisp,
684 bool NegativeOK, bool IsSoImm) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000685 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
686 // purposes of the displacement computation; compensate for that here.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 // Effectively, the valid range of displacements is 2 bytes smaller for such
688 // references.
689 if (isThumb && UserOffset%4 !=0)
690 UserOffset -= 2;
691 // CPEs will be rounded up to a multiple of 4.
692 if (isThumb && TrialOffset%4 != 0)
693 TrialOffset += 2;
694
695 if (UserOffset <= TrialOffset) {
696 // User before the Trial.
Evan Chengf6e7e692009-07-23 18:27:47 +0000697 if (TrialOffset - UserOffset <= MaxDisp)
698 return true;
699 if (IsSoImm && ARM_AM::getSOImmVal(TrialOffset - UserOffset) != -1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 return true;
701 } else if (NegativeOK) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000702 if (UserOffset - TrialOffset <= MaxDisp)
703 return true;
704 if (IsSoImm && ARM_AM::getSOImmVal(~(TrialOffset - UserOffset)) != -1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 return true;
706 }
707 return false;
708}
709
710/// WaterIsInRange - Returns true if a CPE placed after the specified
711/// Water (a basic block) will be in range for the specific MI.
712
713bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000714 MachineBasicBlock* Water, CPUser &U) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 unsigned MaxDisp = U.MaxDisp;
Bob Wilsonec92b492009-05-12 17:09:30 +0000716 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 BBSizes[Water->getNumber()];
718
719 // If the CPE is to be inserted before the instruction, that will raise
720 // the offset of the instruction. (Currently applies only to ARM, so
721 // no alignment compensation attempted here.)
722 if (CPEOffset < UserOffset)
723 UserOffset += U.CPEMI->getOperand(2).getImm();
724
Evan Chengf6e7e692009-07-23 18:27:47 +0000725 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726}
727
728/// CPEIsInRange - Returns true if the distance between specific MI and
729/// specific ConstPool entry instruction can fit in MI's displacement field.
730bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000731 MachineInstr *CPEMI, unsigned MaxDisp,
732 bool NegOk, bool DoDump) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 unsigned CPEOffset = GetOffsetOf(CPEMI);
734 assert(CPEOffset%4 == 0 && "Misaligned CPE");
735
736 if (DoDump) {
737 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
738 << " max delta=" << MaxDisp
739 << " insn address=" << UserOffset
740 << " CPE address=" << CPEOffset
741 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
742 }
743
Evan Chengbf2498c2009-07-21 23:56:01 +0000744 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745}
746
Evan Cheng10361732009-01-28 00:53:34 +0000747#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
749/// unconditionally branches to its only successor.
750static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
751 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
752 return false;
753
754 MachineBasicBlock *Succ = *MBB->succ_begin();
755 MachineBasicBlock *Pred = *MBB->pred_begin();
756 MachineInstr *PredMI = &Pred->back();
David Goodwinf6154702009-06-30 18:04:13 +0000757 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
758 || PredMI->getOpcode() == ARM::t2B)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 return PredMI->getOperand(0).getMBB() == Succ;
760 return false;
761}
Evan Cheng10361732009-01-28 00:53:34 +0000762#endif // NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763
Bob Wilsonec92b492009-05-12 17:09:30 +0000764void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 int delta) {
766 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengf6e7e692009-07-23 18:27:47 +0000767 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
768 i < e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 BBOffsets[i] += delta;
770 // If some existing blocks have padding, adjust the padding as needed, a
771 // bit tricky. delta can be negative so don't use % on that.
Evan Chengf6e7e692009-07-23 18:27:47 +0000772 if (!isThumb)
773 continue;
774 MachineBasicBlock *MBB = MBBI;
775 if (!MBB->empty()) {
776 // Constant pool entries require padding.
777 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
778 unsigned oldOffset = BBOffsets[i] - delta;
779 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
780 // add new padding
781 BBSizes[i] += 2;
782 delta += 2;
783 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
784 // remove existing padding
785 BBSizes[i] -=2;
786 delta -= 2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000789 // Thumb1 jump tables require padding. They should be at the end;
790 // following unconditional branches are removed by AnalyzeBranch.
Evan Chenga609c1d2009-07-24 18:20:44 +0000791 MachineInstr *ThumbJTMI = prior(MBB->end());
792 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr ||
793 ThumbJTMI->getOpcode() == ARM::t2BR_JTr ||
794 ThumbJTMI->getOpcode() == ARM::t2BR_JTm ||
795 ThumbJTMI->getOpcode() == ARM::t2BR_JTadd) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000796 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
797 unsigned oldMIOffset = newMIOffset - delta;
798 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
799 // remove existing padding
800 BBSizes[i] -= 2;
801 delta -= 2;
802 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
803 // add new padding
804 BBSizes[i] += 2;
805 delta += 2;
806 }
807 }
808 if (delta==0)
809 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000811 MBBI = next(MBBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 }
813}
814
815/// DecrementOldEntry - find the constant pool entry with index CPI
816/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilsonec92b492009-05-12 17:09:30 +0000817/// becomes 0 remove the entry and instruction. Returns true if we removed
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818/// the entry, false if we didn't.
819
820bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
821 // Find the old entry. Eliminate it if it is no longer used.
822 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
823 assert(CPE && "Unexpected!");
824 if (--CPE->RefCount == 0) {
825 RemoveDeadCPEMI(CPEMI);
826 CPE->CPEMI = NULL;
827 NumCPEs--;
828 return true;
829 }
830 return false;
831}
832
833/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
834/// if not, see if an in-range clone of the CPE is in range, and if so,
835/// change the data structures so the user references the clone. Returns:
836/// 0 = no existing entry found
837/// 1 = entry found, and there were no code insertions or deletions
838/// 2 = entry found, and there were code insertions or deletions
839int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
840{
841 MachineInstr *UserMI = U.MI;
842 MachineInstr *CPEMI = U.CPEMI;
843
844 // Check to see if the CPE is already in-range.
Evan Chengbf2498c2009-07-21 23:56:01 +0000845 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 DOUT << "In range\n";
847 return 1;
848 }
849
850 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner6017d482007-12-30 23:10:15 +0000851 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 std::vector<CPEntry> &CPEs = CPEntries[CPI];
853 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
854 // We already tried this one
855 if (CPEs[i].CPEMI == CPEMI)
856 continue;
857 // Removing CPEs can leave empty entries, skip
858 if (CPEs[i].CPEMI == NULL)
859 continue;
Evan Chengbf2498c2009-07-21 23:56:01 +0000860 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
862 // Point the CPUser node to the replacement
863 U.CPEMI = CPEs[i].CPEMI;
864 // Change the CPI in the instruction operand to refer to the clone.
865 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000866 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +0000867 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 break;
869 }
870 // Adjust the refcount of the clone...
871 CPEs[i].RefCount++;
872 // ...and the original. If we didn't remove the old entry, none of the
873 // addresses changed, so we don't need another pass.
874 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
875 }
876 }
877 return 0;
878}
879
880/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
881/// the specific unconditional branch instruction.
882static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwinf6154702009-06-30 18:04:13 +0000883 switch (Opc) {
884 case ARM::tB:
885 return ((1<<10)-1)*2;
886 case ARM::t2B:
887 return ((1<<23)-1)*2;
888 default:
889 break;
890 }
891
892 return ((1<<23)-1)*4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893}
894
895/// AcceptWater - Small amount of common code factored out of the following.
896
Bob Wilsonec92b492009-05-12 17:09:30 +0000897MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000898 std::vector<MachineBasicBlock*>::iterator IP) {
899 DOUT << "found water in range\n";
900 // Remove the original WaterList entry; we want subsequent
901 // insertions in this vicinity to go after the one we're
902 // about to insert. This considerably reduces the number
903 // of times we have to move the same CPE more than once.
904 WaterList.erase(IP);
905 // CPE goes before following block (NewMBB).
906 return next(MachineFunction::iterator(WaterBB));
907}
908
909/// LookForWater - look for an existing entry in the WaterList in which
910/// we can place the CPE referenced from U so it's within range of U's MI.
911/// Returns true if found, false if not. If it returns true, *NewMBB
912/// is set to the WaterList entry.
Evan Chengf6e7e692009-07-23 18:27:47 +0000913/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914/// water that will not introduce padding to water that will; within each
915/// group, prefer the water that's farthest away.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
917 MachineBasicBlock** NewMBB) {
918 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
919 MachineBasicBlock* WaterBBThatWouldPad = NULL;
920 if (!WaterList.empty()) {
921 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengf6e7e692009-07-23 18:27:47 +0000922 B = WaterList.begin();; --IP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 MachineBasicBlock* WaterBB = *IP;
924 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000925 unsigned WBBId = WaterBB->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 if (isThumb &&
Evan Chengf6e7e692009-07-23 18:27:47 +0000927 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 // This is valid Water, but would introduce padding. Remember
929 // it in case we don't find any Water that doesn't do this.
930 if (!WaterBBThatWouldPad) {
931 WaterBBThatWouldPad = WaterBB;
932 IPThatWouldPad = IP;
933 }
934 } else {
935 *NewMBB = AcceptWater(WaterBB, IP);
936 return true;
937 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000938 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 if (IP == B)
940 break;
941 }
942 }
943 if (isThumb && WaterBBThatWouldPad) {
944 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
945 return true;
946 }
947 return false;
948}
949
Bob Wilsonec92b492009-05-12 17:09:30 +0000950/// CreateNewWater - No existing WaterList entry will work for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
952/// block is used if in range, and the conditional branch munged so control
953/// flow is correct. Otherwise the block is split to create a hole with an
954/// unconditional branch around it. In either case *NewMBB is set to a
955/// block following which the new island can be inserted (the WaterList
956/// is not adjusted).
957
Bob Wilsonec92b492009-05-12 17:09:30 +0000958void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959 unsigned UserOffset, MachineBasicBlock** NewMBB) {
960 CPUser &U = CPUsers[CPUserIndex];
961 MachineInstr *UserMI = U.MI;
962 MachineInstr *CPEMI = U.CPEMI;
963 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000964 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 BBSizes[UserMBB->getNumber()];
966 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
967
968 // If the use is at the end of the block, or the end of the block
969 // is within range, make new water there. (The addition below is
Evan Chengf6e7e692009-07-23 18:27:47 +0000970 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
971 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 // inside OffsetIsInRange.
Bob Wilsonec92b492009-05-12 17:09:30 +0000973 // If the block ends in an unconditional branch already, it is water,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 // and is known to be out of range, so we'll always be adding a branch.)
975 if (&UserMBB->back() == UserMI ||
Evan Chengf6e7e692009-07-23 18:27:47 +0000976 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
977 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 DOUT << "Split at end of block\n";
979 if (&UserMBB->back() == UserMI)
980 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
981 *NewMBB = next(MachineFunction::iterator(UserMBB));
982 // Add an unconditional branch from UserMBB to fallthrough block.
983 // Record it for branch lengthening; this new branch will not get out of
984 // range, but if the preceding conditional branch is out of range, the
985 // targets will be exchanged, and the altered branch may be out of
986 // range, so the machinery has to know about it.
David Goodwinf6154702009-06-30 18:04:13 +0000987 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesene8a10c42009-02-13 02:25:56 +0000988 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
989 TII->get(UncondBr)).addMBB(*NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilsonec92b492009-05-12 17:09:30 +0000991 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 MaxDisp, false, UncondBr));
Evan Chengf6e7e692009-07-23 18:27:47 +0000993 int delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 BBSizes[UserMBB->getNumber()] += delta;
995 AdjustBBOffsetsAfter(UserMBB, delta);
996 } else {
997 // What a big block. Find a place within the block to split it.
Evan Chengf6e7e692009-07-23 18:27:47 +0000998 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 // and constant pool entries are 4 bytes: if instruction I references
1000 // island CPE, and instruction I+1 references CPE', it will
1001 // not work well to put CPE as far forward as possible, since then
1002 // CPE' cannot immediately follow it (that location is 2 bytes
1003 // farther away from I+1 than CPE was from I) and we'd need to create
1004 // a new island. So, we make a first guess, then walk through the
1005 // instructions between the one currently being looked at and the
1006 // possible insertion point, and make sure any other instructions
1007 // that reference CPEs will be able to use the same island area;
1008 // if not, we back up the insertion point.
1009
1010 // The 4 in the following is for the unconditional branch we'll be
Evan Chengf6e7e692009-07-23 18:27:47 +00001011 // inserting (allows for long branch on Thumb1). Alignment of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 // island is handled inside OffsetIsInRange.
1013 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1014 // This could point off the end of the block if we've already got
1015 // constant pool entries following this block; only the last one is
1016 // in the water list. Back past any possible branches (allow for a
1017 // conditional and a maximally long unconditional).
1018 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilsonec92b492009-05-12 17:09:30 +00001019 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengf6e7e692009-07-23 18:27:47 +00001020 (isThumb1 ? 6 : 8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 unsigned EndInsertOffset = BaseInsertOffset +
1022 CPEMI->getOperand(2).getImm();
1023 MachineBasicBlock::iterator MI = UserMI;
1024 ++MI;
1025 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001026 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027 Offset < BaseInsertOffset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001028 Offset += TII->GetInstSizeInBytes(MI),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 MI = next(MI)) {
1030 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001031 CPUser &U = CPUsers[CPUIndex];
Bob Wilsonec92b492009-05-12 17:09:30 +00001032 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +00001033 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1034 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1035 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 }
1037 // This is overly conservative, as we don't account for CPEMIs
1038 // being reused within the block, but it doesn't matter much.
1039 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1040 CPUIndex++;
1041 }
1042 }
1043 DOUT << "Split in middle of big block\n";
1044 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1045 }
1046}
1047
1048/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsond6985d52009-05-12 17:35:29 +00001049/// is out-of-range. If so, pick up the constant pool value and move it some
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050/// place in-range. Return true if we changed any addresses (thus must run
1051/// another pass of branch lengthening), false otherwise.
Bob Wilsonec92b492009-05-12 17:09:30 +00001052bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1053 unsigned CPUserIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 CPUser &U = CPUsers[CPUserIndex];
1055 MachineInstr *UserMI = U.MI;
1056 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001057 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 unsigned Size = CPEMI->getOperand(2).getImm();
1059 MachineBasicBlock *NewMBB;
1060 // Compute this only once, it's expensive. The 4 or 8 is the value the
Bob Wilsond6985d52009-05-12 17:35:29 +00001061 // hardware keeps in the PC (2 insns ahead of the reference).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1063
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 // See if the current entry is within range, or there is a clone of it
1065 // in range.
1066 int result = LookForExistingCPEntry(U, UserOffset);
1067 if (result==1) return false;
1068 else if (result==2) return true;
1069
1070 // No existing clone of this CPE is within range.
1071 // We will be generating a new clone. Get a UID for it.
Bob Wilsond6985d52009-05-12 17:35:29 +00001072 unsigned ID = AFI->createConstPoolEntryUId();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073
1074 // Look for water where we can place this CPE. We look for the farthest one
1075 // away that will work. Forward references only for now (although later
1076 // we might find some that are backwards).
1077
1078 if (!LookForWater(U, UserOffset, &NewMBB)) {
1079 // No water found.
1080 DOUT << "No water found\n";
1081 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1082 }
1083
1084 // Okay, we know we can put an island before NewMBB now, do it!
Dan Gohman221a4372008-07-07 23:14:23 +00001085 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1086 Fn.insert(NewMBB, NewIsland);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087
1088 // Update internal data structures to account for the newly inserted MBB.
1089 UpdateForInsertedWaterBlock(NewIsland);
1090
1091 // Decrement the old entry, and remove it if refcount becomes 0.
1092 DecrementOldEntry(CPI, CPEMI);
1093
1094 // Now that we have an island to add the CPE to, clone the original CPE and
1095 // add it to the island.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001096 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1097 TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1099 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1100 NumCPEs++;
1101
1102 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1103 // Compensate for .align 2 in thumb mode.
Bob Wilsonec92b492009-05-12 17:09:30 +00001104 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 Size += 2;
1106 // Increase the size of the island block to account for the new entry.
1107 BBSizes[NewIsland->getNumber()] += Size;
1108 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilsonec92b492009-05-12 17:09:30 +00001109
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 // Finally, change the CPI in the instruction operand to be ID.
1111 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001112 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +00001113 UserMI->getOperand(i).setIndex(ID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 break;
1115 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001116
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilsonec92b492009-05-12 17:09:30 +00001118
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 return true;
1120}
1121
1122/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1123/// sizes and offsets of impacted basic blocks.
1124void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1125 MachineBasicBlock *CPEBB = CPEMI->getParent();
1126 unsigned Size = CPEMI->getOperand(2).getImm();
1127 CPEMI->eraseFromParent();
1128 BBSizes[CPEBB->getNumber()] -= Size;
1129 // All succeeding offsets have the current size value added in, fix this.
1130 if (CPEBB->empty()) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001131 // In thumb1 mode, the size of island may be padded by two to compensate for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 // the alignment requirement. Then it will now be 2 when the block is
1133 // empty, so fix this.
1134 // All succeeding offsets have the current size value added in, fix this.
1135 if (BBSizes[CPEBB->getNumber()] != 0) {
1136 Size += BBSizes[CPEBB->getNumber()];
1137 BBSizes[CPEBB->getNumber()] = 0;
1138 }
1139 }
1140 AdjustBBOffsetsAfter(CPEBB, -Size);
1141 // An island has only one predecessor BB and one successor BB. Check if
1142 // this BB's predecessor jumps directly to this BB's successor. This
1143 // shouldn't happen currently.
1144 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1145 // FIXME: remove the empty blocks after all the work is done?
1146}
1147
1148/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1149/// are zero.
1150bool ARMConstantIslands::RemoveUnusedCPEntries() {
1151 unsigned MadeChange = false;
1152 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1153 std::vector<CPEntry> &CPEs = CPEntries[i];
1154 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1155 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1156 RemoveDeadCPEMI(CPEs[j].CPEMI);
1157 CPEs[j].CPEMI = NULL;
1158 MadeChange = true;
1159 }
1160 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001161 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 return MadeChange;
1163}
1164
1165/// BBIsInRange - Returns true if the distance between specific MI and
1166/// specific BB can fit in MI's displacement field.
1167bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1168 unsigned MaxDisp) {
1169 unsigned PCAdj = isThumb ? 4 : 8;
1170 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1171 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1172
1173 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1174 << " from BB#" << MI->getParent()->getNumber()
1175 << " max delta=" << MaxDisp
1176 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1177 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1178
1179 if (BrOffset <= DestOffset) {
1180 // Branch before the Dest.
1181 if (DestOffset-BrOffset <= MaxDisp)
1182 return true;
1183 } else {
1184 if (BrOffset-DestOffset <= MaxDisp)
1185 return true;
1186 }
1187 return false;
1188}
1189
1190/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1191/// away to fit in its displacement field.
1192bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1193 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001194 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195
1196 // Check to see if the DestBB is already in-range.
1197 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1198 return false;
1199
1200 if (!Br.isCond)
1201 return FixUpUnconditionalBr(Fn, Br);
1202 return FixUpConditionalBr(Fn, Br);
1203}
1204
1205/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1206/// too far away to fit in its displacement field. If the LR register has been
1207/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsond6985d52009-05-12 17:35:29 +00001208/// Otherwise, add an intermediate branch instruction to a branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209bool
1210ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1211 MachineInstr *MI = Br.MI;
1212 MachineBasicBlock *MBB = MI->getParent();
Evan Chengf6e7e692009-07-23 18:27:47 +00001213 assert(isThumb && !isThumb2 && "Expected a Thumb1 function!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214
1215 // Use BL to implement far jump.
1216 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner86bb02f2008-01-11 18:10:50 +00001217 MI->setDesc(TII->get(ARM::tBfar));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218 BBSizes[MBB->getNumber()] += 2;
1219 AdjustBBOffsetsAfter(MBB, 2);
1220 HasFarJump = true;
1221 NumUBrFixed++;
1222
1223 DOUT << " Changed B to long jump " << *MI;
1224
1225 return true;
1226}
1227
1228/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1229/// far away to fit in its displacement field. It is converted to an inverse
1230/// conditional branch + an unconditional branch to the destination.
1231bool
1232ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1233 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001234 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235
Bob Wilsond6985d52009-05-12 17:35:29 +00001236 // Add an unconditional branch to the destination and invert the branch
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 // condition to jump over it:
1238 // blt L1
1239 // =>
1240 // bge L2
1241 // b L1
1242 // L2:
Chris Lattnera96056a2007-12-30 20:49:49 +00001243 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 CC = ARMCC::getOppositeCondition(CC);
1245 unsigned CCReg = MI->getOperand(2).getReg();
1246
1247 // If the branch is at the end of its MBB and that has a fall-through block,
1248 // direct the updated conditional branch to the fall-through block. Otherwise,
1249 // split the MBB before the next instruction.
1250 MachineBasicBlock *MBB = MI->getParent();
1251 MachineInstr *BMI = &MBB->back();
1252 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1253
1254 NumCBrFixed++;
1255 if (BMI != MI) {
Dan Gohman221a4372008-07-07 23:14:23 +00001256 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsond6985d52009-05-12 17:35:29 +00001258 // Last MI in the BB is an unconditional branch. Can we simply invert the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 // condition and swap destinations:
1260 // beq L1
1261 // b L2
1262 // =>
1263 // bne L2
1264 // b L1
Chris Lattner6017d482007-12-30 23:10:15 +00001265 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1267 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001268 BMI->getOperand(0).setMBB(DestBB);
1269 MI->getOperand(0).setMBB(NewDest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 MI->getOperand(1).setImm(CC);
1271 return true;
1272 }
1273 }
1274 }
1275
1276 if (NeedSplit) {
1277 SplitBlockBeforeInstr(MI);
Bob Wilsond6985d52009-05-12 17:35:29 +00001278 // No need for the branch to the next block. We're adding an unconditional
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 // branch to the destination.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001280 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 BBSizes[MBB->getNumber()] -= delta;
1282 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1283 AdjustBBOffsetsAfter(SplitBB, -delta);
1284 MBB->back().eraseFromParent();
1285 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1286 }
1287 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilsonec92b492009-05-12 17:09:30 +00001288
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 DOUT << " Insert B to BB#" << DestBB->getNumber()
1290 << " also invert condition and change dest. to BB#"
1291 << NextBB->getNumber() << "\n";
1292
1293 // Insert a new conditional branch and a new unconditional branch.
1294 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001295 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1296 TII->get(MI->getOpcode()))
1297 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 Br.MI = &MBB->back();
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001299 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesene8a10c42009-02-13 02:25:56 +00001300 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001301 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1303 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1304
1305 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001306 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 MI->eraseFromParent();
1308
1309 // The net size change is an addition of one unconditional branch.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001310 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 AdjustBBOffsetsAfter(MBB, delta);
1312 return true;
1313}
1314
1315/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1316/// LR / restores LR to pc.
1317bool ARMConstantIslands::UndoLRSpillRestore() {
1318 bool MadeChange = false;
1319 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1320 MachineInstr *MI = PushPopMIs[i];
1321 if (MI->getOpcode() == ARM::tPOP_RET &&
1322 MI->getOperand(0).getReg() == ARM::PC &&
1323 MI->getNumExplicitOperands() == 1) {
Dale Johannesene8a10c42009-02-13 02:25:56 +00001324 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 MI->eraseFromParent();
1326 MadeChange = true;
1327 }
1328 }
1329 return MadeChange;
1330}