blob: f29247ef0cdee7f2d57f94f525762ea363eef9f8 [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"
Evan Cheng1b2b3e22009-07-29 02:18:14 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
33using namespace llvm;
34
Evan Chenga441c1a2009-08-14 00:32:16 +000035STATISTIC(NumCPEs, "Number of constpool entries");
36STATISTIC(NumSplit, "Number of uncond branches inserted");
37STATISTIC(NumCBrFixed, "Number of cond branches fixed");
38STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
39STATISTIC(NumTBs, "Number of table branches generated");
40STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
Evan Chengf7b61a12009-08-14 18:31:44 +000041STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042
43namespace {
44 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
45 /// requires constant pool entries to be scattered among the instructions
46 /// inside a function. To do this, it completely ignores the normal LLVM
47 /// constant pool; instead, it places constants wherever it feels like with
48 /// special instructions.
49 ///
50 /// The terminology used in this pass includes:
51 /// Islands - Clumps of constants placed in the function.
52 /// Water - Potential places where an island could be formed.
53 /// CPE - A constant pool entry that has been placed somewhere, which
54 /// tracks a list of users.
55 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
57 /// by MBB Number. The two-byte pads required for Thumb alignment are
58 /// counted as part of the following block (i.e., the offset and size for
59 /// a padded block will both be ==2 mod 4).
60 std::vector<unsigned> BBSizes;
Bob Wilsonec92b492009-05-12 17:09:30 +000061
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
63 /// The two-byte pads required for Thumb alignment are counted as part of
64 /// the following block.
65 std::vector<unsigned> BBOffsets;
66
67 /// WaterList - A sorted list of basic blocks where islands could be placed
68 /// (i.e. blocks that don't fall through to the following block, due
69 /// to a return, unreachable, or unconditional branch).
70 std::vector<MachineBasicBlock*> WaterList;
71
72 /// CPUser - One user of a constant pool, keeping the machine instruction
73 /// pointer, the constant pool being referenced, and the max displacement
74 /// allowed from the instruction to the CP.
75 struct CPUser {
76 MachineInstr *MI;
77 MachineInstr *CPEMI;
78 unsigned MaxDisp;
Evan Chengbf2498c2009-07-21 23:56:01 +000079 bool NegOk;
Evan Chengf6e7e692009-07-23 18:27:47 +000080 bool IsSoImm;
81 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
82 bool neg, bool soimm)
83 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 };
Bob Wilsonec92b492009-05-12 17:09:30 +000085
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 /// CPUsers - Keep track of all of the machine instructions that use various
87 /// constant pools and their max displacement.
88 std::vector<CPUser> CPUsers;
Bob Wilsonec92b492009-05-12 17:09:30 +000089
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 /// CPEntry - One per constant pool entry, keeping the machine instruction
91 /// pointer, the constpool index, and the number of CPUser's which
92 /// reference this entry.
93 struct CPEntry {
94 MachineInstr *CPEMI;
95 unsigned CPI;
96 unsigned RefCount;
97 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
98 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
99 };
100
101 /// CPEntries - Keep track of all of the constant pool entry machine
102 /// instructions. For each original constpool index (i.e. those that
103 /// existed upon entry to this pass), it keeps a vector of entries.
104 /// Original elements are cloned as we go along; the clones are
105 /// put in the vector of the original element, but have distinct CPIs.
106 std::vector<std::vector<CPEntry> > CPEntries;
Bob Wilsonec92b492009-05-12 17:09:30 +0000107
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 /// ImmBranch - One per immediate branch, keeping the machine instruction
109 /// pointer, conditional or unconditional, the max displacement,
110 /// and (if isCond is true) the corresponding unconditional branch
111 /// opcode.
112 struct ImmBranch {
113 MachineInstr *MI;
114 unsigned MaxDisp : 31;
115 bool isCond : 1;
116 int UncondBr;
117 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
118 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
119 };
120
121 /// ImmBranches - Keep track of all the immediate branch instructions.
122 ///
123 std::vector<ImmBranch> ImmBranches;
124
125 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
126 ///
127 SmallVector<MachineInstr*, 4> PushPopMIs;
128
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000129 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
130 SmallVector<MachineInstr*, 4> T2JumpTables;
131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 /// HasFarJump - True if any far jump instruction has been emitted during
133 /// the branch fix up pass.
134 bool HasFarJump;
135
136 const TargetInstrInfo *TII;
Evan Cheng04f40fa2009-08-01 06:13:52 +0000137 const ARMSubtarget *STI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 ARMFunctionInfo *AFI;
139 bool isThumb;
Evan Chengf6e7e692009-07-23 18:27:47 +0000140 bool isThumb1;
David Goodwinf6154702009-06-30 18:04:13 +0000141 bool isThumb2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142 public:
143 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +0000144 ARMConstantIslands() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000146 virtual bool runOnMachineFunction(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147
148 virtual const char *getPassName() const {
149 return "ARM constant island placement and branch shortening pass";
150 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000151
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 private:
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000153 void DoInitialPlacement(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 std::vector<MachineInstr*> &CPEMIs);
155 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000156 void InitialFunctionScan(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 const std::vector<MachineInstr*> &CPEMIs);
158 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
159 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
160 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
161 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
162 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
Bob Wilsonec92b492009-05-12 17:09:30 +0000163 bool LookForWater(CPUser&U, unsigned UserOffset,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164 MachineBasicBlock** NewMBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000165 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 std::vector<MachineBasicBlock*>::iterator IP);
167 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
168 MachineBasicBlock** NewMBB);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000169 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 void RemoveDeadCPEMI(MachineInstr *CPEMI);
171 bool RemoveUnusedCPEntries();
Bob Wilsonec92b492009-05-12 17:09:30 +0000172 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000173 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
174 bool DoDump = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
176 CPUser &U);
177 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000178 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000180 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
181 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
182 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 bool UndoLRSpillRestore();
Evan Chenga441c1a2009-08-14 00:32:16 +0000184 bool OptimizeThumb2Instructions(MachineFunction &MF);
185 bool OptimizeThumb2Branches(MachineFunction &MF);
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000186 bool OptimizeThumb2JumpTables(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187
188 unsigned GetOffsetOf(MachineInstr *MI) const;
189 void dumpBBs();
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000190 void verify(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 };
192 char ARMConstantIslands::ID = 0;
193}
194
195/// verify - check BBOffsets, BBSizes, alignment of islands
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000196void ARMConstantIslands::verify(MachineFunction &MF) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 assert(BBOffsets.size() == BBSizes.size());
198 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
199 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
Evan Chengf6e7e692009-07-23 18:27:47 +0000200 if (!isThumb)
201 return;
202#ifndef NDEBUG
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000203 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Evan Chengf6e7e692009-07-23 18:27:47 +0000204 MBBI != E; ++MBBI) {
205 MachineBasicBlock *MBB = MBBI;
206 if (!MBB->empty() &&
207 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
208 unsigned MBBId = MBB->getNumber();
209 assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
210 (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 }
212 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000213#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214}
215
216/// print block size and offset information - debugging
217void ARMConstantIslands::dumpBBs() {
218 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000219 DOUT << "block " << J << " offset " << BBOffsets[J] <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 " size " << BBSizes[J] << "\n";
221 }
222}
223
224/// createARMConstantIslandPass - returns an instance of the constpool
225/// island pass.
226FunctionPass *llvm::createARMConstantIslandPass() {
227 return new ARMConstantIslands();
228}
229
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000230bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
231 MachineConstantPool &MCP = *MF.getConstantPool();
Bob Wilsonec92b492009-05-12 17:09:30 +0000232
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000233 TII = MF.getTarget().getInstrInfo();
234 AFI = MF.getInfo<ARMFunctionInfo>();
Evan Cheng04f40fa2009-08-01 06:13:52 +0000235 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
236
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 isThumb = AFI->isThumbFunction();
Evan Chengf6e7e692009-07-23 18:27:47 +0000238 isThumb1 = AFI->isThumb1OnlyFunction();
David Goodwinf6154702009-06-30 18:04:13 +0000239 isThumb2 = AFI->isThumb2Function();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240
241 HasFarJump = false;
242
243 // Renumber all of the machine basic blocks in the function, guaranteeing that
244 // the numbers agree with the position of the block in the function.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000245 MF.RenumberBlocks();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246
Evan Chengb6a03382009-07-31 18:28:05 +0000247 // Thumb1 functions containing constant pools get 4-byte alignment.
Evan Chengf6e7e692009-07-23 18:27:47 +0000248 // This is so we can keep exact track of where the alignment padding goes.
249
Evan Chengb6a03382009-07-31 18:28:05 +0000250 // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
Evan Chengf6e7e692009-07-23 18:27:47 +0000251 // aligned.
252 AFI->setAlign(isThumb1 ? 1U : 2U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253
254 // Perform the initial placement of the constant pool entries. To start with,
255 // we put them all at the end of the function.
256 std::vector<MachineInstr*> CPEMIs;
257 if (!MCP.isEmpty()) {
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000258 DoInitialPlacement(MF, CPEMIs);
Evan Chengf6e7e692009-07-23 18:27:47 +0000259 if (isThumb1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 AFI->setAlign(2U);
261 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000262
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 /// The next UID to take is the first unused one.
Evan Chengd3c573a2008-11-08 00:51:41 +0000264 AFI->initConstPoolEntryUId(CPEMIs.size());
Bob Wilsonec92b492009-05-12 17:09:30 +0000265
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 // Do the initial scan of the function, building up information about the
267 // sizes of each block, the location of all the water, and finding all of the
268 // constant pool users.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000269 InitialFunctionScan(MF, CPEMIs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 CPEMIs.clear();
Bob Wilsonec92b492009-05-12 17:09:30 +0000271
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 /// Remove dead constant pool entries.
273 RemoveUnusedCPEntries();
274
275 // Iteratively place constant pool entries and fix up branches until there
276 // is no change.
277 bool MadeChange = false;
Evan Cheng3c05d132009-08-07 07:35:21 +0000278 unsigned NoCPIters = 0, NoBRIters = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 while (true) {
Evan Cheng3c05d132009-08-07 07:35:21 +0000280 bool CPChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Cheng3c05d132009-08-07 07:35:21 +0000282 CPChange |= HandleConstantPoolUser(MF, i);
283 if (CPChange && ++NoCPIters > 30)
284 llvm_unreachable("Constant Island pass failed to converge!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 DEBUG(dumpBBs());
Evan Cheng3c05d132009-08-07 07:35:21 +0000286
287 bool BRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Cheng3c05d132009-08-07 07:35:21 +0000289 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
290 if (BRChange && ++NoBRIters > 30)
291 llvm_unreachable("Branch Fix Up pass failed to converge!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 DEBUG(dumpBBs());
Evan Cheng3c05d132009-08-07 07:35:21 +0000293
294 if (!CPChange && !BRChange)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 break;
296 MadeChange = true;
297 }
298
Evan Chenga441c1a2009-08-14 00:32:16 +0000299 // Shrink 32-bit Thumb2 branch, load, and store instructions.
300 if (isThumb2)
301 MadeChange |= OptimizeThumb2Instructions(MF);
Evan Cheng04f40fa2009-08-01 06:13:52 +0000302
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 // After a while, this might be made debug-only, but it is not expensive.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000304 verify(MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305
306 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
307 // Undo the spill / restore of LR if possible.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000308 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 MadeChange |= UndoLRSpillRestore();
310
311 BBSizes.clear();
312 BBOffsets.clear();
313 WaterList.clear();
314 CPUsers.clear();
315 CPEntries.clear();
316 ImmBranches.clear();
317 PushPopMIs.clear();
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000318 T2JumpTables.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319
320 return MadeChange;
321}
322
323/// DoInitialPlacement - Perform the initial placement of the constant pool
324/// entries. To start with, we put them all at the end of the function.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000325void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
Bob Wilsonec92b492009-05-12 17:09:30 +0000326 std::vector<MachineInstr*> &CPEMIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 // Create the basic block to hold the CPE's.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000328 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
329 MF.push_back(BB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000330
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 // Add all of the constants from the constant pool to the end block, use an
332 // identity mapping of CPI's to CPE's.
333 const std::vector<MachineConstantPoolEntry> &CPs =
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000334 MF.getConstantPool()->getConstants();
Bob Wilsonec92b492009-05-12 17:09:30 +0000335
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000336 const TargetData &TD = *MF.getTarget().getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000338 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
340 // we would have to pad them out or something so that instructions stay
341 // aligned.
342 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
343 MachineInstr *CPEMI =
Dale Johannesene8a10c42009-02-13 02:25:56 +0000344 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 .addImm(i).addConstantPoolIndex(i).addImm(Size);
346 CPEMIs.push_back(CPEMI);
347
348 // Add a new CPEntry, but no corresponding CPUser yet.
349 std::vector<CPEntry> CPEs;
350 CPEs.push_back(CPEntry(CPEMI, i));
351 CPEntries.push_back(CPEs);
352 NumCPEs++;
353 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
354 }
355}
356
357/// BBHasFallthrough - Return true if the specified basic block can fallthrough
358/// into the block immediately after it.
359static bool BBHasFallthrough(MachineBasicBlock *MBB) {
360 // Get the next machine basic block in the function.
361 MachineFunction::iterator MBBI = MBB;
362 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
363 return false;
Bob Wilsonec92b492009-05-12 17:09:30 +0000364
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 MachineBasicBlock *NextBB = next(MBBI);
366 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
367 E = MBB->succ_end(); I != E; ++I)
368 if (*I == NextBB)
369 return true;
Bob Wilsonec92b492009-05-12 17:09:30 +0000370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371 return false;
372}
373
374/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
375/// look up the corresponding CPEntry.
376ARMConstantIslands::CPEntry
377*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
378 const MachineInstr *CPEMI) {
379 std::vector<CPEntry> &CPEs = CPEntries[CPI];
380 // Number of entries per constpool index should be small, just do a
381 // linear search.
382 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
383 if (CPEs[i].CPEMI == CPEMI)
384 return &CPEs[i];
385 }
386 return NULL;
387}
388
389/// InitialFunctionScan - Do the initial scan of the function, building up
390/// information about the sizes of each block, the location of all the water,
391/// and finding all of the constant pool users.
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000392void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 const std::vector<MachineInstr*> &CPEMIs) {
394 unsigned Offset = 0;
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000395 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 MBBI != E; ++MBBI) {
397 MachineBasicBlock &MBB = *MBBI;
Bob Wilsonec92b492009-05-12 17:09:30 +0000398
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 // If this block doesn't fall through into the next MBB, then this is
400 // 'water' that a constant pool island could be placed.
401 if (!BBHasFallthrough(&MBB))
402 WaterList.push_back(&MBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000403
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 unsigned MBBSize = 0;
405 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
406 I != E; ++I) {
407 // Add instruction size to MBBSize.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000408 MBBSize += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409
410 int Opc = I->getOpcode();
Chris Lattner5b930372008-01-07 07:27:27 +0000411 if (I->getDesc().isBranch()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 bool isCond = false;
413 unsigned Bits = 0;
414 unsigned Scale = 1;
415 int UOpc = Opc;
416 switch (Opc) {
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000417 default:
418 continue; // Ignore other JT branches
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 case ARM::tBR_JTr:
Evan Cheng6e2ebc92009-07-25 00:33:29 +0000420 // A Thumb1 table jump may involve padding; for the offsets to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 // be right, functions containing these must be 4-byte aligned.
422 AFI->setAlign(2U);
423 if ((Offset+MBBSize)%4 != 0)
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000424 // FIXME: Add a pseudo ALIGN instruction instead.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 MBBSize += 2; // padding
426 continue; // Does not get an entry in ImmBranches
Evan Cheng1b2b3e22009-07-29 02:18:14 +0000427 case ARM::t2BR_JT:
428 T2JumpTables.push_back(I);
429 continue; // Does not get an entry in ImmBranches
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 case ARM::Bcc:
431 isCond = true;
432 UOpc = ARM::B;
433 // Fallthrough
434 case ARM::B:
435 Bits = 24;
436 Scale = 4;
437 break;
438 case ARM::tBcc:
439 isCond = true;
440 UOpc = ARM::tB;
441 Bits = 8;
442 Scale = 2;
443 break;
444 case ARM::tB:
445 Bits = 11;
446 Scale = 2;
447 break;
David Goodwinf6154702009-06-30 18:04:13 +0000448 case ARM::t2Bcc:
449 isCond = true;
450 UOpc = ARM::t2B;
451 Bits = 20;
452 Scale = 2;
453 break;
454 case ARM::t2B:
455 Bits = 24;
456 Scale = 2;
457 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 }
459
460 // Record this immediate branch.
461 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
462 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
463 }
464
465 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
466 PushPopMIs.push_back(I);
467
Evan Chengf6e7e692009-07-23 18:27:47 +0000468 if (Opc == ARM::CONSTPOOL_ENTRY)
469 continue;
470
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 // Scan the instructions for constant pool operands.
472 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000473 if (I->getOperand(op).isCPI()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 // We found one. The addressing mode tells us the max displacement
475 // from the PC that this instruction permits.
Bob Wilsonec92b492009-05-12 17:09:30 +0000476
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 // Basic size info comes from the TSFlags field.
478 unsigned Bits = 0;
479 unsigned Scale = 1;
Evan Chengbf2498c2009-07-21 23:56:01 +0000480 bool NegOk = false;
Evan Chengf6e7e692009-07-23 18:27:47 +0000481 bool IsSoImm = false;
482
483 switch (Opc) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000484 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000485 llvm_unreachable("Unknown addressing mode for CP reference!");
Evan Chengf6e7e692009-07-23 18:27:47 +0000486 break;
487
488 // Taking the address of a CP entry.
489 case ARM::LEApcrel:
490 // This takes a SoImm, which is 8 bit immediate rotated. We'll
491 // pretend the maximum offset is 255 * 4. Since each instruction
492 // 4 byte wide, this is always correct. We'llc heck for other
493 // displacements that fits in a SoImm as well.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494 Bits = 8;
Evan Chengf6e7e692009-07-23 18:27:47 +0000495 Scale = 4;
496 NegOk = true;
497 IsSoImm = true;
498 break;
499 case ARM::t2LEApcrel:
500 Bits = 12;
Evan Chengbf2498c2009-07-21 23:56:01 +0000501 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000503 case ARM::tLEApcrel:
504 Bits = 8;
505 Scale = 4;
506 break;
507
508 case ARM::LDR:
509 case ARM::LDRcp:
510 case ARM::t2LDRpci:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 Bits = 12; // +-offset_12
Evan Chengbf2498c2009-07-21 23:56:01 +0000512 NegOk = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000514
515 case ARM::tLDRpci:
516 case ARM::tLDRcp:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 Bits = 8;
518 Scale = 4; // +(offset_8*4)
519 break;
Evan Chengf6e7e692009-07-23 18:27:47 +0000520
521 case ARM::FLDD:
522 case ARM::FLDS:
523 Bits = 8;
524 Scale = 4; // +-(offset_8*4)
525 NegOk = true;
Evan Cheng532cdc52009-06-29 07:51:04 +0000526 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 }
528
529 // Remember that this is a user of a CP entry.
Chris Lattner6017d482007-12-30 23:10:15 +0000530 unsigned CPI = I->getOperand(op).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 MachineInstr *CPEMI = CPEMIs[CPI];
Evan Chengf7b61a12009-08-14 18:31:44 +0000532 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
Evan Chengf6e7e692009-07-23 18:27:47 +0000533 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534
535 // Increment corresponding CPEntry reference count.
536 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
537 assert(CPE && "Cannot find a corresponding CPEntry!");
538 CPE->RefCount++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000539
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 // Instructions can only use one CP entry, don't bother scanning the
541 // rest of the operands.
542 break;
543 }
544 }
545
546 // In thumb mode, if this block is a constpool island, we may need padding
547 // so it's aligned on 4 byte boundary.
548 if (isThumb &&
549 !MBB.empty() &&
550 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
551 (Offset%4) != 0)
552 MBBSize += 2;
553
554 BBSizes.push_back(MBBSize);
555 BBOffsets.push_back(Offset);
556 Offset += MBBSize;
557 }
558}
559
560/// GetOffsetOf - Return the current offset of the specified machine instruction
561/// from the start of the function. This offset changes as stuff is moved
562/// around inside the function.
563unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
564 MachineBasicBlock *MBB = MI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000565
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 // The offset is composed of two things: the sum of the sizes of all MBB's
567 // before this instruction's block, and the offset from the start of the block
568 // it is in.
569 unsigned Offset = BBOffsets[MBB->getNumber()];
570
571 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
572 // alignment padding, and compensate if so.
Bob Wilsonec92b492009-05-12 17:09:30 +0000573 if (isThumb &&
574 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 Offset%4 != 0)
576 Offset += 2;
577
578 // Sum instructions before MI in MBB.
579 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
580 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
581 if (&*I == MI) return Offset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000582 Offset += TII->GetInstSizeInBytes(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 }
584}
585
586/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
587/// ID.
588static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
589 const MachineBasicBlock *RHS) {
590 return LHS->getNumber() < RHS->getNumber();
591}
592
593/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
594/// machine function, it upsets all of the block numbers. Renumber the blocks
595/// and update the arrays that parallel this numbering.
596void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
597 // Renumber the MBB's to keep them consequtive.
598 NewBB->getParent()->RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000599
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 // Insert a size into BBSizes to align it properly with the (newly
601 // renumbered) block numbers.
602 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
603
604 // Likewise for BBOffsets.
605 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000606
607 // Next, update WaterList. Specifically, we need to add NewMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 // available water after it.
609 std::vector<MachineBasicBlock*>::iterator IP =
610 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
611 CompareMBBNumbers);
612 WaterList.insert(IP, NewBB);
613}
614
615
616/// Split the basic block containing MI into two blocks, which are joined by
617/// an unconditional branch. Update datastructures and renumber blocks to
618/// account for this change and returns the newly created block.
619MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
620 MachineBasicBlock *OrigBB = MI->getParent();
Dan Gohman221a4372008-07-07 23:14:23 +0000621 MachineFunction &MF = *OrigBB->getParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622
623 // Create a new MBB for the code after the OrigBB.
Bob Wilsonec92b492009-05-12 17:09:30 +0000624 MachineBasicBlock *NewBB =
625 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
Dan Gohman221a4372008-07-07 23:14:23 +0000627 MF.insert(MBBI, NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000628
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 // Splice the instructions starting with MI over to NewBB.
630 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
Bob Wilsonec92b492009-05-12 17:09:30 +0000631
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 // Add an unconditional branch from OrigBB to NewBB.
633 // Note the new unconditional branch is not being recorded.
Dale Johannesene8a10c42009-02-13 02:25:56 +0000634 // There doesn't seem to be meaningful DebugInfo available; this doesn't
635 // correspond to anything in the source.
Evan Cheng451192e2009-07-07 01:16:41 +0000636 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
637 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 NumSplit++;
Bob Wilsonec92b492009-05-12 17:09:30 +0000639
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 // Update the CFG. All succs of OrigBB are now succs of NewBB.
641 while (!OrigBB->succ_empty()) {
642 MachineBasicBlock *Succ = *OrigBB->succ_begin();
643 OrigBB->removeSuccessor(Succ);
644 NewBB->addSuccessor(Succ);
Bob Wilsonec92b492009-05-12 17:09:30 +0000645
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 // This pass should be run after register allocation, so there should be no
647 // PHI nodes to update.
648 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
649 && "PHI nodes should be eliminated by now!");
650 }
Bob Wilsonec92b492009-05-12 17:09:30 +0000651
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 // OrigBB branches to NewBB.
653 OrigBB->addSuccessor(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000654
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 // Update internal data structures to account for the newly inserted MBB.
656 // This is almost the same as UpdateForInsertedWaterBlock, except that
657 // the Water goes after OrigBB, not NewBB.
Dan Gohman221a4372008-07-07 23:14:23 +0000658 MF.RenumberBlocks(NewBB);
Bob Wilsonec92b492009-05-12 17:09:30 +0000659
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 // Insert a size into BBSizes to align it properly with the (newly
661 // renumbered) block numbers.
662 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
Bob Wilsonec92b492009-05-12 17:09:30 +0000663
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 // Likewise for BBOffsets.
665 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
666
Bob Wilsonec92b492009-05-12 17:09:30 +0000667 // Next, update WaterList. Specifically, we need to add OrigMBB as having
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 // available water after it (but not if it's already there, which happens
669 // when splitting before a conditional branch that is followed by an
670 // unconditional branch - in that case we want to insert NewBB).
671 std::vector<MachineBasicBlock*>::iterator IP =
672 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
673 CompareMBBNumbers);
674 MachineBasicBlock* WaterBB = *IP;
675 if (WaterBB == OrigBB)
676 WaterList.insert(next(IP), NewBB);
677 else
678 WaterList.insert(IP, OrigBB);
679
680 // Figure out how large the first NewMBB is. (It cannot
681 // contain a constpool_entry or tablejump.)
682 unsigned NewBBSize = 0;
683 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
684 I != E; ++I)
Nicolas Geoffraycb162a02008-04-16 20:10:13 +0000685 NewBBSize += TII->GetInstSizeInBytes(I);
Bob Wilsonec92b492009-05-12 17:09:30 +0000686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 unsigned OrigBBI = OrigBB->getNumber();
688 unsigned NewBBI = NewBB->getNumber();
689 // Set the size of NewBB in BBSizes.
690 BBSizes[NewBBI] = NewBBSize;
Bob Wilsonec92b492009-05-12 17:09:30 +0000691
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 // We removed instructions from UserMBB, subtract that off from its size.
693 // Add 2 or 4 to the block to count the unconditional branch we added to it.
Evan Cheng04f40fa2009-08-01 06:13:52 +0000694 int delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 BBSizes[OrigBBI] -= NewBBSize - delta;
696
697 // ...and adjust BBOffsets for NewBB accordingly.
698 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
699
700 // All BBOffsets following these blocks must be modified.
701 AdjustBBOffsetsAfter(NewBB, delta);
702
703 return NewBB;
704}
705
706/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
Bob Wilsonec92b492009-05-12 17:09:30 +0000707/// reference) is within MaxDisp of TrialOffset (a proposed location of a
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708/// constant pool entry).
Bob Wilsonec92b492009-05-12 17:09:30 +0000709bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +0000710 unsigned TrialOffset, unsigned MaxDisp,
711 bool NegativeOK, bool IsSoImm) {
Bob Wilsonec92b492009-05-12 17:09:30 +0000712 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
713 // purposes of the displacement computation; compensate for that here.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 // Effectively, the valid range of displacements is 2 bytes smaller for such
715 // references.
Evan Chengf7b61a12009-08-14 18:31:44 +0000716 unsigned TotalAdj = 0;
717 if (isThumb && UserOffset%4 !=0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 UserOffset -= 2;
Evan Chengf7b61a12009-08-14 18:31:44 +0000719 TotalAdj = 2;
720 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 // CPEs will be rounded up to a multiple of 4.
Evan Chengf7b61a12009-08-14 18:31:44 +0000722 if (isThumb && TrialOffset%4 != 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 TrialOffset += 2;
Evan Chengf7b61a12009-08-14 18:31:44 +0000724 TotalAdj += 2;
725 }
726
727 // In Thumb2 mode, later branch adjustments can shift instructions up and
728 // cause alignment change. In the worst case scenario this can cause the
729 // user's effective address to be subtracted by 2 and the CPE's address to
730 // be plus 2.
731 if (isThumb2 && TotalAdj != 4)
732 MaxDisp -= (4 - TotalAdj);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733
734 if (UserOffset <= TrialOffset) {
735 // User before the Trial.
Evan Chengf6e7e692009-07-23 18:27:47 +0000736 if (TrialOffset - UserOffset <= MaxDisp)
737 return true;
Evan Cheng4e502402009-07-24 19:31:03 +0000738 // FIXME: Make use full range of soimm values.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 } else if (NegativeOK) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000740 if (UserOffset - TrialOffset <= MaxDisp)
741 return true;
Evan Cheng4e502402009-07-24 19:31:03 +0000742 // FIXME: Make use full range of soimm values.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 }
744 return false;
745}
746
747/// WaterIsInRange - Returns true if a CPE placed after the specified
748/// Water (a basic block) will be in range for the specific MI.
749
750bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000751 MachineBasicBlock* Water, CPUser &U) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 unsigned MaxDisp = U.MaxDisp;
Bob Wilsonec92b492009-05-12 17:09:30 +0000753 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 BBSizes[Water->getNumber()];
755
756 // If the CPE is to be inserted before the instruction, that will raise
757 // the offset of the instruction. (Currently applies only to ARM, so
758 // no alignment compensation attempted here.)
759 if (CPEOffset < UserOffset)
760 UserOffset += U.CPEMI->getOperand(2).getImm();
761
Evan Chengf6e7e692009-07-23 18:27:47 +0000762 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763}
764
765/// CPEIsInRange - Returns true if the distance between specific MI and
766/// specific ConstPool entry instruction can fit in MI's displacement field.
767bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
Evan Chengbf2498c2009-07-21 23:56:01 +0000768 MachineInstr *CPEMI, unsigned MaxDisp,
769 bool NegOk, bool DoDump) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 unsigned CPEOffset = GetOffsetOf(CPEMI);
771 assert(CPEOffset%4 == 0 && "Misaligned CPE");
772
773 if (DoDump) {
774 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
775 << " max delta=" << MaxDisp
776 << " insn address=" << UserOffset
777 << " CPE address=" << CPEOffset
778 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
779 }
780
Evan Chengbf2498c2009-07-21 23:56:01 +0000781 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782}
783
Evan Cheng10361732009-01-28 00:53:34 +0000784#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
786/// unconditionally branches to its only successor.
787static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
788 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
789 return false;
790
791 MachineBasicBlock *Succ = *MBB->succ_begin();
792 MachineBasicBlock *Pred = *MBB->pred_begin();
793 MachineInstr *PredMI = &Pred->back();
David Goodwinf6154702009-06-30 18:04:13 +0000794 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
795 || PredMI->getOpcode() == ARM::t2B)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796 return PredMI->getOperand(0).getMBB() == Succ;
797 return false;
798}
Evan Cheng10361732009-01-28 00:53:34 +0000799#endif // NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800
Bob Wilsonec92b492009-05-12 17:09:30 +0000801void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 int delta) {
803 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
Evan Chengf6e7e692009-07-23 18:27:47 +0000804 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
805 i < e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806 BBOffsets[i] += delta;
807 // If some existing blocks have padding, adjust the padding as needed, a
808 // bit tricky. delta can be negative so don't use % on that.
Evan Chengf6e7e692009-07-23 18:27:47 +0000809 if (!isThumb)
810 continue;
811 MachineBasicBlock *MBB = MBBI;
812 if (!MBB->empty()) {
813 // Constant pool entries require padding.
814 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
Evan Cheng275468a2009-08-11 07:36:14 +0000815 unsigned OldOffset = BBOffsets[i] - delta;
816 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000817 // add new padding
818 BBSizes[i] += 2;
819 delta += 2;
Evan Cheng275468a2009-08-11 07:36:14 +0000820 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000821 // remove existing padding
Evan Cheng275468a2009-08-11 07:36:14 +0000822 BBSizes[i] -= 2;
Evan Chengf6e7e692009-07-23 18:27:47 +0000823 delta -= 2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000826 // Thumb1 jump tables require padding. They should be at the end;
827 // following unconditional branches are removed by AnalyzeBranch.
Evan Chenga609c1d2009-07-24 18:20:44 +0000828 MachineInstr *ThumbJTMI = prior(MBB->end());
Evan Cheng6e2ebc92009-07-25 00:33:29 +0000829 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
Evan Cheng275468a2009-08-11 07:36:14 +0000830 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
831 unsigned OldMIOffset = NewMIOffset - delta;
832 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000833 // remove existing padding
834 BBSizes[i] -= 2;
835 delta -= 2;
Evan Cheng275468a2009-08-11 07:36:14 +0000836 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000837 // add new padding
838 BBSizes[i] += 2;
839 delta += 2;
840 }
841 }
842 if (delta==0)
843 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000845 MBBI = next(MBBI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 }
847}
848
849/// DecrementOldEntry - find the constant pool entry with index CPI
850/// and instruction CPEMI, and decrement its refcount. If the refcount
Bob Wilsonec92b492009-05-12 17:09:30 +0000851/// becomes 0 remove the entry and instruction. Returns true if we removed
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852/// the entry, false if we didn't.
853
854bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
855 // Find the old entry. Eliminate it if it is no longer used.
856 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
857 assert(CPE && "Unexpected!");
858 if (--CPE->RefCount == 0) {
859 RemoveDeadCPEMI(CPEMI);
860 CPE->CPEMI = NULL;
861 NumCPEs--;
862 return true;
863 }
864 return false;
865}
866
867/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
868/// if not, see if an in-range clone of the CPE is in range, and if so,
869/// change the data structures so the user references the clone. Returns:
870/// 0 = no existing entry found
871/// 1 = entry found, and there were no code insertions or deletions
872/// 2 = entry found, and there were code insertions or deletions
873int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
874{
875 MachineInstr *UserMI = U.MI;
876 MachineInstr *CPEMI = U.CPEMI;
877
878 // Check to see if the CPE is already in-range.
Evan Chengbf2498c2009-07-21 23:56:01 +0000879 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 DOUT << "In range\n";
881 return 1;
882 }
883
884 // No. Look for previously created clones of the CPE that are in range.
Chris Lattner6017d482007-12-30 23:10:15 +0000885 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886 std::vector<CPEntry> &CPEs = CPEntries[CPI];
887 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
888 // We already tried this one
889 if (CPEs[i].CPEMI == CPEMI)
890 continue;
891 // Removing CPEs can leave empty entries, skip
892 if (CPEs[i].CPEMI == NULL)
893 continue;
Evan Chengbf2498c2009-07-21 23:56:01 +0000894 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000895 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
896 // Point the CPUser node to the replacement
897 U.CPEMI = CPEs[i].CPEMI;
898 // Change the CPI in the instruction operand to refer to the clone.
899 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000900 if (UserMI->getOperand(j).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +0000901 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 break;
903 }
904 // Adjust the refcount of the clone...
905 CPEs[i].RefCount++;
906 // ...and the original. If we didn't remove the old entry, none of the
907 // addresses changed, so we don't need another pass.
908 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
909 }
910 }
911 return 0;
912}
913
914/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
915/// the specific unconditional branch instruction.
916static inline unsigned getUnconditionalBrDisp(int Opc) {
David Goodwinf6154702009-06-30 18:04:13 +0000917 switch (Opc) {
918 case ARM::tB:
919 return ((1<<10)-1)*2;
920 case ARM::t2B:
921 return ((1<<23)-1)*2;
922 default:
923 break;
924 }
Jim Grosbach770d7182009-08-11 15:33:49 +0000925
David Goodwinf6154702009-06-30 18:04:13 +0000926 return ((1<<23)-1)*4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927}
928
929/// AcceptWater - Small amount of common code factored out of the following.
930
Bob Wilsonec92b492009-05-12 17:09:30 +0000931MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 std::vector<MachineBasicBlock*>::iterator IP) {
933 DOUT << "found water in range\n";
934 // Remove the original WaterList entry; we want subsequent
935 // insertions in this vicinity to go after the one we're
936 // about to insert. This considerably reduces the number
937 // of times we have to move the same CPE more than once.
938 WaterList.erase(IP);
939 // CPE goes before following block (NewMBB).
940 return next(MachineFunction::iterator(WaterBB));
941}
942
943/// LookForWater - look for an existing entry in the WaterList in which
944/// we can place the CPE referenced from U so it's within range of U's MI.
945/// Returns true if found, false if not. If it returns true, *NewMBB
946/// is set to the WaterList entry.
Evan Chengf6e7e692009-07-23 18:27:47 +0000947/// For ARM, we prefer the water that's farthest away. For Thumb, prefer
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948/// water that will not introduce padding to water that will; within each
949/// group, prefer the water that's farthest away.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000950bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
951 MachineBasicBlock** NewMBB) {
952 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
953 MachineBasicBlock* WaterBBThatWouldPad = NULL;
954 if (!WaterList.empty()) {
955 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
Evan Chengf6e7e692009-07-23 18:27:47 +0000956 B = WaterList.begin();; --IP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 MachineBasicBlock* WaterBB = *IP;
958 if (WaterIsInRange(UserOffset, WaterBB, U)) {
Evan Chengf6e7e692009-07-23 18:27:47 +0000959 unsigned WBBId = WaterBB->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 if (isThumb &&
Evan Chengf6e7e692009-07-23 18:27:47 +0000961 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 // This is valid Water, but would introduce padding. Remember
963 // it in case we don't find any Water that doesn't do this.
964 if (!WaterBBThatWouldPad) {
965 WaterBBThatWouldPad = WaterBB;
966 IPThatWouldPad = IP;
967 }
968 } else {
969 *NewMBB = AcceptWater(WaterBB, IP);
970 return true;
971 }
Evan Chengf6e7e692009-07-23 18:27:47 +0000972 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 if (IP == B)
974 break;
975 }
976 }
977 if (isThumb && WaterBBThatWouldPad) {
978 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
979 return true;
980 }
981 return false;
982}
983
Bob Wilsonec92b492009-05-12 17:09:30 +0000984/// CreateNewWater - No existing WaterList entry will work for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
986/// block is used if in range, and the conditional branch munged so control
987/// flow is correct. Otherwise the block is split to create a hole with an
988/// unconditional branch around it. In either case *NewMBB is set to a
989/// block following which the new island can be inserted (the WaterList
990/// is not adjusted).
991
Bob Wilsonec92b492009-05-12 17:09:30 +0000992void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 unsigned UserOffset, MachineBasicBlock** NewMBB) {
994 CPUser &U = CPUsers[CPUserIndex];
995 MachineInstr *UserMI = U.MI;
996 MachineInstr *CPEMI = U.CPEMI;
997 MachineBasicBlock *UserMBB = UserMI->getParent();
Bob Wilsonec92b492009-05-12 17:09:30 +0000998 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 BBSizes[UserMBB->getNumber()];
1000 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1001
1002 // If the use is at the end of the block, or the end of the block
1003 // is within range, make new water there. (The addition below is
Evan Chengf6e7e692009-07-23 18:27:47 +00001004 // for the unconditional branch we will be adding: 4 bytes on ARM + Thumb2,
1005 // 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 // inside OffsetIsInRange.
Bob Wilsonec92b492009-05-12 17:09:30 +00001007 // If the block ends in an unconditional branch already, it is water,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008 // and is known to be out of range, so we'll always be adding a branch.)
1009 if (&UserMBB->back() == UserMI ||
Evan Chengf6e7e692009-07-23 18:27:47 +00001010 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1011 U.MaxDisp, U.NegOk, U.IsSoImm)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 DOUT << "Split at end of block\n";
1013 if (&UserMBB->back() == UserMI)
1014 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1015 *NewMBB = next(MachineFunction::iterator(UserMBB));
1016 // Add an unconditional branch from UserMBB to fallthrough block.
1017 // Record it for branch lengthening; this new branch will not get out of
1018 // range, but if the preceding conditional branch is out of range, the
1019 // targets will be exchanged, and the altered branch may be out of
1020 // range, so the machinery has to know about it.
David Goodwinf6154702009-06-30 18:04:13 +00001021 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
Dale Johannesene8a10c42009-02-13 02:25:56 +00001022 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1023 TII->get(UncondBr)).addMBB(*NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
Bob Wilsonec92b492009-05-12 17:09:30 +00001025 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 MaxDisp, false, UncondBr));
Evan Chengf6e7e692009-07-23 18:27:47 +00001027 int delta = isThumb1 ? 2 : 4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 BBSizes[UserMBB->getNumber()] += delta;
1029 AdjustBBOffsetsAfter(UserMBB, delta);
1030 } else {
1031 // What a big block. Find a place within the block to split it.
Evan Chengf6e7e692009-07-23 18:27:47 +00001032 // This is a little tricky on Thumb1 since instructions are 2 bytes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 // and constant pool entries are 4 bytes: if instruction I references
1034 // island CPE, and instruction I+1 references CPE', it will
1035 // not work well to put CPE as far forward as possible, since then
1036 // CPE' cannot immediately follow it (that location is 2 bytes
1037 // farther away from I+1 than CPE was from I) and we'd need to create
1038 // a new island. So, we make a first guess, then walk through the
1039 // instructions between the one currently being looked at and the
1040 // possible insertion point, and make sure any other instructions
1041 // that reference CPEs will be able to use the same island area;
1042 // if not, we back up the insertion point.
1043
1044 // The 4 in the following is for the unconditional branch we'll be
Evan Chengf6e7e692009-07-23 18:27:47 +00001045 // inserting (allows for long branch on Thumb1). Alignment of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 // island is handled inside OffsetIsInRange.
1047 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1048 // This could point off the end of the block if we've already got
1049 // constant pool entries following this block; only the last one is
1050 // in the water list. Back past any possible branches (allow for a
1051 // conditional and a maximally long unconditional).
1052 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
Bob Wilsonec92b492009-05-12 17:09:30 +00001053 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
Evan Chengf6e7e692009-07-23 18:27:47 +00001054 (isThumb1 ? 6 : 8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 unsigned EndInsertOffset = BaseInsertOffset +
1056 CPEMI->getOperand(2).getImm();
1057 MachineBasicBlock::iterator MI = UserMI;
1058 ++MI;
1059 unsigned CPUIndex = CPUserIndex+1;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001060 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061 Offset < BaseInsertOffset;
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001062 Offset += TII->GetInstSizeInBytes(MI),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063 MI = next(MI)) {
1064 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001065 CPUser &U = CPUsers[CPUIndex];
Bob Wilsonec92b492009-05-12 17:09:30 +00001066 if (!OffsetIsInRange(Offset, EndInsertOffset,
Evan Chengf6e7e692009-07-23 18:27:47 +00001067 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1068 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1069 EndInsertOffset -= (isThumb1 ? 2 : 4);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 }
1071 // This is overly conservative, as we don't account for CPEMIs
1072 // being reused within the block, but it doesn't matter much.
1073 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1074 CPUIndex++;
1075 }
1076 }
1077 DOUT << "Split in middle of big block\n";
1078 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1079 }
1080}
1081
1082/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
Bob Wilsond6985d52009-05-12 17:35:29 +00001083/// is out-of-range. If so, pick up the constant pool value and move it some
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084/// place in-range. Return true if we changed any addresses (thus must run
1085/// another pass of branch lengthening), false otherwise.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001086bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
Bob Wilsonec92b492009-05-12 17:09:30 +00001087 unsigned CPUserIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001088 CPUser &U = CPUsers[CPUserIndex];
1089 MachineInstr *UserMI = U.MI;
1090 MachineInstr *CPEMI = U.CPEMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001091 unsigned CPI = CPEMI->getOperand(1).getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 unsigned Size = CPEMI->getOperand(2).getImm();
1093 MachineBasicBlock *NewMBB;
1094 // Compute this only once, it's expensive. The 4 or 8 is the value the
Evan Chenga441c1a2009-08-14 00:32:16 +00001095 // hardware keeps in the PC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1097
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 // See if the current entry is within range, or there is a clone of it
1099 // in range.
1100 int result = LookForExistingCPEntry(U, UserOffset);
1101 if (result==1) return false;
1102 else if (result==2) return true;
1103
1104 // No existing clone of this CPE is within range.
1105 // We will be generating a new clone. Get a UID for it.
Bob Wilsond6985d52009-05-12 17:35:29 +00001106 unsigned ID = AFI->createConstPoolEntryUId();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107
1108 // Look for water where we can place this CPE. We look for the farthest one
1109 // away that will work. Forward references only for now (although later
1110 // we might find some that are backwards).
1111
1112 if (!LookForWater(U, UserOffset, &NewMBB)) {
1113 // No water found.
1114 DOUT << "No water found\n";
1115 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1116 }
1117
1118 // Okay, we know we can put an island before NewMBB now, do it!
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001119 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1120 MF.insert(NewMBB, NewIsland);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121
1122 // Update internal data structures to account for the newly inserted MBB.
1123 UpdateForInsertedWaterBlock(NewIsland);
1124
1125 // Decrement the old entry, and remove it if refcount becomes 0.
1126 DecrementOldEntry(CPI, CPEMI);
1127
1128 // Now that we have an island to add the CPE to, clone the original CPE and
1129 // add it to the island.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001130 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1131 TII->get(ARM::CONSTPOOL_ENTRY))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1133 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1134 NumCPEs++;
1135
1136 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1137 // Compensate for .align 2 in thumb mode.
Bob Wilsonec92b492009-05-12 17:09:30 +00001138 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139 Size += 2;
1140 // Increase the size of the island block to account for the new entry.
1141 BBSizes[NewIsland->getNumber()] += Size;
1142 AdjustBBOffsetsAfter(NewIsland, Size);
Bob Wilsonec92b492009-05-12 17:09:30 +00001143
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 // Finally, change the CPI in the instruction operand to be ID.
1145 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001146 if (UserMI->getOperand(i).isCPI()) {
Chris Lattner6017d482007-12-30 23:10:15 +00001147 UserMI->getOperand(i).setIndex(ID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 break;
1149 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001150
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
Bob Wilsonec92b492009-05-12 17:09:30 +00001152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 return true;
1154}
1155
1156/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1157/// sizes and offsets of impacted basic blocks.
1158void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1159 MachineBasicBlock *CPEBB = CPEMI->getParent();
1160 unsigned Size = CPEMI->getOperand(2).getImm();
1161 CPEMI->eraseFromParent();
1162 BBSizes[CPEBB->getNumber()] -= Size;
1163 // All succeeding offsets have the current size value added in, fix this.
1164 if (CPEBB->empty()) {
Evan Chengf6e7e692009-07-23 18:27:47 +00001165 // In thumb1 mode, the size of island may be padded by two to compensate for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166 // the alignment requirement. Then it will now be 2 when the block is
1167 // empty, so fix this.
1168 // All succeeding offsets have the current size value added in, fix this.
1169 if (BBSizes[CPEBB->getNumber()] != 0) {
1170 Size += BBSizes[CPEBB->getNumber()];
1171 BBSizes[CPEBB->getNumber()] = 0;
1172 }
1173 }
1174 AdjustBBOffsetsAfter(CPEBB, -Size);
1175 // An island has only one predecessor BB and one successor BB. Check if
1176 // this BB's predecessor jumps directly to this BB's successor. This
1177 // shouldn't happen currently.
1178 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1179 // FIXME: remove the empty blocks after all the work is done?
1180}
1181
1182/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1183/// are zero.
1184bool ARMConstantIslands::RemoveUnusedCPEntries() {
1185 unsigned MadeChange = false;
1186 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1187 std::vector<CPEntry> &CPEs = CPEntries[i];
1188 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1189 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1190 RemoveDeadCPEMI(CPEs[j].CPEMI);
1191 CPEs[j].CPEMI = NULL;
1192 MadeChange = true;
1193 }
1194 }
Bob Wilsonec92b492009-05-12 17:09:30 +00001195 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 return MadeChange;
1197}
1198
1199/// BBIsInRange - Returns true if the distance between specific MI and
1200/// specific BB can fit in MI's displacement field.
1201bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1202 unsigned MaxDisp) {
1203 unsigned PCAdj = isThumb ? 4 : 8;
1204 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1205 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1206
1207 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1208 << " from BB#" << MI->getParent()->getNumber()
1209 << " max delta=" << MaxDisp
1210 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1211 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1212
1213 if (BrOffset <= DestOffset) {
1214 // Branch before the Dest.
1215 if (DestOffset-BrOffset <= MaxDisp)
1216 return true;
1217 } else {
1218 if (BrOffset-DestOffset <= MaxDisp)
1219 return true;
1220 }
1221 return false;
1222}
1223
1224/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1225/// away to fit in its displacement field.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001226bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001228 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229
1230 // Check to see if the DestBB is already in-range.
1231 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1232 return false;
1233
1234 if (!Br.isCond)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001235 return FixUpUnconditionalBr(MF, Br);
1236 return FixUpConditionalBr(MF, Br);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237}
1238
1239/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1240/// too far away to fit in its displacement field. If the LR register has been
1241/// spilled in the epilogue, then we can use BL to implement a far jump.
Bob Wilsond6985d52009-05-12 17:35:29 +00001242/// Otherwise, add an intermediate branch instruction to a branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243bool
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001244ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 MachineInstr *MI = Br.MI;
1246 MachineBasicBlock *MBB = MI->getParent();
Evan Chengd6053af2009-08-07 05:45:07 +00001247 if (!isThumb1)
1248 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249
1250 // Use BL to implement far jump.
1251 Br.MaxDisp = (1 << 21) * 2;
Chris Lattner86bb02f2008-01-11 18:10:50 +00001252 MI->setDesc(TII->get(ARM::tBfar));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 BBSizes[MBB->getNumber()] += 2;
1254 AdjustBBOffsetsAfter(MBB, 2);
1255 HasFarJump = true;
1256 NumUBrFixed++;
1257
1258 DOUT << " Changed B to long jump " << *MI;
1259
1260 return true;
1261}
1262
1263/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1264/// far away to fit in its displacement field. It is converted to an inverse
1265/// conditional branch + an unconditional branch to the destination.
1266bool
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001267ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 MachineInstr *MI = Br.MI;
Chris Lattner6017d482007-12-30 23:10:15 +00001269 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270
Bob Wilsond6985d52009-05-12 17:35:29 +00001271 // Add an unconditional branch to the destination and invert the branch
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 // condition to jump over it:
1273 // blt L1
1274 // =>
1275 // bge L2
1276 // b L1
1277 // L2:
Chris Lattnera96056a2007-12-30 20:49:49 +00001278 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 CC = ARMCC::getOppositeCondition(CC);
1280 unsigned CCReg = MI->getOperand(2).getReg();
1281
1282 // If the branch is at the end of its MBB and that has a fall-through block,
1283 // direct the updated conditional branch to the fall-through block. Otherwise,
1284 // split the MBB before the next instruction.
1285 MachineBasicBlock *MBB = MI->getParent();
1286 MachineInstr *BMI = &MBB->back();
1287 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1288
1289 NumCBrFixed++;
1290 if (BMI != MI) {
Dan Gohman221a4372008-07-07 23:14:23 +00001291 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 BMI->getOpcode() == Br.UncondBr) {
Bob Wilsond6985d52009-05-12 17:35:29 +00001293 // Last MI in the BB is an unconditional branch. Can we simply invert the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 // condition and swap destinations:
1295 // beq L1
1296 // b L2
1297 // =>
1298 // bne L2
1299 // b L1
Chris Lattner6017d482007-12-30 23:10:15 +00001300 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1302 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
Chris Lattner6017d482007-12-30 23:10:15 +00001303 BMI->getOperand(0).setMBB(DestBB);
1304 MI->getOperand(0).setMBB(NewDest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 MI->getOperand(1).setImm(CC);
1306 return true;
1307 }
1308 }
1309 }
1310
1311 if (NeedSplit) {
1312 SplitBlockBeforeInstr(MI);
Bob Wilsond6985d52009-05-12 17:35:29 +00001313 // No need for the branch to the next block. We're adding an unconditional
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 // branch to the destination.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001315 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316 BBSizes[MBB->getNumber()] -= delta;
1317 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1318 AdjustBBOffsetsAfter(SplitBB, -delta);
1319 MBB->back().eraseFromParent();
1320 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1321 }
1322 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
Bob Wilsonec92b492009-05-12 17:09:30 +00001323
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 DOUT << " Insert B to BB#" << DestBB->getNumber()
1325 << " also invert condition and change dest. to BB#"
1326 << NextBB->getNumber() << "\n";
1327
1328 // Insert a new conditional branch and a new unconditional branch.
1329 // Also update the ImmBranch as well as adding a new entry for the new branch.
Dale Johannesene8a10c42009-02-13 02:25:56 +00001330 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1331 TII->get(MI->getOpcode()))
1332 .addMBB(NextBB).addImm(CC).addReg(CCReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 Br.MI = &MBB->back();
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001334 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dale Johannesene8a10c42009-02-13 02:25:56 +00001335 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001336 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1338 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1339
1340 // Remove the old conditional branch. It may or may not still be in MBB.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001341 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 MI->eraseFromParent();
1343
1344 // The net size change is an addition of one unconditional branch.
Nicolas Geoffraycb162a02008-04-16 20:10:13 +00001345 int delta = TII->GetInstSizeInBytes(&MBB->back());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346 AdjustBBOffsetsAfter(MBB, delta);
1347 return true;
1348}
1349
1350/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
Evan Cheng94958142009-08-11 21:11:32 +00001351/// LR / restores LR to pc. FIXME: This is done here because it's only possible
1352/// to do this if tBfar is not used.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353bool ARMConstantIslands::UndoLRSpillRestore() {
1354 bool MadeChange = false;
1355 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1356 MachineInstr *MI = PushPopMIs[i];
1357 if (MI->getOpcode() == ARM::tPOP_RET &&
Evan Cheng2868cf12009-08-13 06:05:07 +00001358 MI->getOperand(2).getReg() == ARM::PC &&
1359 MI->getNumExplicitOperands() == 3) {
Dale Johannesene8a10c42009-02-13 02:25:56 +00001360 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 MI->eraseFromParent();
1362 MadeChange = true;
1363 }
1364 }
1365 return MadeChange;
1366}
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001367
Evan Chenga441c1a2009-08-14 00:32:16 +00001368bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1369 bool MadeChange = false;
1370
1371 // Shrink ADR and LDR from constantpool.
1372 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1373 CPUser &U = CPUsers[i];
1374 unsigned Opcode = U.MI->getOpcode();
1375 unsigned NewOpc = 0;
1376 unsigned Scale = 1;
1377 unsigned Bits = 0;
1378 switch (Opcode) {
1379 default: break;
1380 case ARM::t2LEApcrel:
1381 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1382 NewOpc = ARM::tLEApcrel;
1383 Bits = 8;
1384 Scale = 4;
1385 }
1386 break;
1387 case ARM::t2LDRpci:
1388 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1389 NewOpc = ARM::tLDRpci;
1390 Bits = 8;
1391 Scale = 4;
1392 }
1393 break;
1394 }
1395
1396 if (!NewOpc)
1397 continue;
1398
1399 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1400 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1401 // FIXME: Check if offset is multiple of scale if scale is not 4.
1402 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1403 U.MI->setDesc(TII->get(NewOpc));
1404 MachineBasicBlock *MBB = U.MI->getParent();
1405 BBSizes[MBB->getNumber()] -= 2;
1406 AdjustBBOffsetsAfter(MBB, -2);
1407 ++NumT2CPShrunk;
1408 MadeChange = true;
1409 }
1410 }
1411
Evan Chenga441c1a2009-08-14 00:32:16 +00001412 MadeChange |= OptimizeThumb2Branches(MF);
Evan Chengf7b61a12009-08-14 18:31:44 +00001413 MadeChange |= OptimizeThumb2JumpTables(MF);
Evan Chenga441c1a2009-08-14 00:32:16 +00001414 return MadeChange;
1415}
1416
1417bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
Evan Chengf7b61a12009-08-14 18:31:44 +00001418 bool MadeChange = false;
1419
1420 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1421 ImmBranch &Br = ImmBranches[i];
1422 unsigned Opcode = Br.MI->getOpcode();
1423 unsigned NewOpc = 0;
1424 unsigned Scale = 1;
1425 unsigned Bits = 0;
1426 switch (Opcode) {
1427 default: break;
1428 case ARM::t2B:
1429 NewOpc = ARM::tB;
1430 Bits = 11;
1431 Scale = 2;
1432 break;
1433 case ARM::t2Bcc:
1434 NewOpc = ARM::tBcc;
1435 Bits = 8;
1436 Scale = 2;
1437 break;
1438 }
1439 if (!NewOpc)
1440 continue;
1441
1442 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1443 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1444 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1445 Br.MI->setDesc(TII->get(NewOpc));
1446 MachineBasicBlock *MBB = Br.MI->getParent();
1447 BBSizes[MBB->getNumber()] -= 2;
1448 AdjustBBOffsetsAfter(MBB, -2);
1449 ++NumT2BrShrunk;
1450 MadeChange = true;
1451 }
1452 }
1453
1454 return MadeChange;
Evan Chenga441c1a2009-08-14 00:32:16 +00001455}
1456
1457
1458/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1459/// jumptables when it's possible.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001460bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1461 bool MadeChange = false;
1462
1463 // FIXME: After the tables are shrunk, can we get rid some of the
1464 // constantpool tables?
1465 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1466 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1467 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1468 MachineInstr *MI = T2JumpTables[i];
1469 const TargetInstrDesc &TID = MI->getDesc();
1470 unsigned NumOps = TID.getNumOperands();
1471 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1472 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1473 unsigned JTI = JTOP.getIndex();
1474 assert(JTI < JT.size());
1475
1476 bool ByteOk = true;
1477 bool HalfWordOk = true;
1478 unsigned JTOffset = GetOffsetOf(MI) + 4;
1479 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1480 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1481 MachineBasicBlock *MBB = JTBBs[j];
1482 unsigned DstOffset = BBOffsets[MBB->getNumber()];
Evan Chenge12c92d2009-07-29 23:20:20 +00001483 // Negative offset is not ok. FIXME: We should change BB layout to make
1484 // sure all the branches are forward.
Evan Chengb6a03382009-07-31 18:28:05 +00001485 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001486 ByteOk = false;
Evan Cheng04f40fa2009-08-01 06:13:52 +00001487 unsigned TBHLimit = ((1<<16)-1)*2;
Evan Cheng04f40fa2009-08-01 06:13:52 +00001488 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001489 HalfWordOk = false;
1490 if (!ByteOk && !HalfWordOk)
1491 break;
1492 }
1493
1494 if (ByteOk || HalfWordOk) {
1495 MachineBasicBlock *MBB = MI->getParent();
1496 unsigned BaseReg = MI->getOperand(0).getReg();
1497 bool BaseRegKill = MI->getOperand(0).isKill();
1498 if (!BaseRegKill)
1499 continue;
1500 unsigned IdxReg = MI->getOperand(1).getReg();
1501 bool IdxRegKill = MI->getOperand(1).isKill();
1502 MachineBasicBlock::iterator PrevI = MI;
1503 if (PrevI == MBB->begin())
1504 continue;
1505
1506 MachineInstr *AddrMI = --PrevI;
1507 bool OptOk = true;
1508 // Examine the instruction that calculate the jumptable entry address.
1509 // If it's not the one just before the t2BR_JT, we won't delete it, then
1510 // it's not worth doing the optimization.
1511 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1512 const MachineOperand &MO = AddrMI->getOperand(k);
1513 if (!MO.isReg() || !MO.getReg())
1514 continue;
1515 if (MO.isDef() && MO.getReg() != BaseReg) {
1516 OptOk = false;
1517 break;
1518 }
1519 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1520 OptOk = false;
1521 break;
1522 }
1523 }
1524 if (!OptOk)
1525 continue;
1526
Evan Chenga441c1a2009-08-14 00:32:16 +00001527 // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1528 // to delete it as well.
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001529 MachineInstr *LeaMI = --PrevI;
Evan Chenga441c1a2009-08-14 00:32:16 +00001530 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1531 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001532 LeaMI->getOperand(0).getReg() != BaseReg)
Evan Cheng04f40fa2009-08-01 06:13:52 +00001533 OptOk = false;
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001534
Evan Cheng04f40fa2009-08-01 06:13:52 +00001535 if (!OptOk)
1536 continue;
1537
1538 unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1539 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1540 .addReg(IdxReg, getKillRegState(IdxRegKill))
1541 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1542 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1543 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1544 // is 2-byte aligned. For now, asm printer will fix it up.
1545 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1546 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1547 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1548 OrigSize += TII->GetInstSizeInBytes(MI);
1549
1550 AddrMI->eraseFromParent();
1551 LeaMI->eraseFromParent();
1552 MI->eraseFromParent();
1553
1554 int delta = OrigSize - NewSize;
1555 BBSizes[MBB->getNumber()] -= delta;
1556 AdjustBBOffsetsAfter(MBB, -delta);
1557
1558 ++NumTBs;
1559 MadeChange = true;
Evan Cheng1b2b3e22009-07-29 02:18:14 +00001560 }
1561 }
1562
1563 return MadeChange;
1564}