Thumb jumptable support.
[oota-llvm.git] / lib / Target / ARM / ARMConstantIslandPass.cpp
1 //===-- 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"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include <iostream>
32 using namespace llvm;
33
34 STATISTIC(NumSplit, "Number of uncond branches inserted");
35
36 namespace {
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     
76     /// 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;
82       unsigned MaxDisp : 31;
83       bool isCond : 1;
84       int UncondBr;
85       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
86         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
87     };
88
89     /// Branches - Keep track of all the immediate branch instructions.
90     ///
91     std::vector<ImmBranch> ImmBranches;
92
93     const TargetInstrInfo *TII;
94     const TargetAsmInfo   *TAI;
95   public:
96     virtual bool runOnMachineFunction(MachineFunction &Fn);
97
98     virtual const char *getPassName() const {
99       return "ARM constant island placement and branch shortening pass";
100     }
101     
102   private:
103     void DoInitialPlacement(MachineFunction &Fn,
104                             std::vector<MachineInstr*> &CPEMIs);
105     void InitialFunctionScan(MachineFunction &Fn,
106                              const std::vector<MachineInstr*> &CPEMIs);
107     void SplitBlockBeforeInstr(MachineInstr *MI);
108     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
109     bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
110     bool BBIsInBranchRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned D);
111     bool FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br);
112
113     unsigned GetInstSize(MachineInstr *MI) const;
114     unsigned GetOffsetOf(MachineInstr *MI) const;
115     unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
116   };
117 }
118
119 /// createARMConstantIslandPass - returns an instance of the constpool
120 /// island pass.
121 FunctionPass *llvm::createARMConstantIslandPass() {
122   return new ARMConstantIslands();
123 }
124
125 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
126   MachineConstantPool &MCP = *Fn.getConstantPool();
127   
128   TII = Fn.getTarget().getInstrInfo();
129   TAI = Fn.getTarget().getTargetAsmInfo();
130   
131   // Renumber all of the machine basic blocks in the function, guaranteeing that
132   // the numbers agree with the position of the block in the function.
133   Fn.RenumberBlocks();
134
135   // Perform the initial placement of the constant pool entries.  To start with,
136   // we put them all at the end of the function.
137   std::vector<MachineInstr*> CPEMIs;
138   if (!MCP.isEmpty())
139     DoInitialPlacement(Fn, CPEMIs);
140   
141   /// The next UID to take is the first unused one.
142   NextUID = CPEMIs.size();
143   
144   // Do the initial scan of the function, building up information about the
145   // sizes of each block, the location of all the water, and finding all of the
146   // constant pool users.
147   InitialFunctionScan(Fn, CPEMIs);
148   CPEMIs.clear();
149   
150   // Iteratively place constant pool entries until there is no change.
151   bool MadeChange;
152   do {
153     MadeChange = false;
154     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
155       MadeChange |= HandleConstantPoolUser(Fn, CPUsers[i]);
156     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
157       MadeChange |= FixUpImmediateBranch(Fn, ImmBranches[i]);
158   } while (MadeChange);
159   
160   BBSizes.clear();
161   WaterList.clear();
162   CPUsers.clear();
163   ImmBranches.clear();
164     
165   return true;
166 }
167
168 /// DoInitialPlacement - Perform the initial placement of the constant pool
169 /// entries.  To start with, we put them all at the end of the function.
170 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
171                                             std::vector<MachineInstr*> &CPEMIs){
172   // Create the basic block to hold the CPE's.
173   MachineBasicBlock *BB = new MachineBasicBlock();
174   Fn.getBasicBlockList().push_back(BB);
175   
176   // Add all of the constants from the constant pool to the end block, use an
177   // identity mapping of CPI's to CPE's.
178   const std::vector<MachineConstantPoolEntry> &CPs =
179     Fn.getConstantPool()->getConstants();
180   
181   const TargetData &TD = *Fn.getTarget().getTargetData();
182   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
183     unsigned Size = TD.getTypeSize(CPs[i].getType());
184     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
185     // we would have to pad them out or something so that instructions stay
186     // aligned.
187     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
188     MachineInstr *CPEMI =
189       BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
190                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
191     CPEMIs.push_back(CPEMI);
192     DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
193                     << i << "\n");
194   }
195 }
196
197 /// BBHasFallthrough - Return true of the specified basic block can fallthrough
198 /// into the block immediately after it.
199 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
200   // Get the next machine basic block in the function.
201   MachineFunction::iterator MBBI = MBB;
202   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
203     return false;
204   
205   MachineBasicBlock *NextBB = next(MBBI);
206   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
207        E = MBB->succ_end(); I != E; ++I)
208     if (*I == NextBB)
209       return true;
210   
211   return false;
212 }
213
214 /// InitialFunctionScan - Do the initial scan of the function, building up
215 /// information about the sizes of each block, the location of all the water,
216 /// and finding all of the constant pool users.
217 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
218                                      const std::vector<MachineInstr*> &CPEMIs) {
219   for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
220        MBBI != E; ++MBBI) {
221     MachineBasicBlock &MBB = *MBBI;
222     
223     // If this block doesn't fall through into the next MBB, then this is
224     // 'water' that a constant pool island could be placed.
225     if (!BBHasFallthrough(&MBB))
226       WaterList.push_back(&MBB);
227     
228     unsigned MBBSize = 0;
229     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
230          I != E; ++I) {
231       // Add instruction size to MBBSize.
232       MBBSize += GetInstSize(I);
233
234       int Opc = I->getOpcode();
235       if (TII->isBranch(Opc)) {
236         bool isCond = false;
237         unsigned Bits = 0;
238         unsigned Scale = 1;
239         int UOpc = Opc;
240         switch (Opc) {
241         default:
242           continue;  // Ignore JT branches
243         case ARM::Bcc:
244           isCond = true;
245           UOpc = ARM::B;
246           // Fallthrough
247         case ARM::B:
248           Bits = 24;
249           Scale = 4;
250           break;
251         case ARM::tBcc:
252           isCond = true;
253           UOpc = ARM::tB;
254           Bits = 8;
255           Scale = 2;
256           break;
257         case ARM::tB:
258           Bits = 11;
259           Scale = 2;
260           break;
261         }
262         unsigned MaxDisp = (1 << (Bits-1)) * Scale;
263         ImmBranches.push_back(ImmBranch(I, MaxDisp, isCond, UOpc));
264       }
265
266       // Scan the instructions for constant pool operands.
267       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
268         if (I->getOperand(op).isConstantPoolIndex()) {
269           // We found one.  The addressing mode tells us the max displacement
270           // from the PC that this instruction permits.
271           unsigned MaxOffs = 0;
272           
273           // Basic size info comes from the TSFlags field.
274           unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
275           switch (TSFlags & ARMII::AddrModeMask) {
276           default: 
277             // Constant pool entries can reach anything.
278             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
279               continue;
280             assert(0 && "Unknown addressing mode for CP reference!");
281           case ARMII::AddrMode1: // AM1: 8 bits << 2
282             MaxOffs = 1 << (8+2);   // Taking the address of a CP entry.
283             break;
284           case ARMII::AddrMode2:
285             MaxOffs = 1 << 12;   // +-offset_12
286             break;
287           case ARMII::AddrMode3:
288             MaxOffs = 1 << 8;   // +-offset_8
289             break;
290             // addrmode4 has no immediate offset.
291           case ARMII::AddrMode5:
292             MaxOffs = 1 << (8+2);   // +-(offset_8*4)
293             break;
294           case ARMII::AddrModeT1:
295             MaxOffs = 1 << 5;
296             break;
297           case ARMII::AddrModeT2:
298             MaxOffs = 1 << (5+1);
299             break;
300           case ARMII::AddrModeT4:
301             MaxOffs = 1 << (5+2);
302             break;
303           case ARMII::AddrModeTs:
304             MaxOffs = 1 << (8+2);
305             break;
306           }
307           
308           // Remember that this is a user of a CP entry.
309           MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
310           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
311           
312           // Instructions can only use one CP entry, don't bother scanning the
313           // rest of the operands.
314           break;
315         }
316     }
317     BBSizes.push_back(MBBSize);
318   }
319 }
320
321 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing
322 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
323                                 unsigned JTI) DISABLE_INLINE;
324 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
325                                 unsigned JTI) {
326   return JT[JTI].MBBs.size();
327 }
328
329 /// GetInstSize - Return the size of the specified MachineInstr.
330 ///
331 unsigned ARMConstantIslands::GetInstSize(MachineInstr *MI) const {
332   // Basic size info comes from the TSFlags field.
333   unsigned TSFlags = MI->getInstrDescriptor()->TSFlags;
334   
335   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
336   default:
337     // If this machine instr is an inline asm, measure it.
338     if (MI->getOpcode() == ARM::INLINEASM)
339       return TAI->getInlineAsmLength(MI->getOperand(0).getSymbolName());
340     if (MI->getOpcode() == ARM::LABEL)
341       return 0;
342     assert(0 && "Unknown or unset size field for instr!");
343     break;
344   case ARMII::Size8Bytes: return 8;          // Arm instruction x 2.
345   case ARMII::Size4Bytes: return 4;          // Arm instruction.
346   case ARMII::Size2Bytes: return 2;          // Thumb instruction.
347   case ARMII::SizeSpecial: {
348     switch (MI->getOpcode()) {
349     case ARM::CONSTPOOL_ENTRY:
350       // If this machine instr is a constant pool entry, its size is recorded as
351       // operand #2.
352       return MI->getOperand(2).getImm();
353     case ARM::BR_JTr:
354     case ARM::BR_JTm:
355     case ARM::BR_JTadd:
356     case ARM::tBR_JTr: {
357       // These are jumptable branches, i.e. a branch followed by an inlined
358       // jumptable. The size is 4 + 4 * number of entries.
359       unsigned JTI = MI->getOperand(MI->getNumOperands()-2).getJumpTableIndex();
360       const MachineFunction *MF = MI->getParent()->getParent();
361       MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
362       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
363       assert(JTI < JT.size());
364       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
365       // 4 aligned. The assembler / linker may add 2 byte padding just before
366       // the JT entries. Use + 4 even for tBR_JTr to purposely over-estimate
367       // the size the jumptable.
368       // FIXME: If we know the size of the function is less than (1 << 16) *2
369       // bytes, we can use 16-bit entries instead. Then there won't be an
370       // alignment issue.
371       return getNumJTEntries(JT, JTI) * 4 + 4;
372     }
373     default:
374       // Otherwise, pseudo-instruction sizes are zero.
375       return 0;
376     }
377   }
378   }
379 }
380
381 /// GetOffsetOf - Return the current offset of the specified machine instruction
382 /// from the start of the function.  This offset changes as stuff is moved
383 /// around inside the function.
384 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
385   MachineBasicBlock *MBB = MI->getParent();
386   
387   // The offset is composed of two things: the sum of the sizes of all MBB's
388   // before this instruction's block, and the offset from the start of the block
389   // it is in.
390   unsigned Offset = 0;
391   
392   // Sum block sizes before MBB.
393   for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
394     Offset += BBSizes[BB];
395
396   // Sum instructions before MI in MBB.
397   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
398     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
399     if (&*I == MI) return Offset;
400     Offset += GetInstSize(I);
401   }
402 }
403
404 /// GetOffsetOf - Return the current offset of the specified machine BB
405 /// from the start of the function.  This offset changes as stuff is moved
406 /// around inside the function.
407 unsigned ARMConstantIslands::GetOffsetOf(MachineBasicBlock *MBB) const {
408   // Sum block sizes before MBB.
409   unsigned Offset = 0;  
410   for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
411     Offset += BBSizes[BB];
412
413   return Offset;
414 }
415
416 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
417 /// ID.
418 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
419                               const MachineBasicBlock *RHS) {
420   return LHS->getNumber() < RHS->getNumber();
421 }
422
423 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
424 /// machine function, it upsets all of the block numbers.  Renumber the blocks
425 /// and update the arrays that parallel this numbering.
426 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
427   // Renumber the MBB's to keep them consequtive.
428   NewBB->getParent()->RenumberBlocks(NewBB);
429   
430   // Insert a size into BBSizes to align it properly with the (newly
431   // renumbered) block numbers.
432   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
433   
434   // Next, update WaterList.  Specifically, we need to add NewMBB as having 
435   // available water after it.
436   std::vector<MachineBasicBlock*>::iterator IP =
437     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
438                      CompareMBBNumbers);
439   WaterList.insert(IP, NewBB);
440 }
441
442
443 /// Split the basic block containing MI into two blocks, which are joined by
444 /// an unconditional branch.  Update datastructures and renumber blocks to
445 /// account for this change.
446 void ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
447   MachineBasicBlock *OrigBB = MI->getParent();
448   const ARMFunctionInfo *AFI = OrigBB->getParent()->getInfo<ARMFunctionInfo>();
449   bool isThumb = AFI->isThumbFunction();
450
451   // Create a new MBB for the code after the OrigBB.
452   MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
453   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
454   OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
455   
456   // Splice the instructions starting with MI over to NewBB.
457   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
458   
459   // Add an unconditional branch from OrigBB to NewBB.
460   BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
461   NumSplit++;
462   
463   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
464   while (!OrigBB->succ_empty()) {
465     MachineBasicBlock *Succ = *OrigBB->succ_begin();
466     OrigBB->removeSuccessor(Succ);
467     NewBB->addSuccessor(Succ);
468     
469     // This pass should be run after register allocation, so there should be no
470     // PHI nodes to update.
471     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
472            && "PHI nodes should be eliminated by now!");
473   }
474   
475   // OrigBB branches to NewBB.
476   OrigBB->addSuccessor(NewBB);
477   
478   // Update internal data structures to account for the newly inserted MBB.
479   UpdateForInsertedWaterBlock(NewBB);
480   
481   // Figure out how large the first NewMBB is.
482   unsigned NewBBSize = 0;
483   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
484        I != E; ++I)
485     NewBBSize += GetInstSize(I);
486   
487   // Set the size of NewBB in BBSizes.
488   BBSizes[NewBB->getNumber()] = NewBBSize;
489   
490   // We removed instructions from UserMBB, subtract that off from its size.
491   // Add 2 or 4 to the block to count the unconditional branch we added to it.
492   BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
493 }
494
495 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
496 /// is out-of-range.  If so, pick it up the constant pool value and move it some
497 /// place in-range.
498 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
499   MachineInstr *UserMI = U.MI;
500   MachineInstr *CPEMI  = U.CPEMI;
501
502   unsigned UserOffset = GetOffsetOf(UserMI);
503   unsigned CPEOffset  = GetOffsetOf(CPEMI);
504   
505   DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
506                   << " max delta=" << U.MaxDisp
507                   << " at offset " << int(UserOffset-CPEOffset) << "\t"
508                   << *UserMI);
509
510   // Check to see if the CPE is already in-range.
511   if (UserOffset < CPEOffset) {
512     // User before the CPE.
513     if (CPEOffset-UserOffset <= U.MaxDisp)
514       return false;
515   } else {
516     if (UserOffset-CPEOffset <= U.MaxDisp)
517       return false;
518   }
519   
520  
521   // Solution guaranteed to work: split the user's MBB right before the user and
522   // insert a clone the CPE into the newly created water.
523   
524   // If the user isn't at the start of its MBB, or if there is a fall-through
525   // into the user's MBB, split the MBB before the User.
526   MachineBasicBlock *UserMBB = UserMI->getParent();
527   if (&UserMBB->front() != UserMI ||
528       UserMBB == &Fn.front() || // entry MBB of function.
529       BBHasFallthrough(prior(MachineFunction::iterator(UserMBB)))) {
530     // TODO: Search for the best place to split the code.  In practice, using
531     // loop nesting information to insert these guys outside of loops would be
532     // sufficient.    
533     SplitBlockBeforeInstr(UserMI);
534     
535     // UserMI's BB may have changed.
536     UserMBB = UserMI->getParent();
537   }
538   
539   // Okay, we know we can put an island before UserMBB now, do it!
540   MachineBasicBlock *NewIsland = new MachineBasicBlock();
541   Fn.getBasicBlockList().insert(UserMBB, NewIsland);
542
543   // Update internal data structures to account for the newly inserted MBB.
544   UpdateForInsertedWaterBlock(NewIsland);
545
546   // Now that we have an island to add the CPE to, clone the original CPE and
547   // add it to the island.
548   unsigned ID  = NextUID++;
549   unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
550   unsigned Size = CPEMI->getOperand(2).getImm();
551   
552   // Build a new CPE for this user.
553   U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
554                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
555   
556   // Increase the size of the island block to account for the new entry.
557   BBSizes[NewIsland->getNumber()] += Size;
558   
559   // Finally, change the CPI in the instruction operand to be ID.
560   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
561     if (UserMI->getOperand(i).isConstantPoolIndex()) {
562       UserMI->getOperand(i).setConstantPoolIndex(ID);
563       break;
564     }
565       
566   DEBUG(std::cerr << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t"
567                   << *UserMI);
568   
569       
570   return true;
571 }
572
573 /// BBIsInBranchRange - Returns true is the distance between specific MI and
574 /// specific BB can fit in MI's displacement field.
575 bool ARMConstantIslands::BBIsInBranchRange(MachineInstr *MI,
576                                            MachineBasicBlock *DestBB,
577                                            unsigned MaxDisp) {
578   unsigned BrOffset   = GetOffsetOf(MI);
579   unsigned DestOffset = GetOffsetOf(DestBB);
580
581   // Check to see if the destination BB is in range.
582   if (BrOffset < DestOffset) {
583     if (DestOffset - BrOffset < MaxDisp)
584       return true;
585   } else {
586     if (BrOffset - DestOffset <= MaxDisp)
587       return true;
588   }
589   return false;
590 }
591
592 static inline unsigned getUncondBranchDisp(int Opc) {
593   return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
594 }
595
596 /// FixUpImmediateBranch - Fix up immediate branches whose destination is too
597 /// far away to fit in its displacement field. If it is a conditional branch,
598 /// then it is converted to an inverse conditional branch + an unconditional
599 /// branch to the destination. If it is an unconditional branch, then it is
600 /// converted to a branch to a branch.
601 bool
602 ARMConstantIslands::FixUpImmediateBranch(MachineFunction &Fn, ImmBranch &Br) {
603   MachineInstr *MI = Br.MI;
604   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
605
606   if (BBIsInBranchRange(MI, DestBB, Br.MaxDisp))
607     return false;
608
609   if (!Br.isCond) {
610     // Unconditional branch. We have to insert a branch somewhere to perform
611     // a two level branch (branch to branch). FIXME: not yet implemented.
612     assert(false && "Can't handle unconditional branch yet!");
613     return false;
614   }
615
616   // Otherwise, add a unconditional branch to the destination and 
617   // invert the branch condition to jump over it:
618   // blt L1
619   // =>
620   // bge L2
621   // b   L1
622   // L2:
623   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
624   CC = ARMCC::getOppositeCondition(CC);
625
626   // If the branch is at the end of its MBB and that has a fall-through block,
627   // direct the updated conditional branch to the fall-through block. Otherwise,
628   // split the MBB before the next instruction.
629   MachineBasicBlock *MBB = MI->getParent();
630   MachineInstr *BackMI = &MBB->back();
631   bool NeedSplit = (BackMI != MI) || !BBHasFallthrough(MBB);
632
633   if (BackMI != MI) {
634     if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
635         BackMI->getOpcode() == Br.UncondBr) {
636       // Last MI in the BB is a unconditional branch. Can we simply invert the
637       // condition and swap destinations:
638       // beq L1
639       // b   L2
640       // =>
641       // bne L2
642       // b   L1
643       MachineBasicBlock *NewDest = BackMI->getOperand(0).getMachineBasicBlock();
644       if (BBIsInBranchRange(MI, NewDest, Br.MaxDisp)) {
645         BackMI->getOperand(0).setMachineBasicBlock(DestBB);
646         MI->getOperand(0).setMachineBasicBlock(NewDest);
647         MI->getOperand(1).setImm(CC);
648         return true;
649       }
650     }
651   }
652
653   if (NeedSplit) {
654     SplitBlockBeforeInstr(MI);
655     // No need for the branch to the next block. We're adding a unconditional
656     // branch to the destination.
657     MBB->back().eraseFromParent();
658   }
659   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
660
661   // Insert a unconditional branch and replace the conditional branch.
662   // Also update the ImmBranch as well as adding a new entry for the new branch.
663   BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
664   Br.MI = &MBB->back();
665   BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
666   unsigned MaxDisp = getUncondBranchDisp(Br.UncondBr);
667   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
668   MI->eraseFromParent();
669
670   // Increase the size of MBB to account for the new unconditional branch.
671   BBSizes[MBB->getNumber()] += GetInstSize(&MBB->back());
672   return true;
673 }