422e0e4cb71f7a14ba181b76683e87f4bb78bac5
[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/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
30 using namespace llvm;
31
32 STATISTIC(NumCPEs,     "Number of constpool entries");
33 STATISTIC(NumSplit,    "Number of uncond branches inserted");
34 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
36
37 namespace {
38   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39   /// requires constant pool entries to be scattered among the instructions
40   /// inside a function.  To do this, it completely ignores the normal LLVM
41   /// constant pool; instead, it places constants wherever it feels like with
42   /// special instructions.
43   ///
44   /// The terminology used in this pass includes:
45   ///   Islands - Clumps of constants placed in the function.
46   ///   Water   - Potential places where an island could be formed.
47   ///   CPE     - A constant pool entry that has been placed somewhere, which
48   ///             tracks a list of users.
49   class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50     /// NextUID - Assign unique ID's to CPE's.
51     unsigned NextUID;
52
53     /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
54     /// by MBB Number.
55     std::vector<unsigned> BBSizes;
56     
57     /// BBOffsets - the offset of each MBB in bytes, starting from 0.
58     std::vector<unsigned> BBOffsets;
59
60     /// WaterList - A sorted list of basic blocks where islands could be placed
61     /// (i.e. blocks that don't fall through to the following block, due
62     /// to a return, unreachable, or unconditional branch).
63     std::vector<MachineBasicBlock*> WaterList;
64
65     /// CPUser - One user of a constant pool, keeping the machine instruction
66     /// pointer, the constant pool being referenced, and the max displacement
67     /// allowed from the instruction to the CP.
68     struct CPUser {
69       MachineInstr *MI;
70       MachineInstr *CPEMI;
71       unsigned MaxDisp;
72       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
73         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
74     };
75     
76     /// CPUsers - Keep track of all of the machine instructions that use various
77     /// constant pools and their max displacement.
78     std::vector<CPUser> CPUsers;
79     
80     /// CPEntry - One per constant pool entry, keeping the machine instruction
81     /// pointer, the constpool index, and the number of CPUser's which
82     /// reference this entry.
83     struct CPEntry {
84       MachineInstr *CPEMI;
85       unsigned CPI;
86       unsigned RefCount;
87       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
88         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
89     };
90
91     /// CPEntries - Keep track of all of the constant pool entry machine
92     /// instructions. For each original constpool index (i.e. those that
93     /// existed upon entry to this pass), it keeps a vector of entries.
94     /// Original elements are cloned as we go along; the clones are
95     /// put in the vector of the original element, but have distinct CPIs.
96     std::vector<std::vector<CPEntry> > CPEntries;
97     
98     /// ImmBranch - One per immediate branch, keeping the machine instruction
99     /// pointer, conditional or unconditional, the max displacement,
100     /// and (if isCond is true) the corresponding unconditional branch
101     /// opcode.
102     struct ImmBranch {
103       MachineInstr *MI;
104       unsigned MaxDisp : 31;
105       bool isCond : 1;
106       int UncondBr;
107       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
108         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
109     };
110
111     /// Branches - Keep track of all the immediate branch instructions.
112     ///
113     std::vector<ImmBranch> ImmBranches;
114
115     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
116     ///
117     SmallVector<MachineInstr*, 4> PushPopMIs;
118
119     /// HasFarJump - True if any far jump instruction has been emitted during
120     /// the branch fix up pass.
121     bool HasFarJump;
122
123     const TargetInstrInfo *TII;
124     const ARMFunctionInfo *AFI;
125   public:
126     virtual bool runOnMachineFunction(MachineFunction &Fn);
127
128     virtual const char *getPassName() const {
129       return "ARM constant island placement and branch shortening pass";
130     }
131     
132   private:
133     void DoInitialPlacement(MachineFunction &Fn,
134                             std::vector<MachineInstr*> &CPEMIs);
135     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
136     void InitialFunctionScan(MachineFunction &Fn,
137                              const std::vector<MachineInstr*> &CPEMIs);
138     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
139     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
140     void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
141     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI, unsigned Size);
142     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
143     bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
144     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset, 
145                       MachineInstr *CPEMI, unsigned Disp,
146                       bool DoDump);
147     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
148                         unsigned Disp);
149     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
150                         unsigned Disp, bool NegativeOK);
151     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
152     bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
153     bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
154     bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
155     bool UndoLRSpillRestore();
156
157     unsigned GetOffsetOf(MachineInstr *MI) const;
158   };
159 }
160
161 /// createARMConstantIslandPass - returns an instance of the constpool
162 /// island pass.
163 FunctionPass *llvm::createARMConstantIslandPass() {
164   return new ARMConstantIslands();
165 }
166
167 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
168   MachineConstantPool &MCP = *Fn.getConstantPool();
169   
170   TII = Fn.getTarget().getInstrInfo();
171   AFI = Fn.getInfo<ARMFunctionInfo>();
172
173   HasFarJump = false;
174
175   // Renumber all of the machine basic blocks in the function, guaranteeing that
176   // the numbers agree with the position of the block in the function.
177   Fn.RenumberBlocks();
178
179   // Perform the initial placement of the constant pool entries.  To start with,
180   // we put them all at the end of the function.
181   std::vector<MachineInstr*> CPEMIs;
182   if (!MCP.isEmpty())
183     DoInitialPlacement(Fn, CPEMIs);
184   
185   /// The next UID to take is the first unused one.
186   NextUID = CPEMIs.size();
187   
188   // Do the initial scan of the function, building up information about the
189   // sizes of each block, the location of all the water, and finding all of the
190   // constant pool users.
191   InitialFunctionScan(Fn, CPEMIs);
192   CPEMIs.clear();
193   
194   // Iteratively place constant pool entries and fix up branches until there
195   // is no change.
196   bool MadeChange = false;
197   while (true) {
198     bool Change = false;
199     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
200       Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
201     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
202       Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
203     if (!Change)
204       break;
205     MadeChange = true;
206   }
207   
208   // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
209   // Undo the spill / restore of LR if possible.
210   if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
211     MadeChange |= UndoLRSpillRestore();
212
213   BBSizes.clear();
214   BBOffsets.clear();
215   WaterList.clear();
216   CPUsers.clear();
217   CPEntries.clear();
218   ImmBranches.clear();
219   PushPopMIs.clear();
220
221   return MadeChange;
222 }
223
224 /// DoInitialPlacement - Perform the initial placement of the constant pool
225 /// entries.  To start with, we put them all at the end of the function.
226 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
227                                         std::vector<MachineInstr*> &CPEMIs){
228   // Create the basic block to hold the CPE's.
229   MachineBasicBlock *BB = new MachineBasicBlock();
230   Fn.getBasicBlockList().push_back(BB);
231   
232   // Add all of the constants from the constant pool to the end block, use an
233   // identity mapping of CPI's to CPE's.
234   const std::vector<MachineConstantPoolEntry> &CPs =
235     Fn.getConstantPool()->getConstants();
236   
237   const TargetData &TD = *Fn.getTarget().getTargetData();
238   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
239     unsigned Size = TD.getTypeSize(CPs[i].getType());
240     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
241     // we would have to pad them out or something so that instructions stay
242     // aligned.
243     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
244     MachineInstr *CPEMI =
245       BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
246                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
247     CPEMIs.push_back(CPEMI);
248
249     // Add a new CPEntry, but no corresponding CPUser yet.
250     std::vector<CPEntry> CPEs;
251     CPEs.push_back(CPEntry(CPEMI, i));
252     CPEntries.push_back(CPEs);
253     NumCPEs++;
254     DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
255   }
256 }
257
258 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
259 /// into the block immediately after it.
260 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
261   // Get the next machine basic block in the function.
262   MachineFunction::iterator MBBI = MBB;
263   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
264     return false;
265   
266   MachineBasicBlock *NextBB = next(MBBI);
267   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
268        E = MBB->succ_end(); I != E; ++I)
269     if (*I == NextBB)
270       return true;
271   
272   return false;
273 }
274
275 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
276 /// look up the corresponding CPEntry.
277 ARMConstantIslands::CPEntry
278 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
279                                         const MachineInstr *CPEMI) {
280   std::vector<CPEntry> &CPEs = CPEntries[CPI];
281   // Number of entries per constpool index should be small, just do a
282   // linear search.
283   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
284     if (CPEs[i].CPEMI == CPEMI)
285       return &CPEs[i];
286   }
287   return NULL;
288 }
289
290 /// InitialFunctionScan - Do the initial scan of the function, building up
291 /// information about the sizes of each block, the location of all the water,
292 /// and finding all of the constant pool users.
293 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
294                                  const std::vector<MachineInstr*> &CPEMIs) {
295   unsigned Offset = 0;
296   for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
297        MBBI != E; ++MBBI) {
298     MachineBasicBlock &MBB = *MBBI;
299     
300     // If this block doesn't fall through into the next MBB, then this is
301     // 'water' that a constant pool island could be placed.
302     if (!BBHasFallthrough(&MBB))
303       WaterList.push_back(&MBB);
304     
305     unsigned MBBSize = 0;
306     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
307          I != E; ++I) {
308       // Add instruction size to MBBSize.
309       MBBSize += ARM::GetInstSize(I);
310
311       int Opc = I->getOpcode();
312       if (TII->isBranch(Opc)) {
313         bool isCond = false;
314         unsigned Bits = 0;
315         unsigned Scale = 1;
316         int UOpc = Opc;
317         switch (Opc) {
318         default:
319           continue;  // Ignore JT branches
320         case ARM::Bcc:
321           isCond = true;
322           UOpc = ARM::B;
323           // Fallthrough
324         case ARM::B:
325           Bits = 24;
326           Scale = 4;
327           break;
328         case ARM::tBcc:
329           isCond = true;
330           UOpc = ARM::tB;
331           Bits = 8;
332           Scale = 2;
333           break;
334         case ARM::tB:
335           Bits = 11;
336           Scale = 2;
337           break;
338         }
339
340         // Record this immediate branch.
341         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
342         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
343       }
344
345       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
346         PushPopMIs.push_back(I);
347
348       // Scan the instructions for constant pool operands.
349       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
350         if (I->getOperand(op).isConstantPoolIndex()) {
351           // We found one.  The addressing mode tells us the max displacement
352           // from the PC that this instruction permits.
353           
354           // Basic size info comes from the TSFlags field.
355           unsigned Bits = 0;
356           unsigned Scale = 1;
357           unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
358           switch (TSFlags & ARMII::AddrModeMask) {
359           default: 
360             // Constant pool entries can reach anything.
361             if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
362               continue;
363             assert(0 && "Unknown addressing mode for CP reference!");
364           case ARMII::AddrMode1: // AM1: 8 bits << 2
365             Bits = 8;
366             Scale = 4;  // Taking the address of a CP entry.
367             break;
368           case ARMII::AddrMode2:
369             Bits = 12;  // +-offset_12
370             break;
371           case ARMII::AddrMode3:
372             Bits = 8;   // +-offset_8
373             break;
374             // addrmode4 has no immediate offset.
375           case ARMII::AddrMode5:
376             Bits = 8;
377             Scale = 4;  // +-(offset_8*4)
378             break;
379           case ARMII::AddrModeT1:
380             Bits = 5;  // +offset_5
381             break;
382           case ARMII::AddrModeT2:
383             Bits = 5;
384             Scale = 2;  // +(offset_5*2)
385             break;
386           case ARMII::AddrModeT4:
387             Bits = 5;
388             Scale = 4;  // +(offset_5*4)
389             break;
390           case ARMII::AddrModeTs:
391             Bits = 8;
392             Scale = 4;  // +(offset_8*4)
393             break;
394           }
395
396           // Remember that this is a user of a CP entry.
397           unsigned CPI = I->getOperand(op).getConstantPoolIndex();
398           MachineInstr *CPEMI = CPEMIs[CPI];
399           unsigned MaxOffs = ((1 << Bits)-1) * Scale;          
400           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
401
402           // Increment corresponding CPEntry reference count.
403           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
404           assert(CPE && "Cannot find a corresponding CPEntry!");
405           CPE->RefCount++;
406           
407           // Instructions can only use one CP entry, don't bother scanning the
408           // rest of the operands.
409           break;
410         }
411     }
412
413     // In thumb mode, if this block is a constpool island, pessimistically 
414     // assume it needs to be padded by two byte so it's aligned on 4 byte 
415     // boundary.
416     if (AFI->isThumbFunction() &&
417         !MBB.empty() &&
418         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
419       MBBSize += 2;
420
421     BBSizes.push_back(MBBSize);
422     BBOffsets.push_back(Offset);
423     Offset += MBBSize;
424   }
425 }
426
427 /// GetOffsetOf - Return the current offset of the specified machine instruction
428 /// from the start of the function.  This offset changes as stuff is moved
429 /// around inside the function.
430 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
431   MachineBasicBlock *MBB = MI->getParent();
432   
433   // The offset is composed of two things: the sum of the sizes of all MBB's
434   // before this instruction's block, and the offset from the start of the block
435   // it is in.
436   unsigned Offset = BBOffsets[MBB->getNumber()];
437
438   // Sum instructions before MI in MBB.
439   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
440     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
441     if (&*I == MI) return Offset;
442     Offset += ARM::GetInstSize(I);
443   }
444 }
445
446 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
447 /// ID.
448 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
449                               const MachineBasicBlock *RHS) {
450   return LHS->getNumber() < RHS->getNumber();
451 }
452
453 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
454 /// machine function, it upsets all of the block numbers.  Renumber the blocks
455 /// and update the arrays that parallel this numbering.
456 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
457   // Renumber the MBB's to keep them consequtive.
458   NewBB->getParent()->RenumberBlocks(NewBB);
459   
460   // Insert a size into BBSizes to align it properly with the (newly
461   // renumbered) block numbers.
462   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
463
464   // Likewise for BBOffsets.
465   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
466   
467   // Next, update WaterList.  Specifically, we need to add NewMBB as having 
468   // available water after it.
469   std::vector<MachineBasicBlock*>::iterator IP =
470     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
471                      CompareMBBNumbers);
472   WaterList.insert(IP, NewBB);
473 }
474
475
476 /// Split the basic block containing MI into two blocks, which are joined by
477 /// an unconditional branch.  Update datastructures and renumber blocks to
478 /// account for this change and returns the newly created block.
479 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
480   MachineBasicBlock *OrigBB = MI->getParent();
481   bool isThumb = AFI->isThumbFunction();
482
483   // Create a new MBB for the code after the OrigBB.
484   MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
485   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
486   OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
487   
488   // Splice the instructions starting with MI over to NewBB.
489   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
490   
491   // Add an unconditional branch from OrigBB to NewBB.
492   // Note the new unconditional branch is not being recorded.
493   BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
494   NumSplit++;
495   
496   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
497   while (!OrigBB->succ_empty()) {
498     MachineBasicBlock *Succ = *OrigBB->succ_begin();
499     OrigBB->removeSuccessor(Succ);
500     NewBB->addSuccessor(Succ);
501     
502     // This pass should be run after register allocation, so there should be no
503     // PHI nodes to update.
504     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
505            && "PHI nodes should be eliminated by now!");
506   }
507   
508   // OrigBB branches to NewBB.
509   OrigBB->addSuccessor(NewBB);
510   
511   // Update internal data structures to account for the newly inserted MBB.
512   // This is almost the same as UpdateForInsertedWaterBlock, except that
513   // the Water goes after OrigBB, not NewBB.
514   NewBB->getParent()->RenumberBlocks(NewBB);
515   
516   // Insert a size into BBSizes to align it properly with the (newly
517   // renumbered) block numbers.
518   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
519   
520   // Likewise for BBOffsets.
521   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
522
523   // Next, update WaterList.  Specifically, we need to add OrigMBB as having 
524   // available water after it (but not if it's already there, which happens
525   // when splitting before a conditional branch that is followed by an
526   // unconditional branch - in that case we want to insert NewBB).
527   std::vector<MachineBasicBlock*>::iterator IP =
528     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
529                      CompareMBBNumbers);
530   MachineBasicBlock* WaterBB = *IP;
531   if (WaterBB == OrigBB)
532     WaterList.insert(next(IP), NewBB);
533   else
534     WaterList.insert(IP, OrigBB);
535
536   // Figure out how large the first NewMBB is.
537   unsigned NewBBSize = 0;
538   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
539        I != E; ++I)
540     NewBBSize += ARM::GetInstSize(I);
541   
542   unsigned OrigBBI = OrigBB->getNumber();
543   unsigned NewBBI = NewBB->getNumber();
544   // Set the size of NewBB in BBSizes.
545   BBSizes[NewBBI] = NewBBSize;
546   
547   // We removed instructions from UserMBB, subtract that off from its size.
548   // Add 2 or 4 to the block to count the unconditional branch we added to it.
549   unsigned delta = isThumb ? 2 : 4;
550   BBSizes[OrigBBI] -= NewBBSize - delta;
551
552   // ...and adjust BBOffsets for NewBB accordingly.
553   BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
554
555   // All BBOffsets following these blocks must be modified.
556   AdjustBBOffsetsAfter(NewBB, delta);
557
558   return NewBB;
559 }
560
561 //// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
562 /// TrialOffset.
563 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset, 
564                       unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
565   if (UserOffset <= TrialOffset) {
566     // User before the Trial.
567     if (TrialOffset-UserOffset <= MaxDisp)
568       return true;
569   } else if (NegativeOK) {
570     if (UserOffset-TrialOffset <= MaxDisp)
571       return true;
572   }
573   return false;
574 }
575
576 /// WaterIsInRange - Returns true if a CPE placed after the specified
577 /// Water (a basic block) will be in range for the specific MI.
578
579 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
580                          MachineBasicBlock* Water, unsigned MaxDisp)
581 {
582   bool isThumb = AFI->isThumbFunction();
583   unsigned CPEOffset = BBOffsets[Water->getNumber()] + 
584                        BBSizes[Water->getNumber()];
585   // If the Water is a constpool island, it has already been aligned.
586   // If not, align it.
587   if (isThumb &&
588       (Water->empty() ||
589        Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
590     CPEOffset += 2;
591
592   return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
593 }
594
595 /// CPEIsInRange - Returns true if the distance between specific MI and
596 /// specific ConstPool entry instruction can fit in MI's displacement field.
597 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
598                                       MachineInstr *CPEMI,
599                                       unsigned MaxDisp, bool DoDump) {
600   // In thumb mode, pessimistically assumes the .align 2 before the first CPE
601   // in the island adds two byte padding.
602   bool isThumb = AFI->isThumbFunction();
603   unsigned AlignAdj   = isThumb ? 2 : 0;
604   unsigned CPEOffset  = GetOffsetOf(CPEMI) + AlignAdj;
605
606   if (DoDump) {
607     DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
608          << " max delta=" << MaxDisp
609          << " insn address=" << UserOffset
610          << " CPE address=" << CPEOffset
611          << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
612   }
613
614   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
615 }
616
617 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
618 /// unconditionally branches to its only successor.
619 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
620   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
621     return false;
622
623   MachineBasicBlock *Succ = *MBB->succ_begin();
624   MachineBasicBlock *Pred = *MBB->pred_begin();
625   MachineInstr *PredMI = &Pred->back();
626   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
627     return PredMI->getOperand(0).getMBB() == Succ;
628   return false;
629 }
630
631 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
632 {
633   MachineFunction::iterator MBBI = BB->getParent()->end();
634   for(int i=BB->getNumber()+1; i<=prior(MBBI)->getNumber(); i++)
635     BBOffsets[i] += delta;
636 }
637
638 /// DecrementOldEntry - find the constant pool entry with index CPI
639 /// and instruction CPEMI, and decrement its refcount.  If the refcount
640 /// becomes 0 remove the entry and instruction.  Returns true if we removed 
641 /// the entry, false if we didn't.
642
643 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI, 
644                               unsigned Size) {
645   // Find the old entry. Eliminate it if it is no longer used.
646   CPEntry *OldCPE = findConstPoolEntry(CPI, CPEMI);
647   assert(OldCPE && "Unexpected!");
648   if (--OldCPE->RefCount == 0) {
649     MachineBasicBlock *OldCPEBB = OldCPE->CPEMI->getParent();
650     if (OldCPEBB->empty()) {
651       // In thumb mode, the size of island is padded by two to compensate for
652       // the alignment requirement.  Thus it will now be 2 when the block is
653       // empty, so fix this.
654       // All succeeding offsets have the current size value added in, fix this.
655       if (BBSizes[OldCPEBB->getNumber()] != 0) {
656         AdjustBBOffsetsAfter(OldCPEBB, -BBSizes[OldCPEBB->getNumber()]);
657         BBSizes[OldCPEBB->getNumber()] = 0;
658       }
659       // An island has only one predecessor BB and one successor BB. Check if
660       // this BB's predecessor jumps directly to this BB's successor. This
661       // shouldn't happen currently.
662       assert(!BBIsJumpedOver(OldCPEBB) && "How did this happen?");
663       // FIXME: remove the empty blocks after all the work is done?
664     } else {
665       BBSizes[OldCPEBB->getNumber()] -= Size;
666       // All succeeding offsets have the current size value added in, fix this.
667       AdjustBBOffsetsAfter(OldCPEBB, -Size);
668     }
669     OldCPE->CPEMI->eraseFromParent();
670     OldCPE->CPEMI = NULL;
671     NumCPEs--;
672     return true;
673   }
674   return false;
675 }
676
677 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
678 /// if not, see if an in-range clone of the CPE is in range, and if so,
679 /// change the data structures so the user references the clone.  Returns:
680 /// 0 = no existing entry found
681 /// 1 = entry found, and there were no code insertions or deletions
682 /// 2 = entry found, and there were code insertions or deletions
683 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
684 {
685   MachineInstr *UserMI = U.MI;
686   MachineInstr *CPEMI  = U.CPEMI;
687
688   // Check to see if the CPE is already in-range.
689   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
690     DOUT << "In range\n";
691     return 1;
692   }
693
694   // No.  Look for previously created clones of the CPE that are in range.
695   unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
696   std::vector<CPEntry> &CPEs = CPEntries[CPI];
697   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
698     // We already tried this one
699     if (CPEs[i].CPEMI == CPEMI)
700       continue;
701     // Removing CPEs can leave empty entries, skip
702     if (CPEs[i].CPEMI == NULL)
703       continue;
704     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
705       DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
706       // Point the CPUser node to the replacement
707       U.CPEMI = CPEs[i].CPEMI;
708       // Change the CPI in the instruction operand to refer to the clone.
709       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
710         if (UserMI->getOperand(j).isConstantPoolIndex()) {
711           UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
712           break;
713         }
714       // Adjust the refcount of the clone...
715       CPEs[i].RefCount++;
716       // ...and the original.  If we didn't remove the old entry, none of the
717       // addresses changed, so we don't need another pass.
718       unsigned Size = CPEMI->getOperand(2).getImm();
719       return DecrementOldEntry(CPI, CPEMI, Size) ? 2 : 1;
720     }
721   }
722   return 0;
723 }
724
725 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
726 /// is out-of-range.  If so, pick it up the constant pool value and move it some
727 /// place in-range.  Return true if we changed any addresses (thus must run
728 /// another pass of branch lengthening), false otherwise.
729 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
730   MachineInstr *UserMI = U.MI;
731   MachineInstr *CPEMI  = U.CPEMI;
732   unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
733   unsigned Size = CPEMI->getOperand(2).getImm();
734   bool isThumb = AFI->isThumbFunction();
735   MachineBasicBlock *NewMBB;
736   // Compute this only once, it's expensive
737   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
738  
739   // See if the current entry is within range, or there is a clone of it
740   // in range.
741   int result = LookForExistingCPEntry(U, UserOffset);
742   if (result==1) return false;
743   else if (result==2) return true;
744
745   // No existing clone of this CPE is within range.
746   // We will be generating a new clone.  Get a UID for it.
747   unsigned ID  = NextUID++;
748
749   // Look for water where we can place this CPE.  We look for the farthest one
750   // away that will work.  Forward references only for now (although later
751   // we might find some that are backwards).
752   bool WaterFound = false;
753   if (!WaterList.empty()) {
754     for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
755         B = WaterList.begin();; --IP) {
756       MachineBasicBlock* WaterBB = *IP;
757       if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
758         WaterFound = true;
759         DOUT << "found water in range\n";
760         // CPE goes before following block (NewMBB).
761         NewMBB = next(MachineFunction::iterator(WaterBB));
762         // Remove the original WaterList entry; we want subsequent
763         // insertions in this vicinity to go after the one we're
764         // about to insert.  This considerably reduces the number
765         // of times we have to move the same CPE more than once.
766         WaterList.erase(IP);
767         break;
768       }
769       if (IP == B)
770         break;
771     }
772   }
773
774   if (!WaterFound) {
775     // No water found.
776
777     DOUT << "No water found\n";
778     MachineBasicBlock *UserMBB = UserMI->getParent();
779     unsigned TrialOffset = BBOffsets[UserMBB->getNumber()] + 
780                            BBSizes[UserMBB->getNumber()] +
781                            isThumb ? 2 : 4; /* for branch to be added */
782
783     // If the use is at the end of the block, or the end of the block
784     // is within range, make new water there.  (If the block ends in
785     // an unconditional branch already, it is water, and is known to
786     // be out of range; so it's OK to assume above we'll be adding a Br.)
787     if (&UserMBB->back() == UserMI ||
788         OffsetIsInRange(UserOffset, TrialOffset, U.MaxDisp, !isThumb)) {
789       if (&UserMBB->back() == UserMI)
790         assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
791       NewMBB = next(MachineFunction::iterator(UserMBB));
792       // Add an unconditional branch from UserMBB to fallthrough block.
793       // Note the new unconditional branch is not being recorded.
794       BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
795       int delta = isThumb ? 2 : 4;
796       BBSizes[UserMBB->getNumber()] += delta;
797       AdjustBBOffsetsAfter(UserMBB, delta);
798     } else {
799       // What a big block.  Find a place within the block to split it.
800       // This is a little tricky on Thumb since instructions are 2 bytes
801       // and constant pool entries are 4 bytes: if instruction I references
802       // island CPE, and instruction I+1 references CPE', it will
803       // not work well to put CPE as far forward as possible, since then
804       // CPE' cannot immediately follow it (that location is 2 bytes
805       // farther away from I+1 than CPE was from I) and we'd need to create
806       // a new island.
807
808       // Solution of last resort: split the user's MBB right after the user
809       // and insert a clone of the CPE into the newly created water.
810       MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
811       NewMBB = SplitBlockBeforeInstr(NextMI);
812     }
813   }
814
815   // Okay, we know we can put an island before NewMBB now, do it!
816   MachineBasicBlock *NewIsland = new MachineBasicBlock();
817   Fn.getBasicBlockList().insert(NewMBB, NewIsland);
818
819   // Update internal data structures to account for the newly inserted MBB.
820   UpdateForInsertedWaterBlock(NewIsland);
821
822   // Decrement the old entry, and remove it if refcount becomes 0.
823   DecrementOldEntry(CPI, CPEMI, Size);
824
825   // Now that we have an island to add the CPE to, clone the original CPE and
826   // add it to the island.
827   U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
828                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
829   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
830   NumCPEs++;
831
832   // Compensate for .align 2 in thumb mode.
833   if (isThumb) Size += 2;  
834   // Increase the size of the island block to account for the new entry.
835   BBSizes[NewIsland->getNumber()] += Size;
836   BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
837   AdjustBBOffsetsAfter(NewIsland, Size);
838   
839   // Finally, change the CPI in the instruction operand to be ID.
840   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
841     if (UserMI->getOperand(i).isConstantPoolIndex()) {
842       UserMI->getOperand(i).setConstantPoolIndex(ID);
843       break;
844     }
845       
846   DOUT << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
847       
848   return true;
849 }
850
851 /// BBIsInRange - Returns true if the distance between specific MI and
852 /// specific BB can fit in MI's displacement field.
853 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
854                                      unsigned MaxDisp) {
855   unsigned PCAdj      = AFI->isThumbFunction() ? 4 : 8;
856   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
857   unsigned DestOffset = BBOffsets[DestBB->getNumber()];
858
859   DOUT << "Branch of destination BB#" << DestBB->getNumber()
860        << " from BB#" << MI->getParent()->getNumber()
861        << " max delta=" << MaxDisp
862        << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
863
864   return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
865 }
866
867 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
868 /// away to fit in its displacement field.
869 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
870   MachineInstr *MI = Br.MI;
871   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
872
873   // Check to see if the DestBB is already in-range.
874   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
875     return false;
876
877   if (!Br.isCond)
878     return FixUpUnconditionalBr(Fn, Br);
879   return FixUpConditionalBr(Fn, Br);
880 }
881
882 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
883 /// too far away to fit in its displacement field. If the LR register has been
884 /// spilled in the epilogue, then we can use BL to implement a far jump.
885 /// Otherwise, add an intermediate branch instruction to to a branch.
886 bool
887 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
888   MachineInstr *MI = Br.MI;
889   MachineBasicBlock *MBB = MI->getParent();
890   assert(AFI->isThumbFunction() && "Expected a Thumb function!");
891
892   // Use BL to implement far jump.
893   Br.MaxDisp = (1 << 21) * 2;
894   MI->setInstrDescriptor(TII->get(ARM::tBfar));
895   BBSizes[MBB->getNumber()] += 2;
896   AdjustBBOffsetsAfter(MBB, 2);
897   HasFarJump = true;
898   NumUBrFixed++;
899
900   DOUT << "  Changed B to long jump " << *MI;
901
902   return true;
903 }
904
905 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
906 /// the specific unconditional branch instruction.
907 static inline unsigned getUnconditionalBrDisp(int Opc) {
908   return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
909 }
910
911 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
912 /// far away to fit in its displacement field. It is converted to an inverse
913 /// conditional branch + an unconditional branch to the destination.
914 bool
915 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
916   MachineInstr *MI = Br.MI;
917   MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
918
919   // Add a unconditional branch to the destination and invert the branch
920   // condition to jump over it:
921   // blt L1
922   // =>
923   // bge L2
924   // b   L1
925   // L2:
926   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
927   CC = ARMCC::getOppositeCondition(CC);
928
929   // If the branch is at the end of its MBB and that has a fall-through block,
930   // direct the updated conditional branch to the fall-through block. Otherwise,
931   // split the MBB before the next instruction.
932   MachineBasicBlock *MBB = MI->getParent();
933   MachineInstr *BMI = &MBB->back();
934   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
935
936   NumCBrFixed++;
937   if (BMI != MI) {
938     if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
939         BMI->getOpcode() == Br.UncondBr) {
940       // Last MI in the BB is a unconditional branch. Can we simply invert the
941       // condition and swap destinations:
942       // beq L1
943       // b   L2
944       // =>
945       // bne L2
946       // b   L1
947       MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
948       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
949         DOUT << "  Invert Bcc condition and swap its destination with " << *BMI;
950         BMI->getOperand(0).setMachineBasicBlock(DestBB);
951         MI->getOperand(0).setMachineBasicBlock(NewDest);
952         MI->getOperand(1).setImm(CC);
953         return true;
954       }
955     }
956   }
957
958   if (NeedSplit) {
959     SplitBlockBeforeInstr(MI);
960     // No need for the branch to the next block. We're adding a unconditional
961     // branch to the destination.
962     MBB->back().eraseFromParent();
963   }
964   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
965  
966   DOUT << "  Insert B to BB#" << DestBB->getNumber()
967        << " also invert condition and change dest. to BB#"
968        << NextBB->getNumber() << "\n";
969
970   // Insert a unconditional branch and replace the conditional branch.
971   // Also update the ImmBranch as well as adding a new entry for the new branch.
972   BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
973   Br.MI = &MBB->back();
974   BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
975   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
976   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
977   MI->eraseFromParent();
978
979   // Increase the size of MBB to account for the new unconditional branch.
980   int delta = ARM::GetInstSize(&MBB->back());
981   BBSizes[MBB->getNumber()] += delta;
982   AdjustBBOffsetsAfter(MBB, delta);
983   return true;
984 }
985
986 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
987 /// LR / restores LR to pc.
988 bool ARMConstantIslands::UndoLRSpillRestore() {
989   bool MadeChange = false;
990   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
991     MachineInstr *MI = PushPopMIs[i];
992     if (MI->getNumOperands() == 1) {
993         if (MI->getOpcode() == ARM::tPOP_RET &&
994             MI->getOperand(0).getReg() == ARM::PC)
995           BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
996         MI->eraseFromParent();
997         MadeChange = true;
998     }
999   }
1000   return MadeChange;
1001 }