blob: 32f8e8cb255ad1e2df54fbc9e43a21920263cee7 [file] [log] [blame]
Evan Chenga8e29892007-01-19 07:51:42 +00001//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that splits the constant pool up into 'islands'
11// which are scattered through-out the function. This is required due to the
12// limited pc-relative displacements that ARM has.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "arm-cp-islands"
17#include "ARM.h"
Evan Chengaf5cbcb2007-01-25 03:12:46 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga8e29892007-01-19 07:51:42 +000019#include "ARMInstrInfo.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Chenga8e29892007-01-19 07:51:42 +000023#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/Statistic.h"
29#include <iostream>
30using namespace llvm;
31
Evan Chengd1b2c1e2007-01-30 01:18:38 +000032STATISTIC(NumSplit, "Number of uncond branches inserted");
33STATISTIC(NumCBrFixed, "Number of cond branches fixed");
34STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
Evan Chenga8e29892007-01-19 07:51:42 +000035
36namespace {
37 /// ARMConstantIslands - Due to limited pc-relative displacements, ARM
38 /// requires constant pool entries to be scattered among the instructions
39 /// inside a function. To do this, it completely ignores the normal LLVM
40 /// constant pool, instead, it places constants where-ever it feels like with
41 /// special instructions.
42 ///
43 /// The terminology used in this pass includes:
44 /// Islands - Clumps of constants placed in the function.
45 /// Water - Potential places where an island could be formed.
46 /// CPE - A constant pool entry that has been placed somewhere, which
47 /// tracks a list of users.
48 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
49 /// NextUID - Assign unique ID's to CPE's.
50 unsigned NextUID;
51
52 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
53 /// by MBB Number.
54 std::vector<unsigned> BBSizes;
55
56 /// WaterList - A sorted list of basic blocks where islands could be placed
57 /// (i.e. blocks that don't fall through to the following block, due
58 /// to a return, unreachable, or unconditional branch).
59 std::vector<MachineBasicBlock*> WaterList;
60
61 /// CPUser - One user of a constant pool, keeping the machine instruction
62 /// pointer, the constant pool being referenced, and the max displacement
63 /// allowed from the instruction to the CP.
64 struct CPUser {
65 MachineInstr *MI;
66 MachineInstr *CPEMI;
67 unsigned MaxDisp;
68 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
69 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
70 };
71
72 /// CPUsers - Keep track of all of the machine instructions that use various
73 /// constant pools and their max displacement.
74 std::vector<CPUser> CPUsers;
75
Evan Chengaf5cbcb2007-01-25 03:12:46 +000076 /// ImmBranch - One per immediate branch, keeping the machine instruction
77 /// pointer, conditional or unconditional, the max displacement,
78 /// and (if isCond is true) the corresponding unconditional branch
79 /// opcode.
80 struct ImmBranch {
81 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +000082 unsigned MaxDisp : 31;
83 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +000084 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +000085 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
86 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +000087 };
88
Evan Chengc2854142007-01-25 23:18:59 +000089 /// Branches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +000090 ///
91 std::vector<ImmBranch> ImmBranches;
92
Evan Chengd1b2c1e2007-01-30 01:18:38 +000093 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
94 ///
95 std::vector<MachineInstr*> PushPopMIs;
96
97 /// HasFarJump - True if any far jump instruction has been emitted during
98 /// the branch fix up pass.
99 bool HasFarJump;
100
Evan Chenga8e29892007-01-19 07:51:42 +0000101 const TargetInstrInfo *TII;
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000102 const ARMFunctionInfo *AFI;
Evan Chenga8e29892007-01-19 07:51:42 +0000103 public:
104 virtual bool runOnMachineFunction(MachineFunction &Fn);
105
106 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000107 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +0000108 }
109
110 private:
111 void DoInitialPlacement(MachineFunction &Fn,
112 std::vector<MachineInstr*> &CPEMIs);
113 void InitialFunctionScan(MachineFunction &Fn,
114 const std::vector<MachineInstr*> &CPEMIs);
Evan Cheng0c615842007-01-31 02:22:22 +0000115 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000116 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000117 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
Evan Cheng43aeab62007-01-26 20:38:26 +0000118 bool BBIsInBranchRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned D);
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000119 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
120 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
121 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
122 bool UndoLRSpillRestore();
Evan Chenga8e29892007-01-19 07:51:42 +0000123
Evan Chenga8e29892007-01-19 07:51:42 +0000124 unsigned GetOffsetOf(MachineInstr *MI) const;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000125 unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
Evan Chenga8e29892007-01-19 07:51:42 +0000126 };
127}
128
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000129/// createARMConstantIslandPass - returns an instance of the constpool
130/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000131FunctionPass *llvm::createARMConstantIslandPass() {
132 return new ARMConstantIslands();
133}
134
135bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000136 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000137
138 TII = Fn.getTarget().getInstrInfo();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000139 AFI = Fn.getInfo<ARMFunctionInfo>();
140
141 HasFarJump = false;
142
Evan Chenga8e29892007-01-19 07:51:42 +0000143 // Renumber all of the machine basic blocks in the function, guaranteeing that
144 // the numbers agree with the position of the block in the function.
145 Fn.RenumberBlocks();
146
147 // Perform the initial placement of the constant pool entries. To start with,
148 // we put them all at the end of the function.
149 std::vector<MachineInstr*> CPEMIs;
Evan Cheng7755fac2007-01-26 01:04:44 +0000150 if (!MCP.isEmpty())
151 DoInitialPlacement(Fn, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000152
153 /// The next UID to take is the first unused one.
154 NextUID = CPEMIs.size();
155
156 // Do the initial scan of the function, building up information about the
157 // sizes of each block, the location of all the water, and finding all of the
158 // constant pool users.
159 InitialFunctionScan(Fn, CPEMIs);
160 CPEMIs.clear();
161
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000162 // Iteratively place constant pool entries and fix up branches until there
163 // is no change.
164 bool MadeChange = false;
165 while (true) {
166 bool Change = false;
Evan Chenga8e29892007-01-19 07:51:42 +0000167 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000168 Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000169 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000170 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
171 if (!Change)
172 break;
173 MadeChange = true;
174 }
Evan Chenga8e29892007-01-19 07:51:42 +0000175
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000176 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
177 // Undo the spill / restore of LR if possible.
178 if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
179 MadeChange |= UndoLRSpillRestore();
180
Evan Chenga8e29892007-01-19 07:51:42 +0000181 BBSizes.clear();
182 WaterList.clear();
183 CPUsers.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000184 ImmBranches.clear();
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000185
186 return MadeChange;
Evan Chenga8e29892007-01-19 07:51:42 +0000187}
188
189/// DoInitialPlacement - Perform the initial placement of the constant pool
190/// entries. To start with, we put them all at the end of the function.
191void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
192 std::vector<MachineInstr*> &CPEMIs){
193 // Create the basic block to hold the CPE's.
194 MachineBasicBlock *BB = new MachineBasicBlock();
195 Fn.getBasicBlockList().push_back(BB);
196
197 // Add all of the constants from the constant pool to the end block, use an
198 // identity mapping of CPI's to CPE's.
199 const std::vector<MachineConstantPoolEntry> &CPs =
200 Fn.getConstantPool()->getConstants();
201
202 const TargetData &TD = *Fn.getTarget().getTargetData();
203 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
204 unsigned Size = TD.getTypeSize(CPs[i].getType());
205 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
206 // we would have to pad them out or something so that instructions stay
207 // aligned.
208 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
209 MachineInstr *CPEMI =
210 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
211 .addImm(i).addConstantPoolIndex(i).addImm(Size);
212 CPEMIs.push_back(CPEMI);
213 DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
214 << i << "\n");
215 }
216}
217
218/// BBHasFallthrough - Return true of the specified basic block can fallthrough
219/// into the block immediately after it.
220static bool BBHasFallthrough(MachineBasicBlock *MBB) {
221 // Get the next machine basic block in the function.
222 MachineFunction::iterator MBBI = MBB;
223 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
224 return false;
225
226 MachineBasicBlock *NextBB = next(MBBI);
227 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
228 E = MBB->succ_end(); I != E; ++I)
229 if (*I == NextBB)
230 return true;
231
232 return false;
233}
234
235/// InitialFunctionScan - Do the initial scan of the function, building up
236/// information about the sizes of each block, the location of all the water,
237/// and finding all of the constant pool users.
238void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
239 const std::vector<MachineInstr*> &CPEMIs) {
240 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
241 MBBI != E; ++MBBI) {
242 MachineBasicBlock &MBB = *MBBI;
243
244 // If this block doesn't fall through into the next MBB, then this is
245 // 'water' that a constant pool island could be placed.
246 if (!BBHasFallthrough(&MBB))
247 WaterList.push_back(&MBB);
248
249 unsigned MBBSize = 0;
250 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
251 I != E; ++I) {
252 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000253 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000254
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000255 int Opc = I->getOpcode();
256 if (TII->isBranch(Opc)) {
257 bool isCond = false;
258 unsigned Bits = 0;
259 unsigned Scale = 1;
260 int UOpc = Opc;
261 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000262 default:
263 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000264 case ARM::Bcc:
265 isCond = true;
266 UOpc = ARM::B;
267 // Fallthrough
268 case ARM::B:
269 Bits = 24;
270 Scale = 4;
271 break;
272 case ARM::tBcc:
273 isCond = true;
274 UOpc = ARM::tB;
275 Bits = 8;
276 Scale = 2;
277 break;
278 case ARM::tB:
279 Bits = 11;
280 Scale = 2;
281 break;
282 }
283 unsigned MaxDisp = (1 << (Bits-1)) * Scale;
Evan Chengc2854142007-01-25 23:18:59 +0000284 ImmBranches.push_back(ImmBranch(I, MaxDisp, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000285 }
286
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000287 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
288 PushPopMIs.push_back(I);
289
Evan Chenga8e29892007-01-19 07:51:42 +0000290 // Scan the instructions for constant pool operands.
291 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
292 if (I->getOperand(op).isConstantPoolIndex()) {
293 // We found one. The addressing mode tells us the max displacement
294 // from the PC that this instruction permits.
295 unsigned MaxOffs = 0;
296
297 // Basic size info comes from the TSFlags field.
298 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
299 switch (TSFlags & ARMII::AddrModeMask) {
300 default:
301 // Constant pool entries can reach anything.
302 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
303 continue;
304 assert(0 && "Unknown addressing mode for CP reference!");
305 case ARMII::AddrMode1: // AM1: 8 bits << 2
306 MaxOffs = 1 << (8+2); // Taking the address of a CP entry.
307 break;
308 case ARMII::AddrMode2:
309 MaxOffs = 1 << 12; // +-offset_12
310 break;
311 case ARMII::AddrMode3:
312 MaxOffs = 1 << 8; // +-offset_8
313 break;
314 // addrmode4 has no immediate offset.
315 case ARMII::AddrMode5:
316 MaxOffs = 1 << (8+2); // +-(offset_8*4)
317 break;
318 case ARMII::AddrModeT1:
319 MaxOffs = 1 << 5;
320 break;
321 case ARMII::AddrModeT2:
322 MaxOffs = 1 << (5+1);
323 break;
324 case ARMII::AddrModeT4:
325 MaxOffs = 1 << (5+2);
326 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000327 case ARMII::AddrModeTs:
328 MaxOffs = 1 << (8+2);
329 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000330 }
331
332 // Remember that this is a user of a CP entry.
333 MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
334 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
335
336 // Instructions can only use one CP entry, don't bother scanning the
337 // rest of the operands.
338 break;
339 }
340 }
341 BBSizes.push_back(MBBSize);
342 }
343}
344
Evan Chenga8e29892007-01-19 07:51:42 +0000345/// GetOffsetOf - Return the current offset of the specified machine instruction
346/// from the start of the function. This offset changes as stuff is moved
347/// around inside the function.
348unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
349 MachineBasicBlock *MBB = MI->getParent();
350
351 // The offset is composed of two things: the sum of the sizes of all MBB's
352 // before this instruction's block, and the offset from the start of the block
353 // it is in.
354 unsigned Offset = 0;
355
356 // Sum block sizes before MBB.
357 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
358 Offset += BBSizes[BB];
359
360 // Sum instructions before MI in MBB.
361 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
362 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
363 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000364 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000365 }
366}
367
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000368/// GetOffsetOf - Return the current offset of the specified machine BB
369/// from the start of the function. This offset changes as stuff is moved
370/// around inside the function.
371unsigned ARMConstantIslands::GetOffsetOf(MachineBasicBlock *MBB) const {
372 // Sum block sizes before MBB.
373 unsigned Offset = 0;
374 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
375 Offset += BBSizes[BB];
376
377 return Offset;
378}
379
Evan Chenga8e29892007-01-19 07:51:42 +0000380/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
381/// ID.
382static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
383 const MachineBasicBlock *RHS) {
384 return LHS->getNumber() < RHS->getNumber();
385}
386
387/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
388/// machine function, it upsets all of the block numbers. Renumber the blocks
389/// and update the arrays that parallel this numbering.
390void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
391 // Renumber the MBB's to keep them consequtive.
392 NewBB->getParent()->RenumberBlocks(NewBB);
393
394 // Insert a size into BBSizes to align it properly with the (newly
395 // renumbered) block numbers.
396 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
397
398 // Next, update WaterList. Specifically, we need to add NewMBB as having
399 // available water after it.
400 std::vector<MachineBasicBlock*>::iterator IP =
401 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
402 CompareMBBNumbers);
403 WaterList.insert(IP, NewBB);
404}
405
406
407/// Split the basic block containing MI into two blocks, which are joined by
408/// an unconditional branch. Update datastructures and renumber blocks to
Evan Cheng0c615842007-01-31 02:22:22 +0000409/// account for this change and returns the newly created block.
410MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
Evan Chenga8e29892007-01-19 07:51:42 +0000411 MachineBasicBlock *OrigBB = MI->getParent();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000412 bool isThumb = AFI->isThumbFunction();
Evan Chenga8e29892007-01-19 07:51:42 +0000413
414 // Create a new MBB for the code after the OrigBB.
415 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
416 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
417 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
418
419 // Splice the instructions starting with MI over to NewBB.
420 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
421
422 // Add an unconditional branch from OrigBB to NewBB.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000423 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000424 NumSplit++;
425
426 // Update the CFG. All succs of OrigBB are now succs of NewBB.
427 while (!OrigBB->succ_empty()) {
428 MachineBasicBlock *Succ = *OrigBB->succ_begin();
429 OrigBB->removeSuccessor(Succ);
430 NewBB->addSuccessor(Succ);
431
432 // This pass should be run after register allocation, so there should be no
433 // PHI nodes to update.
434 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
435 && "PHI nodes should be eliminated by now!");
436 }
437
438 // OrigBB branches to NewBB.
439 OrigBB->addSuccessor(NewBB);
440
441 // Update internal data structures to account for the newly inserted MBB.
442 UpdateForInsertedWaterBlock(NewBB);
443
444 // Figure out how large the first NewMBB is.
445 unsigned NewBBSize = 0;
446 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
447 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000448 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000449
450 // Set the size of NewBB in BBSizes.
451 BBSizes[NewBB->getNumber()] = NewBBSize;
452
453 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000454 // Add 2 or 4 to the block to count the unconditional branch we added to it.
455 BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
Evan Cheng0c615842007-01-31 02:22:22 +0000456
457 return NewBB;
Evan Chenga8e29892007-01-19 07:51:42 +0000458}
459
460/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
461/// is out-of-range. If so, pick it up the constant pool value and move it some
462/// place in-range.
463bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
Evan Cheng934536d2007-01-31 18:19:07 +0000464 bool isThumb = AFI->isThumbFunction();
Evan Chenga8e29892007-01-19 07:51:42 +0000465 MachineInstr *UserMI = U.MI;
466 MachineInstr *CPEMI = U.CPEMI;
467
468 unsigned UserOffset = GetOffsetOf(UserMI);
469 unsigned CPEOffset = GetOffsetOf(CPEMI);
470
471 DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
472 << " max delta=" << U.MaxDisp
473 << " at offset " << int(UserOffset-CPEOffset) << "\t"
474 << *UserMI);
475
476 // Check to see if the CPE is already in-range.
477 if (UserOffset < CPEOffset) {
478 // User before the CPE.
479 if (CPEOffset-UserOffset <= U.MaxDisp)
480 return false;
Evan Cheng934536d2007-01-31 18:19:07 +0000481 } else if (!isThumb) {
Evan Cheng0c615842007-01-31 02:22:22 +0000482 // Thumb LDR cannot encode negative offset.
Evan Chenga8e29892007-01-19 07:51:42 +0000483 if (UserOffset-CPEOffset <= U.MaxDisp)
484 return false;
485 }
486
Evan Cheng0c615842007-01-31 02:22:22 +0000487
488 // Solution guaranteed to work: split the user's MBB right after the user and
Evan Chenga8e29892007-01-19 07:51:42 +0000489 // insert a clone the CPE into the newly created water.
Evan Cheng0c615842007-01-31 02:22:22 +0000490
Evan Cheng934536d2007-01-31 18:19:07 +0000491 MachineBasicBlock *UserMBB = UserMI->getParent();
492 MachineBasicBlock *NewMBB;
493
Evan Cheng0c615842007-01-31 02:22:22 +0000494 // TODO: Search for the best place to split the code. In practice, using
495 // loop nesting information to insert these guys outside of loops would be
496 // sufficient.
Evan Cheng934536d2007-01-31 18:19:07 +0000497 if (&UserMBB->back() == UserMI) {
498 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
499 NewMBB = next(MachineFunction::iterator(UserMBB));
500 // Add an unconditional branch from UserMBB to fallthrough block.
501 BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
502 BBSizes[UserMBB->getNumber()] += isThumb ? 2 : 4;
503 } else {
504 MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
505 NewMBB = SplitBlockBeforeInstr(NextMI);
506 }
Evan Cheng0c615842007-01-31 02:22:22 +0000507
Evan Chenga8e29892007-01-19 07:51:42 +0000508 // Okay, we know we can put an island before UserMBB now, do it!
509 MachineBasicBlock *NewIsland = new MachineBasicBlock();
Evan Cheng934536d2007-01-31 18:19:07 +0000510 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
Evan Chenga8e29892007-01-19 07:51:42 +0000511
512 // Update internal data structures to account for the newly inserted MBB.
513 UpdateForInsertedWaterBlock(NewIsland);
514
515 // Now that we have an island to add the CPE to, clone the original CPE and
516 // add it to the island.
517 unsigned ID = NextUID++;
518 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
519 unsigned Size = CPEMI->getOperand(2).getImm();
520
521 // Build a new CPE for this user.
522 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
523 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
524
525 // Increase the size of the island block to account for the new entry.
526 BBSizes[NewIsland->getNumber()] += Size;
527
528 // Finally, change the CPI in the instruction operand to be ID.
529 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
530 if (UserMI->getOperand(i).isConstantPoolIndex()) {
531 UserMI->getOperand(i).setConstantPoolIndex(ID);
532 break;
533 }
534
535 DEBUG(std::cerr << " Moved CPE to #" << ID << " CPI=" << CPI << "\t"
536 << *UserMI);
Evan Chenga8e29892007-01-19 07:51:42 +0000537
538 return true;
539}
540
Evan Cheng43aeab62007-01-26 20:38:26 +0000541/// BBIsInBranchRange - Returns true is the distance between specific MI and
542/// specific BB can fit in MI's displacement field.
543bool ARMConstantIslands::BBIsInBranchRange(MachineInstr *MI,
544 MachineBasicBlock *DestBB,
545 unsigned MaxDisp) {
546 unsigned BrOffset = GetOffsetOf(MI);
547 unsigned DestOffset = GetOffsetOf(DestBB);
548
549 // Check to see if the destination BB is in range.
550 if (BrOffset < DestOffset) {
551 if (DestOffset - BrOffset < MaxDisp)
552 return true;
553 } else {
554 if (BrOffset - DestOffset <= MaxDisp)
555 return true;
556 }
557 return false;
558}
559
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000560/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
561/// away to fit in its displacement field.
562bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000563 MachineInstr *MI = Br.MI;
564 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
565
Evan Cheng43aeab62007-01-26 20:38:26 +0000566 if (BBIsInBranchRange(MI, DestBB, Br.MaxDisp))
567 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000568
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000569 if (!Br.isCond)
570 return FixUpUnconditionalBr(Fn, Br);
571 return FixUpConditionalBr(Fn, Br);
572}
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000573
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000574/// FixUpUnconditionalBr - Fix up an unconditional branches whose destination is
575/// too far away to fit in its displacement field. If LR register has been
576/// spilled in the epilogue, then we can use BL to implement a far jump.
577/// Otherwise, add a intermediate branch instruction to to a branch.
578bool
579ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
580 MachineInstr *MI = Br.MI;
581 MachineBasicBlock *MBB = MI->getParent();
582 assert(AFI->isThumbFunction() && "Expected a Thumb function!");
583
584 // Use BL to implement far jump.
585 Br.MaxDisp = (1 << 21) * 2;
586 MI->setInstrDescriptor(TII->get(ARM::tBfar));
587 BBSizes[MBB->getNumber()] += 2;
588 HasFarJump = true;
589 NumUBrFixed++;
590 return true;
591}
592
593static inline unsigned getUncondBranchDisp(int Opc) {
594 return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
595}
596
597/// FixUpConditionalBr - Fix up a conditional branches whose destination is too
598/// far away to fit in its displacement field. It is converted to an inverse
599/// conditional branch + an unconditional branch to the destination.
600bool
601ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
602 MachineInstr *MI = Br.MI;
603 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
604
605 // Add a unconditional branch to the destination and invert the branch
606 // condition to jump over it:
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000607 // blt L1
608 // =>
609 // bge L2
610 // b L1
611 // L2:
612 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
613 CC = ARMCC::getOppositeCondition(CC);
614
615 // If the branch is at the end of its MBB and that has a fall-through block,
616 // direct the updated conditional branch to the fall-through block. Otherwise,
617 // split the MBB before the next instruction.
618 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng43aeab62007-01-26 20:38:26 +0000619 MachineInstr *BackMI = &MBB->back();
620 bool NeedSplit = (BackMI != MI) || !BBHasFallthrough(MBB);
621
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000622 NumCBrFixed++;
Evan Cheng43aeab62007-01-26 20:38:26 +0000623 if (BackMI != MI) {
624 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
625 BackMI->getOpcode() == Br.UncondBr) {
626 // Last MI in the BB is a unconditional branch. Can we simply invert the
627 // condition and swap destinations:
628 // beq L1
629 // b L2
630 // =>
631 // bne L2
632 // b L1
633 MachineBasicBlock *NewDest = BackMI->getOperand(0).getMachineBasicBlock();
634 if (BBIsInBranchRange(MI, NewDest, Br.MaxDisp)) {
635 BackMI->getOperand(0).setMachineBasicBlock(DestBB);
636 MI->getOperand(0).setMachineBasicBlock(NewDest);
637 MI->getOperand(1).setImm(CC);
638 return true;
639 }
640 }
641 }
642
643 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000644 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +0000645 // No need for the branch to the next block. We're adding a unconditional
646 // branch to the destination.
647 MBB->back().eraseFromParent();
648 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000649 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
650
651 // Insert a unconditional branch and replace the conditional branch.
652 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +0000653 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000654 Br.MI = &MBB->back();
655 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Evan Cheng43aeab62007-01-26 20:38:26 +0000656 unsigned MaxDisp = getUncondBranchDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +0000657 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000658 MI->eraseFromParent();
659
660 // Increase the size of MBB to account for the new unconditional branch.
Evan Cheng29836c32007-01-29 23:45:17 +0000661 BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000662 return true;
663}
Evan Chengd1b2c1e2007-01-30 01:18:38 +0000664
665
666/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
667/// LR / restores LR to pc.
668bool ARMConstantIslands::UndoLRSpillRestore() {
669 bool MadeChange = false;
670 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
671 MachineInstr *MI = PushPopMIs[i];
672 if (MI->getNumOperands() == 1) {
673 if (MI->getOpcode() == ARM::tPOP_RET &&
674 MI->getOperand(0).getReg() == ARM::PC)
675 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
676 MI->eraseFromParent();
677 MadeChange = true;
678 }
679 }
680 return MadeChange;
681}