Some comments.
[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 BBIsInBranchRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned D);
119     bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
120     bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
121     bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
122     bool UndoLRSpillRestore();
123
124     unsigned GetOffsetOf(MachineInstr *MI) const;
125     unsigned GetOffsetOf(MachineBasicBlock *MBB) const;
126   };
127 }
128
129 /// createARMConstantIslandPass - returns an instance of the constpool
130 /// island pass.
131 FunctionPass *llvm::createARMConstantIslandPass() {
132   return new ARMConstantIslands();
133 }
134
135 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
136   MachineConstantPool &MCP = *Fn.getConstantPool();
137   
138   TII = Fn.getTarget().getInstrInfo();
139   AFI = Fn.getInfo<ARMFunctionInfo>();
140
141   HasFarJump = false;
142
143   // 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;
150   if (!MCP.isEmpty())
151     DoInitialPlacement(Fn, CPEMIs);
152   
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   
162   // 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;
167     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
168       Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
169     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
170       Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
171     if (!Change)
172       break;
173     MadeChange = true;
174   }
175   
176   // 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
181   BBSizes.clear();
182   WaterList.clear();
183   CPUsers.clear();
184   ImmBranches.clear();
185
186   return MadeChange;
187 }
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.
191 void 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.
220 static 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.
238 void 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.
253       MBBSize += ARM::GetInstSize(I);
254
255       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) {
262         default:
263           continue;  // Ignore JT branches
264         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;
284         ImmBranches.push_back(ImmBranch(I, MaxDisp, isCond, UOpc));
285       }
286
287       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
288         PushPopMIs.push_back(I);
289
290       // 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;
327           case ARMII::AddrModeTs:
328             MaxOffs = 1 << (8+2);
329             break;
330           }
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
345 /// 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.
348 unsigned 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;
364     Offset += ARM::GetInstSize(I);
365   }
366 }
367
368 /// 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.
371 unsigned 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
380 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
381 /// ID.
382 static 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.
390 void 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
409 /// account for this change and returns the newly created block.
410 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
411   MachineBasicBlock *OrigBB = MI->getParent();
412   bool isThumb = AFI->isThumbFunction();
413
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.
423   // Note the new unconditional branch is not being recorded.
424   BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
425   NumSplit++;
426   
427   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
428   while (!OrigBB->succ_empty()) {
429     MachineBasicBlock *Succ = *OrigBB->succ_begin();
430     OrigBB->removeSuccessor(Succ);
431     NewBB->addSuccessor(Succ);
432     
433     // This pass should be run after register allocation, so there should be no
434     // PHI nodes to update.
435     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
436            && "PHI nodes should be eliminated by now!");
437   }
438   
439   // OrigBB branches to NewBB.
440   OrigBB->addSuccessor(NewBB);
441   
442   // Update internal data structures to account for the newly inserted MBB.
443   UpdateForInsertedWaterBlock(NewBB);
444   
445   // Figure out how large the first NewMBB is.
446   unsigned NewBBSize = 0;
447   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
448        I != E; ++I)
449     NewBBSize += ARM::GetInstSize(I);
450   
451   // Set the size of NewBB in BBSizes.
452   BBSizes[NewBB->getNumber()] = NewBBSize;
453   
454   // We removed instructions from UserMBB, subtract that off from its size.
455   // Add 2 or 4 to the block to count the unconditional branch we added to it.
456   BBSizes[OrigBB->getNumber()] -= NewBBSize - (isThumb ? 2 : 4);
457
458   return NewBB;
459 }
460
461 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
462 /// is out-of-range.  If so, pick it up the constant pool value and move it some
463 /// place in-range.
464 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
465   bool isThumb = AFI->isThumbFunction();
466   MachineInstr *UserMI = U.MI;
467   MachineInstr *CPEMI  = U.CPEMI;
468
469   unsigned UserOffset = GetOffsetOf(UserMI);
470   unsigned CPEOffset  = GetOffsetOf(CPEMI);
471   
472   DEBUG(std::cerr << "User of CPE#" << CPEMI->getOperand(0).getImm()
473                   << " max delta=" << U.MaxDisp
474                   << " at offset " << int(UserOffset-CPEOffset) << "\t"
475                   << *UserMI);
476
477   // Check to see if the CPE is already in-range.
478   if (UserOffset < CPEOffset) {
479     // User before the CPE.
480     if (CPEOffset-UserOffset <= U.MaxDisp)
481       return false;
482   } else if (!isThumb) {
483     // Thumb LDR cannot encode negative offset.
484     if (UserOffset-CPEOffset <= U.MaxDisp)
485       return false;
486   }
487   
488
489   // Solution guaranteed to work: split the user's MBB right after the user and
490   // insert a clone the CPE into the newly created water.
491
492   MachineBasicBlock *UserMBB = UserMI->getParent();
493   MachineBasicBlock *NewMBB;
494
495   // TODO: Search for the best place to split the code.  In practice, using
496   // loop nesting information to insert these guys outside of loops would be
497   // sufficient.    
498   if (&UserMBB->back() == UserMI) {
499     assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
500     NewMBB = next(MachineFunction::iterator(UserMBB));
501     // Add an unconditional branch from UserMBB to fallthrough block.
502     // Note the new unconditional branch is not being recorded.
503     BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
504     BBSizes[UserMBB->getNumber()] += isThumb ? 2 : 4;
505   } else {
506     MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
507     NewMBB = SplitBlockBeforeInstr(NextMI);
508   }
509
510   // Okay, we know we can put an island before UserMBB now, do it!
511   MachineBasicBlock *NewIsland = new MachineBasicBlock();
512   Fn.getBasicBlockList().insert(NewMBB, NewIsland);
513
514   // Update internal data structures to account for the newly inserted MBB.
515   UpdateForInsertedWaterBlock(NewIsland);
516
517   // Now that we have an island to add the CPE to, clone the original CPE and
518   // add it to the island.
519   unsigned ID  = NextUID++;
520   unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
521   unsigned Size = CPEMI->getOperand(2).getImm();
522   
523   // Build a new CPE for this user.
524   U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
525                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
526   
527   // Increase the size of the island block to account for the new entry.
528   BBSizes[NewIsland->getNumber()] += Size;
529   
530   // Finally, change the CPI in the instruction operand to be ID.
531   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
532     if (UserMI->getOperand(i).isConstantPoolIndex()) {
533       UserMI->getOperand(i).setConstantPoolIndex(ID);
534       break;
535     }
536       
537   DEBUG(std::cerr << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t"
538                   << *UserMI);
539       
540   return true;
541 }
542
543 /// BBIsInBranchRange - Returns true is the distance between specific MI and
544 /// specific BB can fit in MI's displacement field.
545 bool ARMConstantIslands::BBIsInBranchRange(MachineInstr *MI,
546                                            MachineBasicBlock *DestBB,
547                                            unsigned MaxDisp) {
548   unsigned BrOffset   = GetOffsetOf(MI);
549   unsigned DestOffset = GetOffsetOf(DestBB);
550
551   // Check to see if the destination BB is in range.
552   if (BrOffset < DestOffset) {
553     if (DestOffset - BrOffset < MaxDisp)
554       return true;
555   } else {
556     if (BrOffset - DestOffset <= MaxDisp)
557       return true;
558   }
559   return false;
560 }
561
562 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
563 /// away to fit in its displacement field.
564 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
565   MachineInstr *MI = Br.MI;
566   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
567
568   if (BBIsInBranchRange(MI, DestBB, Br.MaxDisp))
569     return false;
570
571   if (!Br.isCond)
572     return FixUpUnconditionalBr(Fn, Br);
573   return FixUpConditionalBr(Fn, Br);
574 }
575
576 /// FixUpUnconditionalBr - Fix up an unconditional branches whose destination is
577 /// too far away to fit in its displacement field. If LR register has been
578 /// spilled in the epilogue, then we can use BL to implement a far jump.
579 /// Otherwise, add a intermediate branch instruction to to a branch.
580 bool
581 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
582   MachineInstr *MI = Br.MI;
583   MachineBasicBlock *MBB = MI->getParent();
584   assert(AFI->isThumbFunction() && "Expected a Thumb function!");
585
586   // Use BL to implement far jump.
587   Br.MaxDisp = (1 << 21) * 2;
588   MI->setInstrDescriptor(TII->get(ARM::tBfar));
589   BBSizes[MBB->getNumber()] += 2;
590   HasFarJump = true;
591   NumUBrFixed++;
592   return true;
593 }
594
595 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in the
596 /// specific unconditional branch instruction.
597 static inline unsigned getUnconditionalBrDisp(int Opc) {
598   return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
599 }
600
601 /// FixUpConditionalBr - Fix up a conditional branches whose destination is too
602 /// far away to fit in its displacement field. It is converted to an inverse
603 /// conditional branch + an unconditional branch to the destination.
604 bool
605 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
606   MachineInstr *MI = Br.MI;
607   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
608
609   // Add a unconditional branch to the destination and invert the branch
610   // condition to jump over it:
611   // blt L1
612   // =>
613   // bge L2
614   // b   L1
615   // L2:
616   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
617   CC = ARMCC::getOppositeCondition(CC);
618
619   // If the branch is at the end of its MBB and that has a fall-through block,
620   // direct the updated conditional branch to the fall-through block. Otherwise,
621   // split the MBB before the next instruction.
622   MachineBasicBlock *MBB = MI->getParent();
623   MachineInstr *BackMI = &MBB->back();
624   bool NeedSplit = (BackMI != MI) || !BBHasFallthrough(MBB);
625
626   NumCBrFixed++;
627   if (BackMI != MI) {
628     if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
629         BackMI->getOpcode() == Br.UncondBr) {
630       // Last MI in the BB is a unconditional branch. Can we simply invert the
631       // condition and swap destinations:
632       // beq L1
633       // b   L2
634       // =>
635       // bne L2
636       // b   L1
637       MachineBasicBlock *NewDest = BackMI->getOperand(0).getMachineBasicBlock();
638       if (BBIsInBranchRange(MI, NewDest, Br.MaxDisp)) {
639         BackMI->getOperand(0).setMachineBasicBlock(DestBB);
640         MI->getOperand(0).setMachineBasicBlock(NewDest);
641         MI->getOperand(1).setImm(CC);
642         return true;
643       }
644     }
645   }
646
647   if (NeedSplit) {
648     SplitBlockBeforeInstr(MI);
649     // No need for the branch to the next block. We're adding a unconditional
650     // branch to the destination.
651     MBB->back().eraseFromParent();
652   }
653   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
654
655   // Insert a unconditional branch and replace the conditional branch.
656   // Also update the ImmBranch as well as adding a new entry for the new branch.
657   BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
658   Br.MI = &MBB->back();
659   BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
660   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
661   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
662   MI->eraseFromParent();
663
664   // Increase the size of MBB to account for the new unconditional branch.
665   BBSizes[MBB->getNumber()] += ARM::GetInstSize(&MBB->back());
666   return true;
667 }
668
669
670 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
671 /// LR / restores LR to pc.
672 bool ARMConstantIslands::UndoLRSpillRestore() {
673   bool MadeChange = false;
674   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
675     MachineInstr *MI = PushPopMIs[i];
676     if (MI->getNumOperands() == 1) {
677         if (MI->getOpcode() == ARM::tPOP_RET &&
678             MI->getOperand(0).getReg() == ARM::PC)
679           BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
680         MI->eraseFromParent();
681         MadeChange = true;
682     }
683   }
684   return MadeChange;
685 }