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