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