35066faf554cac566464077913e7f9b80521eca8
[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/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>
30 using namespace llvm;
31
32 STATISTIC(NumSplit,    "Number of uncond branches inserted");
33 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
34 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
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     /// 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
101     const TargetInstrInfo *TII;
102     const ARMFunctionInfo *AFI;
103   public:
104     virtual bool runOnMachineFunction(MachineFunction &Fn);
105
106     virtual const char *getPassName() const {
107       return "ARM constant island placement and branch shortening pass";
108     }
109     
110   private:
111     void DoInitialPlacement(MachineFunction &Fn,
112                             std::vector<MachineInstr*> &CPEMIs);
113     void InitialFunctionScan(MachineFunction &Fn,
114                              const std::vector<MachineInstr*> &CPEMIs);
115     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
116     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
117     bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
118     bool CPEIsInRange(MachineInstr *MI, MachineInstr *CPEMI, unsigned Disp);
119     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
120     bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
121     bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
122     bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
123     bool UndoLRSpillRestore();
124
125     unsigned GetOffsetOf(MachineInstr *MI) const;
126     unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
127   };
128 }
129
130 /// createARMConstantIslandPass - returns an instance of the constpool
131 /// island pass.
132 FunctionPass *llvm::createARMConstantIslandPass() {
133   return new ARMConstantIslands();
134 }
135
136 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
137   MachineConstantPool &MCP = *Fn.getConstantPool();
138   
139   TII = Fn.getTarget().getInstrInfo();
140   AFI = Fn.getInfo<ARMFunctionInfo>();
141
142   HasFarJump = false;
143
144   // Renumber all of the machine basic blocks in the function, guaranteeing that
145   // the numbers agree with the position of the block in the function.
146   Fn.RenumberBlocks();
147
148   // Perform the initial placement of the constant pool entries.  To start with,
149   // we put them all at the end of the function.
150   std::vector<MachineInstr*> CPEMIs;
151   if (!MCP.isEmpty())
152     DoInitialPlacement(Fn, CPEMIs);
153   
154   /// The next UID to take is the first unused one.
155   NextUID = CPEMIs.size();
156   
157   // Do the initial scan of the function, building up information about the
158   // sizes of each block, the location of all the water, and finding all of the
159   // constant pool users.
160   InitialFunctionScan(Fn, CPEMIs);
161   CPEMIs.clear();
162   
163   // Iteratively place constant pool entries and fix up branches until there
164   // is no change.
165   bool MadeChange = false;
166   while (true) {
167     bool Change = false;
168     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
169       Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
170     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
171       Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
172     if (!Change)
173       break;
174     MadeChange = true;
175   }
176   
177   // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
178   // Undo the spill / restore of LR if possible.
179   if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
180     MadeChange |= UndoLRSpillRestore();
181
182   BBSizes.clear();
183   WaterList.clear();
184   CPUsers.clear();
185   ImmBranches.clear();
186
187   return MadeChange;
188 }
189
190 /// DoInitialPlacement - Perform the initial placement of the constant pool
191 /// entries.  To start with, we put them all at the end of the function.
192 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
193                                             std::vector<MachineInstr*> &CPEMIs){
194   // Create the basic block to hold the CPE's.
195   MachineBasicBlock *BB = new MachineBasicBlock();
196   Fn.getBasicBlockList().push_back(BB);
197   
198   // Add all of the constants from the constant pool to the end block, use an
199   // identity mapping of CPI's to CPE's.
200   const std::vector<MachineConstantPoolEntry> &CPs =
201     Fn.getConstantPool()->getConstants();
202   
203   const TargetData &TD = *Fn.getTarget().getTargetData();
204   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
205     unsigned Size = TD.getTypeSize(CPs[i].getType());
206     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
207     // we would have to pad them out or something so that instructions stay
208     // aligned.
209     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
210     MachineInstr *CPEMI =
211       BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
212                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
213     CPEMIs.push_back(CPEMI);
214     DEBUG(std::cerr << "Moved CPI#" << i << " to end of function as #"
215                     << i << "\n");
216   }
217 }
218
219 /// BBHasFallthrough - Return true of the specified basic block can fallthrough
220 /// into the block immediately after it.
221 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
222   // Get the next machine basic block in the function.
223   MachineFunction::iterator MBBI = MBB;
224   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
225     return false;
226   
227   MachineBasicBlock *NextBB = next(MBBI);
228   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
229        E = MBB->succ_end(); I != E; ++I)
230     if (*I == NextBB)
231       return true;
232   
233   return false;
234 }
235
236 /// InitialFunctionScan - Do the initial scan of the function, building up
237 /// information about the sizes of each block, the location of all the water,
238 /// and finding all of the constant pool users.
239 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
240                                      const std::vector<MachineInstr*> &CPEMIs) {
241   for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
242        MBBI != E; ++MBBI) {
243     MachineBasicBlock &MBB = *MBBI;
244     
245     // If this block doesn't fall through into the next MBB, then this is
246     // 'water' that a constant pool island could be placed.
247     if (!BBHasFallthrough(&MBB))
248       WaterList.push_back(&MBB);
249     
250     unsigned MBBSize = 0;
251     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
252          I != E; ++I) {
253       // Add instruction size to MBBSize.
254       MBBSize += ARM::GetInstSize(I);
255
256       int Opc = I->getOpcode();
257       if (TII->isBranch(Opc)) {
258         bool isCond = false;
259         unsigned Bits = 0;
260         unsigned Scale = 1;
261         int UOpc = Opc;
262         switch (Opc) {
263         default:
264           continue;  // Ignore JT branches
265         case ARM::Bcc:
266           isCond = true;
267           UOpc = ARM::B;
268           // Fallthrough
269         case ARM::B:
270           Bits = 24;
271           Scale = 4;
272           break;
273         case ARM::tBcc:
274           isCond = true;
275           UOpc = ARM::tB;
276           Bits = 8;
277           Scale = 2;
278           break;
279         case ARM::tB:
280           Bits = 11;
281           Scale = 2;
282           break;
283         }
284
285         // Record this immediate branch.
286         unsigned MaxOffs = (1 << (Bits-1)) * Scale;
287         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
288       }
289
290       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
291         PushPopMIs.push_back(I);
292
293       // Scan the instructions for constant pool operands.
294       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
295         if (I->getOperand(op).isConstantPoolIndex()) {
296           // We found one.  The addressing mode tells us the max displacement
297           // from the PC that this instruction permits.
298           
299           // Basic size info comes from the TSFlags field.
300           unsigned Bits = 0;
301           unsigned Scale = 1;
302           unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
303           switch (TSFlags & ARMII::AddrModeMask) {
304           default: 
305             // Constant pool entries can reach anything.
306             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
307               continue;
308             assert(0 && "Unknown addressing mode for CP reference!");
309           case ARMII::AddrMode1: // AM1: 8 bits << 2
310             Bits = 8;
311             Scale = 4;  // Taking the address of a CP entry.
312             break;
313           case ARMII::AddrMode2:
314             Bits = 12;  // +-offset_12
315             break;
316           case ARMII::AddrMode3:
317             Bits = 8;   // +-offset_8
318             break;
319             // addrmode4 has no immediate offset.
320           case ARMII::AddrMode5:
321             Bits = 8;
322             Scale = 4;  // +-(offset_8*4)
323             break;
324           case ARMII::AddrModeT1:
325             Bits = 5;  // +offset_5
326             break;
327           case ARMII::AddrModeT2:
328             Bits = 5;
329             Scale = 2;  // +(offset_5*2)
330             break;
331           case ARMII::AddrModeT4:
332             Bits = 5;
333             Scale = 4;  // +(offset_5*4)
334             break;
335           case ARMII::AddrModeTs:
336             Bits = 8;
337             Scale = 4;  // +(offset_8*4)
338             break;
339           }
340
341           // Remember that this is a user of a CP entry.
342           MachineInstr *CPEMI =CPEMIs[I->getOperand(op).getConstantPoolIndex()];
343           unsigned MaxOffs = ((1 << Bits)-1) * Scale;          
344           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
345           
346           // Instructions can only use one CP entry, don't bother scanning the
347           // rest of the operands.
348           break;
349         }
350     }
351
352     // In thumb mode, if this block is a constpool island, pessmisticly assume
353     // it needs to be padded by two byte so it's aligned on 4 byte boundary.
354     if (AFI->isThumbFunction() &&
355         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
356       MBBSize += 2;
357
358     BBSizes.push_back(MBBSize);
359   }
360 }
361
362 /// GetOffsetOf - Return the current offset of the specified machine instruction
363 /// from the start of the function.  This offset changes as stuff is moved
364 /// around inside the function.
365 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
366   MachineBasicBlock *MBB = MI->getParent();
367   
368   // The offset is composed of two things: the sum of the sizes of all MBB's
369   // before this instruction's block, and the offset from the start of the block
370   // it is in.
371   unsigned Offset = 0;
372   
373   // Sum block sizes before MBB.
374   for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
375     Offset += BBSizes[BB];
376
377   // Sum instructions before MI in MBB.
378   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
379     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
380     if (&*I == MI) return Offset;
381     Offset += ARM::GetInstSize(I);
382   }
383 }
384
385 /// GetOffsetOf - Return the current offset of the specified machine BB
386 /// from the start of the function.  This offset changes as stuff is moved
387 /// around inside the function.
388 unsigned ARMConstantIslands::GetOffsetOf(MachineBasicBlock *MBB) const {
389   // Sum block sizes before MBB.
390   unsigned Offset = 0;  
391   for (unsigned BB = 0, e = MBB->getNumber(); BB != e; ++BB)
392     Offset += BBSizes[BB];
393
394   return Offset;
395 }
396
397 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
398 /// ID.
399 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
400                               const MachineBasicBlock *RHS) {
401   return LHS->getNumber() < RHS->getNumber();
402 }
403
404 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
405 /// machine function, it upsets all of the block numbers.  Renumber the blocks
406 /// and update the arrays that parallel this numbering.
407 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
408   // Renumber the MBB's to keep them consequtive.
409   NewBB->getParent()->RenumberBlocks(NewBB);
410   
411   // Insert a size into BBSizes to align it properly with the (newly
412   // renumbered) block numbers.
413   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
414   
415   // Next, update WaterList.  Specifically, we need to add NewMBB as having 
416   // available water after it.
417   std::vector<MachineBasicBlock*>::iterator IP =
418     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
419                      CompareMBBNumbers);
420   WaterList.insert(IP, NewBB);
421 }
422
423
424 /// Split the basic block containing MI into two blocks, which are joined by
425 /// an unconditional branch.  Update datastructures and renumber blocks to
426 /// account for this change and returns the newly created block.
427 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
428   MachineBasicBlock *OrigBB = MI->getParent();
429   bool isThumb = AFI->isThumbFunction();
430
431   // Create a new MBB for the code after the OrigBB.
432   MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
433   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
434   OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
435   
436   // Splice the instructions starting with MI over to NewBB.
437   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
438   
439   // Add an unconditional branch from OrigBB to NewBB.
440   // Note the new unconditional branch is not being recorded.
441   BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
442   NumSplit++;
443   
444   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
445   while (!OrigBB->succ_empty()) {
446     MachineBasicBlock *Succ = *OrigBB->succ_begin();
447     OrigBB->removeSuccessor(Succ);
448     NewBB->addSuccessor(Succ);
449     
450     // This pass should be run after register allocation, so there should be no
451     // PHI nodes to update.
452     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
453            && "PHI nodes should be eliminated by now!");
454   }
455   
456   // OrigBB branches to NewBB.
457   OrigBB->addSuccessor(NewBB);
458   
459   // Update internal data structures to account for the newly inserted MBB.
460   UpdateForInsertedWaterBlock(NewBB);
461   
462   // Figure out how large the first NewMBB is.
463   unsigned NewBBSize = 0;
464   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
465        I != E; ++I)
466     NewBBSize += ARM::GetInstSize(I);
467   
468   // Set the size of NewBB in BBSizes.
469   BBSizes[NewBB->getNumber()] = NewBBSize;
470   
471   // We removed instructions from UserMBB, subtract that off from its size.
472   // Add 2 or 4 to the block to count the unconditional branch we added to it.
473   BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
474
475   return NewBB;
476 }
477
478 /// CPEIsInRange - Returns true is the distance between specific MI and
479 /// specific ConstPool entry instruction can fit in MI's displacement field.
480 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, MachineInstr *CPEMI,
481                                       unsigned MaxDisp) {
482   unsigned PCAdj      = AFI->isThumbFunction() ? 4 : 8;
483   unsigned UserOffset = GetOffsetOf(MI) + PCAdj;
484   // In thumb mode, pessmisticly assumes the .align 2 before the first CPE
485   // in the island adds two byte padding.
486   unsigned AlignAdj   = AFI->isThumbFunction() ? 2 : 0;
487   unsigned CPEOffset  = GetOffsetOf(CPEMI) + AlignAdj;
488
489   DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
490                   << " max delta=" << MaxDisp
491                   << " at offset " << int(UserOffset-CPEOffset) << "\t"
492                   << *MI);
493
494   if (UserOffset <= CPEOffset) {
495     // User before the CPE.
496     if (CPEOffset-UserOffset <= MaxDisp)
497       return true;
498   } else if (!AFI->isThumbFunction()) {
499     // Thumb LDR cannot encode negative offset.
500     if (UserOffset-CPEOffset <= MaxDisp)
501       return true;
502   }
503   return false;
504 }
505
506 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
507 /// is out-of-range.  If so, pick it up the constant pool value and move it some
508 /// place in-range.
509 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
510   MachineInstr *UserMI = U.MI;
511   MachineInstr *CPEMI  = U.CPEMI;
512
513   // Check to see if the CPE is already in-range.
514   if (CPEIsInRange(UserMI, CPEMI, U.MaxDisp))
515     return false;
516
517   // Solution guaranteed to work: split the user's MBB right after the user and
518   // insert a clone the CPE into the newly created water.
519
520   MachineBasicBlock *UserMBB = UserMI->getParent();
521   MachineBasicBlock *NewMBB;
522
523   // TODO: Search for the best place to split the code.  In practice, using
524   // loop nesting information to insert these guys outside of loops would be
525   // sufficient.    
526   bool isThumb = AFI->isThumbFunction();
527   if (&UserMBB->back() == UserMI) {
528     assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
529     NewMBB = next(MachineFunction::iterator(UserMBB));
530     // Add an unconditional branch from UserMBB to fallthrough block.
531     // Note the new unconditional branch is not being recorded.
532     BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
533     BBSizes[UserMBB->getNumber()] += isThumb ? 2 : 4;
534   } else {
535     MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
536     NewMBB = SplitBlockBeforeInstr(NextMI);
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(NewMBB, 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   // Compensate for .align 2 in thumb mode.
557   if (isThumb) Size += 2;  
558   // Increase the size of the island block to account for the new entry.
559   BBSizes[NewIsland->getNumber()] += Size;
560   
561   // Finally, change the CPI in the instruction operand to be ID.
562   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
563     if (UserMI->getOperand(i).isConstantPoolIndex()) {
564       UserMI->getOperand(i).setConstantPoolIndex(ID);
565       break;
566     }
567       
568   DEBUG(std::cerr << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t"
569                   << *UserMI);
570       
571   return true;
572 }
573
574 /// BBIsInRange - Returns true is the distance between specific MI and
575 /// specific BB can fit in MI's displacement field.
576 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
577                                      unsigned MaxDisp) {
578   unsigned PCAdj      = AFI->isThumbFunction() ? 4 : 8;
579   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
580   unsigned DestOffset = GetOffsetOf(DestBB);
581
582   DEBUG(std::cerr << "Branch of destination BB#" << DestBB->getNumber()
583                   << " max delta=" << MaxDisp
584                   << " at offset " << int(BrOffset-DestOffset) << "\t"
585                   << *MI);
586
587   if (BrOffset <= DestOffset) {
588     if (DestOffset - BrOffset <= MaxDisp)
589       return true;
590   } else {
591     if (BrOffset - DestOffset <= MaxDisp)
592       return true;
593   }
594   return false;
595 }
596
597 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
598 /// away to fit in its displacement field.
599 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
600   MachineInstr *MI = Br.MI;
601   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
602
603   // Check to see if the DestBB is already in-range.
604   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
605     return false;
606
607   if (!Br.isCond)
608     return FixUpUnconditionalBr(Fn, Br);
609   return FixUpConditionalBr(Fn, Br);
610 }
611
612 /// FixUpUnconditionalBr - Fix up an unconditional branches whose destination is
613 /// too far away to fit in its displacement field. If LR register has been
614 /// spilled in the epilogue, then we can use BL to implement a far jump.
615 /// Otherwise, add a intermediate branch instruction to to a branch.
616 bool
617 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
618   MachineInstr *MI = Br.MI;
619   MachineBasicBlock *MBB = MI->getParent();
620   assert(AFI->isThumbFunction() && "Expected a Thumb function!");
621
622   // Use BL to implement far jump.
623   Br.MaxDisp = (1 << 21) * 2;
624   MI->setInstrDescriptor(TII->get(ARM::tBfar));
625   BBSizes[MBB->getNumber()] += 2;
626   HasFarJump = true;
627   NumUBrFixed++;
628   return true;
629 }
630
631 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in the
632 /// specific unconditional branch instruction.
633 static inline unsigned getUnconditionalBrDisp(int Opc) {
634   return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
635 }
636
637 /// FixUpConditionalBr - Fix up a conditional branches whose destination is too
638 /// far away to fit in its displacement field. It is converted to an inverse
639 /// conditional branch + an unconditional branch to the destination.
640 bool
641 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
642   MachineInstr *MI = Br.MI;
643   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
644
645   // Add a unconditional branch to the destination and invert the branch
646   // condition to jump over it:
647   // blt L1
648   // =>
649   // bge L2
650   // b   L1
651   // L2:
652   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
653   CC = ARMCC::getOppositeCondition(CC);
654
655   // If the branch is at the end of its MBB and that has a fall-through block,
656   // direct the updated conditional branch to the fall-through block. Otherwise,
657   // split the MBB before the next instruction.
658   MachineBasicBlock *MBB = MI->getParent();
659   MachineInstr *BackMI = &MBB->back();
660   bool NeedSplit = (BackMI != MI) || !BBHasFallthrough(MBB);
661
662   NumCBrFixed++;
663   if (BackMI != MI) {
664     if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
665         BackMI->getOpcode() == Br.UncondBr) {
666       // Last MI in the BB is a unconditional branch. Can we simply invert the
667       // condition and swap destinations:
668       // beq L1
669       // b   L2
670       // =>
671       // bne L2
672       // b   L1
673       MachineBasicBlock *NewDest = BackMI->getOperand(0).getMachineBasicBlock();
674       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
675         BackMI->getOperand(0).setMachineBasicBlock(DestBB);
676         MI->getOperand(0).setMachineBasicBlock(NewDest);
677         MI->getOperand(1).setImm(CC);
678         return true;
679       }
680     }
681   }
682
683   if (NeedSplit) {
684     SplitBlockBeforeInstr(MI);
685     // No need for the branch to the next block. We're adding a unconditional
686     // branch to the destination.
687     MBB->back().eraseFromParent();
688   }
689   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
690
691   // Insert a unconditional branch and replace the conditional branch.
692   // Also update the ImmBranch as well as adding a new entry for the new branch.
693   BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
694   Br.MI = &MBB->back();
695   BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
696   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
697   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
698   MI->eraseFromParent();
699
700   // Increase the size of MBB to account for the new unconditional branch.
701   BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
702   return true;
703 }
704
705
706 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
707 /// LR / restores LR to pc.
708 bool ARMConstantIslands::UndoLRSpillRestore() {
709   bool MadeChange = false;
710   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
711     MachineInstr *MI = PushPopMIs[i];
712     if (MI->getNumOperands() == 1) {
713         if (MI->getOpcode() == ARM::tPOP_RET &&
714             MI->getOperand(0).getReg() == ARM::PC)
715           BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
716         MI->eraseFromParent();
717         MadeChange = true;
718     }
719   }
720   return MadeChange;
721 }