blob: 927d16f864e582a71d7f6bbe35ebd90b9e7fba4c [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
32STATISTIC(NumSplit, "Number of uncond branches inserted");
33
34namespace {
35 /// ARMConstantIslands - Due to limited pc-relative displacements, ARM
36 /// requires constant pool entries to be scattered among the instructions
37 /// inside a function. To do this, it completely ignores the normal LLVM
38 /// constant pool, instead, it places constants where-ever it feels like with
39 /// special instructions.
40 ///
41 /// The terminology used in this pass includes:
42 /// Islands - Clumps of constants placed in the function.
43 /// Water - Potential places where an island could be formed.
44 /// CPE - A constant pool entry that has been placed somewhere, which
45 /// tracks a list of users.
46 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
47 /// NextUID - Assign unique ID's to CPE's.
48 unsigned NextUID;
49
50 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
51 /// by MBB Number.
52 std::vector<unsigned> BBSizes;
53
54 /// WaterList - A sorted list of basic blocks where islands could be placed
55 /// (i.e. blocks that don't fall through to the following block, due
56 /// to a return, unreachable, or unconditional branch).
57 std::vector<MachineBasicBlock*> WaterList;
58
59 /// CPUser - One user of a constant pool, keeping the machine instruction
60 /// pointer, the constant pool being referenced, and the max displacement
61 /// allowed from the instruction to the CP.
62 struct CPUser {
63 MachineInstr *MI;
64 MachineInstr *CPEMI;
65 unsigned MaxDisp;
66 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
67 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
68 };
69
70 /// CPUsers - Keep track of all of the machine instructions that use various
71 /// constant pools and their max displacement.
72 std::vector<CPUser> CPUsers;
73
Evan Chengaf5cbcb2007-01-25 03:12:46 +000074 /// ImmBranch - One per immediate branch, keeping the machine instruction
75 /// pointer, conditional or unconditional, the max displacement,
76 /// and (if isCond is true) the corresponding unconditional branch
77 /// opcode.
78 struct ImmBranch {
79 MachineInstr *MI;
Evan Chengc2854142007-01-25 23:18:59 +000080 unsigned MaxDisp : 31;
81 bool isCond : 1;
Evan Chengaf5cbcb2007-01-25 03:12:46 +000082 int UncondBr;
Evan Chengc2854142007-01-25 23:18:59 +000083 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
84 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
Evan Chengaf5cbcb2007-01-25 03:12:46 +000085 };
86
Evan Chengc2854142007-01-25 23:18:59 +000087 /// Branches - Keep track of all the immediate branch instructions.
Evan Chengaf5cbcb2007-01-25 03:12:46 +000088 ///
89 std::vector<ImmBranch> ImmBranches;
90
Evan Chenga8e29892007-01-19 07:51:42 +000091 const TargetInstrInfo *TII;
Evan Chenga8e29892007-01-19 07:51:42 +000092 public:
93 virtual bool runOnMachineFunction(MachineFunction &Fn);
94
95 virtual const char *getPassName() const {
Evan Chengaf5cbcb2007-01-25 03:12:46 +000096 return "ARM constant island placement and branch shortening pass";
Evan Chenga8e29892007-01-19 07:51:42 +000097 }
98
99 private:
100 void DoInitialPlacement(MachineFunction &Fn,
101 std::vector<MachineInstr*> &CPEMIs);
102 void InitialFunctionScan(MachineFunction &Fn,
103 const std::vector<MachineInstr*> &CPEMIs);
104 void SplitBlockBeforeInstr(MachineInstr *MI);
Evan Chenga8e29892007-01-19 07:51:42 +0000105 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000106 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
Evan Cheng43aeab62007-01-26 20:38:26 +0000107 bool BBIsInBranchRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned D);
Evan Chengc2854142007-01-25 23:18:59 +0000108 bool FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br);
Evan Chenga8e29892007-01-19 07:51:42 +0000109
Evan Chenga8e29892007-01-19 07:51:42 +0000110 unsigned GetOffsetOf(MachineInstr *MI) const;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000111 unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
Evan Chenga8e29892007-01-19 07:51:42 +0000112 };
113}
114
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000115/// createARMConstantIslandPass - returns an instance of the constpool
116/// island pass.
Evan Chenga8e29892007-01-19 07:51:42 +0000117FunctionPass *llvm::createARMConstantIslandPass() {
118 return new ARMConstantIslands();
119}
120
121bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
Evan Chenga8e29892007-01-19 07:51:42 +0000122 MachineConstantPool &MCP = *Fn.getConstantPool();
Evan Chenga8e29892007-01-19 07:51:42 +0000123
124 TII = Fn.getTarget().getInstrInfo();
Evan Chenga8e29892007-01-19 07:51:42 +0000125
126 // Renumber all of the machine basic blocks in the function, guaranteeing that
127 // the numbers agree with the position of the block in the function.
128 Fn.RenumberBlocks();
129
130 // Perform the initial placement of the constant pool entries. To start with,
131 // we put them all at the end of the function.
132 std::vector<MachineInstr*> CPEMIs;
Evan Cheng7755fac2007-01-26 01:04:44 +0000133 if (!MCP.isEmpty())
134 DoInitialPlacement(Fn, CPEMIs);
Evan Chenga8e29892007-01-19 07:51:42 +0000135
136 /// The next UID to take is the first unused one.
137 NextUID = CPEMIs.size();
138
139 // Do the initial scan of the function, building up information about the
140 // sizes of each block, the location of all the water, and finding all of the
141 // constant pool users.
142 InitialFunctionScan(Fn, CPEMIs);
143 CPEMIs.clear();
144
145 // Iteratively place constant pool entries until there is no change.
146 bool MadeChange;
147 do {
148 MadeChange = false;
149 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
150 MadeChange |= HandleConstantPoolUser(Fn, CPUsers[i]);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000151 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
Evan Chengc2854142007-01-25 23:18:59 +0000152 MadeChange |= FixUpImmediateBranch(Fn, ImmBranches[i]);
Evan Chenga8e29892007-01-19 07:51:42 +0000153 } while (MadeChange);
154
155 BBSizes.clear();
156 WaterList.clear();
157 CPUsers.clear();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000158 ImmBranches.clear();
Evan Chenga8e29892007-01-19 07:51:42 +0000159
160 return true;
161}
162
163/// DoInitialPlacement - Perform the initial placement of the constant pool
164/// entries. To start with, we put them all at the end of the function.
165void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
166 std::vector<MachineInstr*> &CPEMIs){
167 // Create the basic block to hold the CPE's.
168 MachineBasicBlock *BB = new MachineBasicBlock();
169 Fn.getBasicBlockList().push_back(BB);
170
171 // Add all of the constants from the constant pool to the end block, use an
172 // identity mapping of CPI's to CPE's.
173 const std::vector<MachineConstantPoolEntry> &CPs =
174 Fn.getConstantPool()->getConstants();
175
176 const TargetData &TD = *Fn.getTarget().getTargetData();
177 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
178 unsigned Size = TD.getTypeSize(CPs[i].getType());
179 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
180 // we would have to pad them out or something so that instructions stay
181 // aligned.
182 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
183 MachineInstr *CPEMI =
184 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
185 .addImm(i).addConstantPoolIndex(i).addImm(Size);
186 CPEMIs.push_back(CPEMI);
187 DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
188 << i << "\n");
189 }
190}
191
192/// BBHasFallthrough - Return true of the specified basic block can fallthrough
193/// into the block immediately after it.
194static bool BBHasFallthrough(MachineBasicBlock *MBB) {
195 // Get the next machine basic block in the function.
196 MachineFunction::iterator MBBI = MBB;
197 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
198 return false;
199
200 MachineBasicBlock *NextBB = next(MBBI);
201 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
202 E = MBB->succ_end(); I != E; ++I)
203 if (*I == NextBB)
204 return true;
205
206 return false;
207}
208
209/// InitialFunctionScan - Do the initial scan of the function, building up
210/// information about the sizes of each block, the location of all the water,
211/// and finding all of the constant pool users.
212void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
213 const std::vector<MachineInstr*> &CPEMIs) {
214 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
215 MBBI != E; ++MBBI) {
216 MachineBasicBlock &MBB = *MBBI;
217
218 // If this block doesn't fall through into the next MBB, then this is
219 // 'water' that a constant pool island could be placed.
220 if (!BBHasFallthrough(&MBB))
221 WaterList.push_back(&MBB);
222
223 unsigned MBBSize = 0;
224 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
225 I != E; ++I) {
226 // Add instruction size to MBBSize.
Evan Cheng29836c32007-01-29 23:45:17 +0000227 MBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000228
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000229 int Opc = I->getOpcode();
230 if (TII->isBranch(Opc)) {
231 bool isCond = false;
232 unsigned Bits = 0;
233 unsigned Scale = 1;
234 int UOpc = Opc;
235 switch (Opc) {
Evan Cheng743fa032007-01-25 19:43:52 +0000236 default:
237 continue; // Ignore JT branches
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000238 case ARM::Bcc:
239 isCond = true;
240 UOpc = ARM::B;
241 // Fallthrough
242 case ARM::B:
243 Bits = 24;
244 Scale = 4;
245 break;
246 case ARM::tBcc:
247 isCond = true;
248 UOpc = ARM::tB;
249 Bits = 8;
250 Scale = 2;
251 break;
252 case ARM::tB:
253 Bits = 11;
254 Scale = 2;
255 break;
256 }
257 unsigned MaxDisp = (1 << (Bits-1)) * Scale;
Evan Chengc2854142007-01-25 23:18:59 +0000258 ImmBranches.push_back(ImmBranch(I, MaxDisp, isCond, UOpc));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000259 }
260
Evan Chenga8e29892007-01-19 07:51:42 +0000261 // Scan the instructions for constant pool operands.
262 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
263 if (I->getOperand(op).isConstantPoolIndex()) {
264 // We found one. The addressing mode tells us the max displacement
265 // from the PC that this instruction permits.
266 unsigned MaxOffs = 0;
267
268 // Basic size info comes from the TSFlags field.
269 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
270 switch (TSFlags & ARMII::AddrModeMask) {
271 default:
272 // Constant pool entries can reach anything.
273 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
274 continue;
275 assert(0 && "Unknown addressing mode for CP reference!");
276 case ARMII::AddrMode1: // AM1: 8 bits << 2
277 MaxOffs = 1 << (8+2); // Taking the address of a CP entry.
278 break;
279 case ARMII::AddrMode2:
280 MaxOffs = 1 << 12; // +-offset_12
281 break;
282 case ARMII::AddrMode3:
283 MaxOffs = 1 << 8; // +-offset_8
284 break;
285 // addrmode4 has no immediate offset.
286 case ARMII::AddrMode5:
287 MaxOffs = 1 << (8+2); // +-(offset_8*4)
288 break;
289 case ARMII::AddrModeT1:
290 MaxOffs = 1 << 5;
291 break;
292 case ARMII::AddrModeT2:
293 MaxOffs = 1 << (5+1);
294 break;
295 case ARMII::AddrModeT4:
296 MaxOffs = 1 << (5+2);
297 break;
Evan Cheng012f2d92007-01-24 08:53:17 +0000298 case ARMII::AddrModeTs:
299 MaxOffs = 1 << (8+2);
300 break;
Evan Chenga8e29892007-01-19 07:51:42 +0000301 }
302
303 // Remember that this is a user of a CP entry.
304 MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
305 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
306
307 // Instructions can only use one CP entry, don't bother scanning the
308 // rest of the operands.
309 break;
310 }
311 }
312 BBSizes.push_back(MBBSize);
313 }
314}
315
Evan Chenga8e29892007-01-19 07:51:42 +0000316/// GetOffsetOf - Return the current offset of the specified machine instruction
317/// from the start of the function. This offset changes as stuff is moved
318/// around inside the function.
319unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
320 MachineBasicBlock *MBB = MI->getParent();
321
322 // The offset is composed of two things: the sum of the sizes of all MBB's
323 // before this instruction's block, and the offset from the start of the block
324 // it is in.
325 unsigned Offset = 0;
326
327 // Sum block sizes before MBB.
328 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
329 Offset += BBSizes[BB];
330
331 // Sum instructions before MI in MBB.
332 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
333 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
334 if (&*I == MI) return Offset;
Evan Cheng29836c32007-01-29 23:45:17 +0000335 Offset += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000336 }
337}
338
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000339/// GetOffsetOf - Return the current offset of the specified machine BB
340/// from the start of the function. This offset changes as stuff is moved
341/// around inside the function.
342unsigned ARMConstantIslands::GetOffsetOf(MachineBasicBlock *MBB) const {
343 // Sum block sizes before MBB.
344 unsigned Offset = 0;
345 for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
346 Offset += BBSizes[BB];
347
348 return Offset;
349}
350
Evan Chenga8e29892007-01-19 07:51:42 +0000351/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
352/// ID.
353static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
354 const MachineBasicBlock *RHS) {
355 return LHS->getNumber() < RHS->getNumber();
356}
357
358/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
359/// machine function, it upsets all of the block numbers. Renumber the blocks
360/// and update the arrays that parallel this numbering.
361void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
362 // Renumber the MBB's to keep them consequtive.
363 NewBB->getParent()->RenumberBlocks(NewBB);
364
365 // Insert a size into BBSizes to align it properly with the (newly
366 // renumbered) block numbers.
367 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
368
369 // Next, update WaterList. Specifically, we need to add NewMBB as having
370 // available water after it.
371 std::vector<MachineBasicBlock*>::iterator IP =
372 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
373 CompareMBBNumbers);
374 WaterList.insert(IP, NewBB);
375}
376
377
378/// Split the basic block containing MI into two blocks, which are joined by
379/// an unconditional branch. Update datastructures and renumber blocks to
380/// account for this change.
381void ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
382 MachineBasicBlock *OrigBB = MI->getParent();
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000383 const ARMFunctionInfo *AFI = OrigBB->getParent()->getInfo<ARMFunctionInfo>();
384 bool isThumb = AFI->isThumbFunction();
Evan Chenga8e29892007-01-19 07:51:42 +0000385
386 // Create a new MBB for the code after the OrigBB.
387 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
388 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
389 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
390
391 // Splice the instructions starting with MI over to NewBB.
392 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
393
394 // Add an unconditional branch from OrigBB to NewBB.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000395 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
Evan Chenga8e29892007-01-19 07:51:42 +0000396 NumSplit++;
397
398 // Update the CFG. All succs of OrigBB are now succs of NewBB.
399 while (!OrigBB->succ_empty()) {
400 MachineBasicBlock *Succ = *OrigBB->succ_begin();
401 OrigBB->removeSuccessor(Succ);
402 NewBB->addSuccessor(Succ);
403
404 // This pass should be run after register allocation, so there should be no
405 // PHI nodes to update.
406 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
407 && "PHI nodes should be eliminated by now!");
408 }
409
410 // OrigBB branches to NewBB.
411 OrigBB->addSuccessor(NewBB);
412
413 // Update internal data structures to account for the newly inserted MBB.
414 UpdateForInsertedWaterBlock(NewBB);
415
416 // Figure out how large the first NewMBB is.
417 unsigned NewBBSize = 0;
418 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
419 I != E; ++I)
Evan Cheng29836c32007-01-29 23:45:17 +0000420 NewBBSize += ARM::GetInstSize(I);
Evan Chenga8e29892007-01-19 07:51:42 +0000421
422 // Set the size of NewBB in BBSizes.
423 BBSizes[NewBB->getNumber()] = NewBBSize;
424
425 // We removed instructions from UserMBB, subtract that off from its size.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000426 // Add 2 or 4 to the block to count the unconditional branch we added to it.
427 BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
Evan Chenga8e29892007-01-19 07:51:42 +0000428}
429
430/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
431/// is out-of-range. If so, pick it up the constant pool value and move it some
432/// place in-range.
433bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
434 MachineInstr *UserMI = U.MI;
435 MachineInstr *CPEMI = U.CPEMI;
436
437 unsigned UserOffset = GetOffsetOf(UserMI);
438 unsigned CPEOffset = GetOffsetOf(CPEMI);
439
440 DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
441 << " max delta=" << U.MaxDisp
442 << " at offset " << int(UserOffset-CPEOffset) << "\t"
443 << *UserMI);
444
445 // Check to see if the CPE is already in-range.
446 if (UserOffset < CPEOffset) {
447 // User before the CPE.
448 if (CPEOffset-UserOffset <= U.MaxDisp)
449 return false;
450 } else {
451 if (UserOffset-CPEOffset <= U.MaxDisp)
452 return false;
453 }
454
455
456 // Solution guaranteed to work: split the user's MBB right before the user and
457 // insert a clone the CPE into the newly created water.
458
459 // If the user isn't at the start of its MBB, or if there is a fall-through
460 // into the user's MBB, split the MBB before the User.
461 MachineBasicBlock *UserMBB = UserMI->getParent();
462 if (&UserMBB->front() != UserMI ||
463 UserMBB == &Fn.front() || // entry MBB of function.
464 BBHasFallthrough(prior(MachineFunction::iterator(UserMBB)))) {
465 // TODO: Search for the best place to split the code. In practice, using
466 // loop nesting information to insert these guys outside of loops would be
467 // sufficient.
468 SplitBlockBeforeInstr(UserMI);
469
470 // UserMI's BB may have changed.
471 UserMBB = UserMI->getParent();
472 }
473
474 // Okay, we know we can put an island before UserMBB now, do it!
475 MachineBasicBlock *NewIsland = new MachineBasicBlock();
476 Fn.getBasicBlockList().insert(UserMBB, NewIsland);
477
478 // Update internal data structures to account for the newly inserted MBB.
479 UpdateForInsertedWaterBlock(NewIsland);
480
481 // Now that we have an island to add the CPE to, clone the original CPE and
482 // add it to the island.
483 unsigned ID = NextUID++;
484 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
485 unsigned Size = CPEMI->getOperand(2).getImm();
486
487 // Build a new CPE for this user.
488 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
489 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
490
491 // Increase the size of the island block to account for the new entry.
492 BBSizes[NewIsland->getNumber()] += Size;
493
494 // Finally, change the CPI in the instruction operand to be ID.
495 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
496 if (UserMI->getOperand(i).isConstantPoolIndex()) {
497 UserMI->getOperand(i).setConstantPoolIndex(ID);
498 break;
499 }
500
501 DEBUG(std::cerr << " Moved CPE to #" << ID << " CPI=" << CPI << "\t"
502 << *UserMI);
503
504
505 return true;
506}
507
Evan Cheng43aeab62007-01-26 20:38:26 +0000508/// BBIsInBranchRange - Returns true is the distance between specific MI and
509/// specific BB can fit in MI's displacement field.
510bool ARMConstantIslands::BBIsInBranchRange(MachineInstr *MI,
511 MachineBasicBlock *DestBB,
512 unsigned MaxDisp) {
513 unsigned BrOffset = GetOffsetOf(MI);
514 unsigned DestOffset = GetOffsetOf(DestBB);
515
516 // Check to see if the destination BB is in range.
517 if (BrOffset < DestOffset) {
518 if (DestOffset - BrOffset < MaxDisp)
519 return true;
520 } else {
521 if (BrOffset - DestOffset <= MaxDisp)
522 return true;
523 }
524 return false;
525}
526
527static inline unsigned getUncondBranchDisp(int Opc) {
528 return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
529}
530
Evan Chengc2854142007-01-25 23:18:59 +0000531/// FixUpImmediateBranch - Fix up immediate branches whose destination is too
532/// far away to fit in its displacement field. If it is a conditional branch,
533/// then it is converted to an inverse conditional branch + an unconditional
534/// branch to the destination. If it is an unconditional branch, then it is
535/// converted to a branch to a branch.
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000536bool
Evan Chengc2854142007-01-25 23:18:59 +0000537ARMConstantIslands::FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000538 MachineInstr *MI = Br.MI;
539 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
540
Evan Cheng43aeab62007-01-26 20:38:26 +0000541 if (BBIsInBranchRange(MI, DestBB, Br.MaxDisp))
542 return false;
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000543
544 if (!Br.isCond) {
545 // Unconditional branch. We have to insert a branch somewhere to perform
546 // a two level branch (branch to branch). FIXME: not yet implemented.
547 assert(false && "Can't handle unconditional branch yet!");
548 return false;
549 }
550
551 // Otherwise, add a unconditional branch to the destination and
552 // invert the branch condition to jump over it:
553 // blt L1
554 // =>
555 // bge L2
556 // b L1
557 // L2:
558 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
559 CC = ARMCC::getOppositeCondition(CC);
560
561 // If the branch is at the end of its MBB and that has a fall-through block,
562 // direct the updated conditional branch to the fall-through block. Otherwise,
563 // split the MBB before the next instruction.
564 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng43aeab62007-01-26 20:38:26 +0000565 MachineInstr *BackMI = &MBB->back();
566 bool NeedSplit = (BackMI != MI) || !BBHasFallthrough(MBB);
567
568 if (BackMI != MI) {
569 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
570 BackMI->getOpcode() == Br.UncondBr) {
571 // Last MI in the BB is a unconditional branch. Can we simply invert the
572 // condition and swap destinations:
573 // beq L1
574 // b L2
575 // =>
576 // bne L2
577 // b L1
578 MachineBasicBlock *NewDest = BackMI->getOperand(0).getMachineBasicBlock();
579 if (BBIsInBranchRange(MI, NewDest, Br.MaxDisp)) {
580 BackMI->getOperand(0).setMachineBasicBlock(DestBB);
581 MI->getOperand(0).setMachineBasicBlock(NewDest);
582 MI->getOperand(1).setImm(CC);
583 return true;
584 }
585 }
586 }
587
588 if (NeedSplit) {
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000589 SplitBlockBeforeInstr(MI);
Evan Chengdd353b82007-01-26 02:02:39 +0000590 // No need for the branch to the next block. We're adding a unconditional
591 // branch to the destination.
592 MBB->back().eraseFromParent();
593 }
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000594 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
595
596 // Insert a unconditional branch and replace the conditional branch.
597 // Also update the ImmBranch as well as adding a new entry for the new branch.
Evan Chengdd353b82007-01-26 02:02:39 +0000598 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000599 Br.MI = &MBB->back();
600 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
Evan Cheng43aeab62007-01-26 20:38:26 +0000601 unsigned MaxDisp = getUncondBranchDisp(Br.UncondBr);
Evan Chenga0bf7942007-01-25 23:31:04 +0000602 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000603 MI->eraseFromParent();
604
605 // Increase the size of MBB to account for the new unconditional branch.
Evan Cheng29836c32007-01-29 23:45:17 +0000606 BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
Evan Chengaf5cbcb2007-01-25 03:12:46 +0000607 return true;
608}