Track worst case alignment padding more accurately.
[oota-llvm.git] / lib / Target / ARM / ARMConstantIslandPass.cpp
1 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "Thumb2InstrInfo.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Support/CommandLine.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 STATISTIC(NumCPEs,       "Number of constpool entries");
40 STATISTIC(NumSplit,      "Number of uncond branches inserted");
41 STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
42 STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
43 STATISTIC(NumTBs,        "Number of table branches generated");
44 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
45 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
46 STATISTIC(NumCBZ,        "Number of CBZ / CBNZ formed");
47 STATISTIC(NumJTMoved,    "Number of jump table destination blocks moved");
48 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
49
50
51 static cl::opt<bool>
52 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
53           cl::desc("Adjust basic block layout to better use TB[BH]"));
54
55 // FIXME: This option should be removed once it has received sufficient testing.
56 static cl::opt<bool>
57 AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
58           cl::desc("Align constant islands in code"));
59
60 /// UnknownPadding - Return the worst case padding that could result from
61 /// unknown offset bits.  This does not include alignment padding caused by
62 /// known offset bits.
63 ///
64 /// @param LogAlign log2(alignment)
65 /// @param KnownBits Number of known low offset bits.
66 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
67   if (KnownBits < LogAlign)
68     return (1u << LogAlign) - (1u << KnownBits);
69   return 0;
70 }
71
72 namespace {
73   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
74   /// requires constant pool entries to be scattered among the instructions
75   /// inside a function.  To do this, it completely ignores the normal LLVM
76   /// constant pool; instead, it places constants wherever it feels like with
77   /// special instructions.
78   ///
79   /// The terminology used in this pass includes:
80   ///   Islands - Clumps of constants placed in the function.
81   ///   Water   - Potential places where an island could be formed.
82   ///   CPE     - A constant pool entry that has been placed somewhere, which
83   ///             tracks a list of users.
84   class ARMConstantIslands : public MachineFunctionPass {
85     /// BasicBlockInfo - Information about the offset and size of a single
86     /// basic block.
87     struct BasicBlockInfo {
88       /// Offset - Distance from the beginning of the function to the beginning
89       /// of this basic block.
90       ///
91       /// Offsets are computed assuming worst case padding before an aligned
92       /// block. This means that subtracting basic block offsets always gives a
93       /// conservative estimate of the real distance which may be smaller.
94       ///
95       /// Because worst case padding is used, the computed offset of an aligned
96       /// block may not actually be aligned.
97       unsigned Offset;
98
99       /// Size - Size of the basic block in bytes.  If the block contains
100       /// inline assembly, this is a worst case estimate.
101       ///
102       /// The size does not include any alignment padding whether from the
103       /// beginning of the block, or from an aligned jump table at the end.
104       unsigned Size;
105
106       /// KnownBits - The number of low bits in Offset that are known to be
107       /// exact.  The remaining bits of Offset are an upper bound.
108       uint8_t KnownBits;
109
110       /// Unalign - When non-zero, the block contains instructions (inline asm)
111       /// of unknown size.  The real size may be smaller than Size bytes by a
112       /// multiple of 1 << Unalign.
113       uint8_t Unalign;
114
115       /// PostAlign - When non-zero, the block terminator contains a .align
116       /// directive, so the end of the block is aligned to 1 << PostAlign
117       /// bytes.
118       uint8_t PostAlign;
119
120       BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
121         PostAlign(0) {}
122
123       /// Compute the number of known offset bits internally to this block.
124       /// This number should be used to predict worst case padding when
125       /// splitting the block.
126       unsigned internalKnownBits() const {
127         return Unalign ? Unalign : KnownBits;
128       }
129
130       /// Compute the offset immediately following this block.  If LogAlign is
131       /// specified, return the offset the successor block will get if it has
132       /// this alignment.
133       unsigned postOffset(unsigned LogAlign = 0) const {
134         unsigned PO = Offset + Size;
135         unsigned LA = std::max(unsigned(PostAlign), LogAlign);
136         if (!LA)
137           return PO;
138         // Add alignment padding from the terminator.
139         return PO + UnknownPadding(LA, internalKnownBits());
140       }
141
142       /// Compute the number of known low bits of postOffset.  If this block
143       /// contains inline asm, the number of known bits drops to the
144       /// instruction alignment.  An aligned terminator may increase the number
145       /// of know bits.
146       /// If LogAlign is given, also consider the alignment of the next block.
147       unsigned postKnownBits(unsigned LogAlign = 0) const {
148         return std::max(std::max(unsigned(PostAlign), LogAlign),
149                         internalKnownBits());
150       }
151     };
152
153     std::vector<BasicBlockInfo> BBInfo;
154
155     /// WaterList - A sorted list of basic blocks where islands could be placed
156     /// (i.e. blocks that don't fall through to the following block, due
157     /// to a return, unreachable, or unconditional branch).
158     std::vector<MachineBasicBlock*> WaterList;
159
160     /// NewWaterList - The subset of WaterList that was created since the
161     /// previous iteration by inserting unconditional branches.
162     SmallSet<MachineBasicBlock*, 4> NewWaterList;
163
164     typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
165
166     /// CPUser - One user of a constant pool, keeping the machine instruction
167     /// pointer, the constant pool being referenced, and the max displacement
168     /// allowed from the instruction to the CP.  The HighWaterMark records the
169     /// highest basic block where a new CPEntry can be placed.  To ensure this
170     /// pass terminates, the CP entries are initially placed at the end of the
171     /// function and then move monotonically to lower addresses.  The
172     /// exception to this rule is when the current CP entry for a particular
173     /// CPUser is out of range, but there is another CP entry for the same
174     /// constant value in range.  We want to use the existing in-range CP
175     /// entry, but if it later moves out of range, the search for new water
176     /// should resume where it left off.  The HighWaterMark is used to record
177     /// that point.
178     struct CPUser {
179       MachineInstr *MI;
180       MachineInstr *CPEMI;
181       MachineBasicBlock *HighWaterMark;
182     private:
183       unsigned MaxDisp;
184     public:
185       bool NegOk;
186       bool IsSoImm;
187       bool KnownAlignment;
188       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
189              bool neg, bool soimm)
190         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
191           KnownAlignment(false) {
192         HighWaterMark = CPEMI->getParent();
193       }
194       /// getMaxDisp - Returns the maximum displacement supported by MI.
195       /// Correct for unknown alignment.
196       /// Conservatively subtract 2 bytes to handle weird alignment effects.
197       unsigned getMaxDisp() const {
198         return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
199       }
200     };
201
202     /// CPUsers - Keep track of all of the machine instructions that use various
203     /// constant pools and their max displacement.
204     std::vector<CPUser> CPUsers;
205
206     /// CPEntry - One per constant pool entry, keeping the machine instruction
207     /// pointer, the constpool index, and the number of CPUser's which
208     /// reference this entry.
209     struct CPEntry {
210       MachineInstr *CPEMI;
211       unsigned CPI;
212       unsigned RefCount;
213       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
214         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
215     };
216
217     /// CPEntries - Keep track of all of the constant pool entry machine
218     /// instructions. For each original constpool index (i.e. those that
219     /// existed upon entry to this pass), it keeps a vector of entries.
220     /// Original elements are cloned as we go along; the clones are
221     /// put in the vector of the original element, but have distinct CPIs.
222     std::vector<std::vector<CPEntry> > CPEntries;
223
224     /// ImmBranch - One per immediate branch, keeping the machine instruction
225     /// pointer, conditional or unconditional, the max displacement,
226     /// and (if isCond is true) the corresponding unconditional branch
227     /// opcode.
228     struct ImmBranch {
229       MachineInstr *MI;
230       unsigned MaxDisp : 31;
231       bool isCond : 1;
232       int UncondBr;
233       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
234         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
235     };
236
237     /// ImmBranches - Keep track of all the immediate branch instructions.
238     ///
239     std::vector<ImmBranch> ImmBranches;
240
241     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
242     ///
243     SmallVector<MachineInstr*, 4> PushPopMIs;
244
245     /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
246     SmallVector<MachineInstr*, 4> T2JumpTables;
247
248     /// HasFarJump - True if any far jump instruction has been emitted during
249     /// the branch fix up pass.
250     bool HasFarJump;
251
252     MachineFunction *MF;
253     MachineConstantPool *MCP;
254     const ARMBaseInstrInfo *TII;
255     const ARMSubtarget *STI;
256     ARMFunctionInfo *AFI;
257     bool isThumb;
258     bool isThumb1;
259     bool isThumb2;
260   public:
261     static char ID;
262     ARMConstantIslands() : MachineFunctionPass(ID) {}
263
264     virtual bool runOnMachineFunction(MachineFunction &MF);
265
266     virtual const char *getPassName() const {
267       return "ARM constant island placement and branch shortening pass";
268     }
269
270   private:
271     void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
272     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
273     unsigned getCPELogAlign(const MachineInstr *CPEMI);
274     void scanFunctionJumpTables();
275     void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
276     MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
277     void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
278     void adjustBBOffsetsAfter(MachineBasicBlock *BB);
279     bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
280     int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
281     bool findAvailableWater(CPUser&U, unsigned UserOffset,
282                             water_iterator &WaterIter);
283     void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
284                         MachineBasicBlock *&NewMBB);
285     bool handleConstantPoolUser(unsigned CPUserIndex);
286     void removeDeadCPEMI(MachineInstr *CPEMI);
287     bool removeUnusedCPEntries();
288     bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
289                           MachineInstr *CPEMI, unsigned Disp, bool NegOk,
290                           bool DoDump = false);
291     bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
292                         CPUser &U, unsigned &Growth);
293     bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
294     bool fixupImmediateBr(ImmBranch &Br);
295     bool fixupConditionalBr(ImmBranch &Br);
296     bool fixupUnconditionalBr(ImmBranch &Br);
297     bool undoLRSpillRestore();
298     bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
299     bool optimizeThumb2Instructions();
300     bool optimizeThumb2Branches();
301     bool reorderThumb2JumpTables();
302     bool optimizeThumb2JumpTables();
303     MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
304                                                   MachineBasicBlock *JTBB);
305
306     void computeBlockSize(MachineBasicBlock *MBB);
307     unsigned getOffsetOf(MachineInstr *MI) const;
308     unsigned getUserOffset(CPUser&) const;
309     void dumpBBs();
310     void verify();
311
312     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
313                          unsigned Disp, bool NegativeOK, bool IsSoImm = false);
314     bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
315                          const CPUser &U) {
316       return isOffsetInRange(UserOffset, TrialOffset,
317                              U.getMaxDisp(), U.NegOk, U.IsSoImm);
318     }
319   };
320   char ARMConstantIslands::ID = 0;
321 }
322
323 /// verify - check BBOffsets, BBSizes, alignment of islands
324 void ARMConstantIslands::verify() {
325 #ifndef NDEBUG
326   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
327        MBBI != E; ++MBBI) {
328     MachineBasicBlock *MBB = MBBI;
329     unsigned MBBId = MBB->getNumber();
330     assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
331   }
332   DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
333   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
334     CPUser &U = CPUsers[i];
335     unsigned UserOffset = getUserOffset(U);
336     // Verify offset using the real max displacement without the safety
337     // adjustment.
338     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
339                          /* DoDump = */ true)) {
340       DEBUG(dbgs() << "OK\n");
341       continue;
342     }
343     DEBUG(dbgs() << "Out of range.\n");
344     dumpBBs();
345     DEBUG(MF->dump());
346     llvm_unreachable("Constant pool entry out of range!");
347   }
348 #endif
349 }
350
351 /// print block size and offset information - debugging
352 void ARMConstantIslands::dumpBBs() {
353   DEBUG({
354     for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
355       const BasicBlockInfo &BBI = BBInfo[J];
356       dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
357              << " kb=" << unsigned(BBI.KnownBits)
358              << " ua=" << unsigned(BBI.Unalign)
359              << " pa=" << unsigned(BBI.PostAlign)
360              << format(" size=%#x\n", BBInfo[J].Size);
361     }
362   });
363 }
364
365 /// createARMConstantIslandPass - returns an instance of the constpool
366 /// island pass.
367 FunctionPass *llvm::createARMConstantIslandPass() {
368   return new ARMConstantIslands();
369 }
370
371 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
372   MF = &mf;
373   MCP = mf.getConstantPool();
374
375   DEBUG(dbgs() << "***** ARMConstantIslands: "
376                << MCP->getConstants().size() << " CP entries, aligned to "
377                << MCP->getConstantPoolAlignment() << " bytes *****\n");
378
379   TII = (const ARMBaseInstrInfo*)MF->getTarget().getInstrInfo();
380   AFI = MF->getInfo<ARMFunctionInfo>();
381   STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
382
383   isThumb = AFI->isThumbFunction();
384   isThumb1 = AFI->isThumb1OnlyFunction();
385   isThumb2 = AFI->isThumb2Function();
386
387   HasFarJump = false;
388
389   // This pass invalidates liveness information when it splits basic blocks.
390   MF->getRegInfo().invalidateLiveness();
391
392   // Renumber all of the machine basic blocks in the function, guaranteeing that
393   // the numbers agree with the position of the block in the function.
394   MF->RenumberBlocks();
395
396   // Try to reorder and otherwise adjust the block layout to make good use
397   // of the TB[BH] instructions.
398   bool MadeChange = false;
399   if (isThumb2 && AdjustJumpTableBlocks) {
400     scanFunctionJumpTables();
401     MadeChange |= reorderThumb2JumpTables();
402     // Data is out of date, so clear it. It'll be re-computed later.
403     T2JumpTables.clear();
404     // Blocks may have shifted around. Keep the numbering up to date.
405     MF->RenumberBlocks();
406   }
407
408   // Thumb1 functions containing constant pools get 4-byte alignment.
409   // This is so we can keep exact track of where the alignment padding goes.
410
411   // ARM and Thumb2 functions need to be 4-byte aligned.
412   if (!isThumb1)
413     MF->EnsureAlignment(2);  // 2 = log2(4)
414
415   // Perform the initial placement of the constant pool entries.  To start with,
416   // we put them all at the end of the function.
417   std::vector<MachineInstr*> CPEMIs;
418   if (!MCP->isEmpty())
419     doInitialPlacement(CPEMIs);
420
421   /// The next UID to take is the first unused one.
422   AFI->initPICLabelUId(CPEMIs.size());
423
424   // Do the initial scan of the function, building up information about the
425   // sizes of each block, the location of all the water, and finding all of the
426   // constant pool users.
427   initializeFunctionInfo(CPEMIs);
428   CPEMIs.clear();
429   DEBUG(dumpBBs());
430
431
432   /// Remove dead constant pool entries.
433   MadeChange |= removeUnusedCPEntries();
434
435   // Iteratively place constant pool entries and fix up branches until there
436   // is no change.
437   unsigned NoCPIters = 0, NoBRIters = 0;
438   while (true) {
439     DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
440     bool CPChange = false;
441     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
442       CPChange |= handleConstantPoolUser(i);
443     if (CPChange && ++NoCPIters > 30)
444       report_fatal_error("Constant Island pass failed to converge!");
445     DEBUG(dumpBBs());
446
447     // Clear NewWaterList now.  If we split a block for branches, it should
448     // appear as "new water" for the next iteration of constant pool placement.
449     NewWaterList.clear();
450
451     DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
452     bool BRChange = false;
453     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
454       BRChange |= fixupImmediateBr(ImmBranches[i]);
455     if (BRChange && ++NoBRIters > 30)
456       report_fatal_error("Branch Fix Up pass failed to converge!");
457     DEBUG(dumpBBs());
458
459     if (!CPChange && !BRChange)
460       break;
461     MadeChange = true;
462   }
463
464   // Shrink 32-bit Thumb2 branch, load, and store instructions.
465   if (isThumb2 && !STI->prefers32BitThumb())
466     MadeChange |= optimizeThumb2Instructions();
467
468   // After a while, this might be made debug-only, but it is not expensive.
469   verify();
470
471   // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
472   // undo the spill / restore of LR if possible.
473   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
474     MadeChange |= undoLRSpillRestore();
475
476   // Save the mapping between original and cloned constpool entries.
477   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
478     for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
479       const CPEntry & CPE = CPEntries[i][j];
480       AFI->recordCPEClone(i, CPE.CPI);
481     }
482   }
483
484   DEBUG(dbgs() << '\n'; dumpBBs());
485
486   BBInfo.clear();
487   WaterList.clear();
488   CPUsers.clear();
489   CPEntries.clear();
490   ImmBranches.clear();
491   PushPopMIs.clear();
492   T2JumpTables.clear();
493
494   return MadeChange;
495 }
496
497 /// doInitialPlacement - Perform the initial placement of the constant pool
498 /// entries.  To start with, we put them all at the end of the function.
499 void
500 ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
501   // Create the basic block to hold the CPE's.
502   MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
503   MF->push_back(BB);
504
505   // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
506   unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
507
508   // Mark the basic block as required by the const-pool.
509   // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
510   BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
511
512   // The function needs to be as aligned as the basic blocks. The linker may
513   // move functions around based on their alignment.
514   MF->EnsureAlignment(BB->getAlignment());
515
516   // Order the entries in BB by descending alignment.  That ensures correct
517   // alignment of all entries as long as BB is sufficiently aligned.  Keep
518   // track of the insertion point for each alignment.  We are going to bucket
519   // sort the entries as they are created.
520   SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
521
522   // Add all of the constants from the constant pool to the end block, use an
523   // identity mapping of CPI's to CPE's.
524   const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
525
526   const TargetData &TD = *MF->getTarget().getTargetData();
527   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
528     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
529     assert(Size >= 4 && "Too small constant pool entry");
530     unsigned Align = CPs[i].getAlignment();
531     assert(isPowerOf2_32(Align) && "Invalid alignment");
532     // Verify that all constant pool entries are a multiple of their alignment.
533     // If not, we would have to pad them out so that instructions stay aligned.
534     assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
535
536     // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
537     unsigned LogAlign = Log2_32(Align);
538     MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
539     MachineInstr *CPEMI =
540       BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
541         .addImm(i).addConstantPoolIndex(i).addImm(Size);
542     CPEMIs.push_back(CPEMI);
543
544     // Ensure that future entries with higher alignment get inserted before
545     // CPEMI. This is bucket sort with iterators.
546     for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
547       if (InsPoint[a] == InsAt)
548         InsPoint[a] = CPEMI;
549
550     // Add a new CPEntry, but no corresponding CPUser yet.
551     std::vector<CPEntry> CPEs;
552     CPEs.push_back(CPEntry(CPEMI, i));
553     CPEntries.push_back(CPEs);
554     ++NumCPEs;
555     DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
556                  << Size << ", align = " << Align <<'\n');
557   }
558   DEBUG(BB->dump());
559 }
560
561 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
562 /// into the block immediately after it.
563 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
564   // Get the next machine basic block in the function.
565   MachineFunction::iterator MBBI = MBB;
566   // Can't fall off end of function.
567   if (llvm::next(MBBI) == MBB->getParent()->end())
568     return false;
569
570   MachineBasicBlock *NextBB = llvm::next(MBBI);
571   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
572        E = MBB->succ_end(); I != E; ++I)
573     if (*I == NextBB)
574       return true;
575
576   return false;
577 }
578
579 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
580 /// look up the corresponding CPEntry.
581 ARMConstantIslands::CPEntry
582 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
583                                         const MachineInstr *CPEMI) {
584   std::vector<CPEntry> &CPEs = CPEntries[CPI];
585   // Number of entries per constpool index should be small, just do a
586   // linear search.
587   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
588     if (CPEs[i].CPEMI == CPEMI)
589       return &CPEs[i];
590   }
591   return NULL;
592 }
593
594 /// getCPELogAlign - Returns the required alignment of the constant pool entry
595 /// represented by CPEMI.  Alignment is measured in log2(bytes) units.
596 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
597   assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
598
599   // Everything is 4-byte aligned unless AlignConstantIslands is set.
600   if (!AlignConstantIslands)
601     return 2;
602
603   unsigned CPI = CPEMI->getOperand(1).getIndex();
604   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
605   unsigned Align = MCP->getConstants()[CPI].getAlignment();
606   assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
607   return Log2_32(Align);
608 }
609
610 /// scanFunctionJumpTables - Do a scan of the function, building up
611 /// information about the sizes of each block and the locations of all
612 /// the jump tables.
613 void ARMConstantIslands::scanFunctionJumpTables() {
614   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
615        MBBI != E; ++MBBI) {
616     MachineBasicBlock &MBB = *MBBI;
617
618     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
619          I != E; ++I)
620       if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
621         T2JumpTables.push_back(I);
622   }
623 }
624
625 /// initializeFunctionInfo - Do the initial scan of the function, building up
626 /// information about the sizes of each block, the location of all the water,
627 /// and finding all of the constant pool users.
628 void ARMConstantIslands::
629 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
630   BBInfo.clear();
631   BBInfo.resize(MF->getNumBlockIDs());
632
633   // First thing, compute the size of all basic blocks, and see if the function
634   // has any inline assembly in it. If so, we have to be conservative about
635   // alignment assumptions, as we don't know for sure the size of any
636   // instructions in the inline assembly.
637   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
638     computeBlockSize(I);
639
640   // The known bits of the entry block offset are determined by the function
641   // alignment.
642   BBInfo.front().KnownBits = MF->getAlignment();
643
644   // Compute block offsets and known bits.
645   adjustBBOffsetsAfter(MF->begin());
646
647   // Now go back through the instructions and build up our data structures.
648   for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
649        MBBI != E; ++MBBI) {
650     MachineBasicBlock &MBB = *MBBI;
651
652     // If this block doesn't fall through into the next MBB, then this is
653     // 'water' that a constant pool island could be placed.
654     if (!BBHasFallthrough(&MBB))
655       WaterList.push_back(&MBB);
656
657     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
658          I != E; ++I) {
659       if (I->isDebugValue())
660         continue;
661
662       int Opc = I->getOpcode();
663       if (I->isBranch()) {
664         bool isCond = false;
665         unsigned Bits = 0;
666         unsigned Scale = 1;
667         int UOpc = Opc;
668         switch (Opc) {
669         default:
670           continue;  // Ignore other JT branches
671         case ARM::t2BR_JT:
672           T2JumpTables.push_back(I);
673           continue;   // Does not get an entry in ImmBranches
674         case ARM::Bcc:
675           isCond = true;
676           UOpc = ARM::B;
677           // Fallthrough
678         case ARM::B:
679           Bits = 24;
680           Scale = 4;
681           break;
682         case ARM::tBcc:
683           isCond = true;
684           UOpc = ARM::tB;
685           Bits = 8;
686           Scale = 2;
687           break;
688         case ARM::tB:
689           Bits = 11;
690           Scale = 2;
691           break;
692         case ARM::t2Bcc:
693           isCond = true;
694           UOpc = ARM::t2B;
695           Bits = 20;
696           Scale = 2;
697           break;
698         case ARM::t2B:
699           Bits = 24;
700           Scale = 2;
701           break;
702         }
703
704         // Record this immediate branch.
705         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
706         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
707       }
708
709       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
710         PushPopMIs.push_back(I);
711
712       if (Opc == ARM::CONSTPOOL_ENTRY)
713         continue;
714
715       // Scan the instructions for constant pool operands.
716       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
717         if (I->getOperand(op).isCPI()) {
718           // We found one.  The addressing mode tells us the max displacement
719           // from the PC that this instruction permits.
720
721           // Basic size info comes from the TSFlags field.
722           unsigned Bits = 0;
723           unsigned Scale = 1;
724           bool NegOk = false;
725           bool IsSoImm = false;
726
727           switch (Opc) {
728           default:
729             llvm_unreachable("Unknown addressing mode for CP reference!");
730
731           // Taking the address of a CP entry.
732           case ARM::LEApcrel:
733             // This takes a SoImm, which is 8 bit immediate rotated. We'll
734             // pretend the maximum offset is 255 * 4. Since each instruction
735             // 4 byte wide, this is always correct. We'll check for other
736             // displacements that fits in a SoImm as well.
737             Bits = 8;
738             Scale = 4;
739             NegOk = true;
740             IsSoImm = true;
741             break;
742           case ARM::t2LEApcrel:
743             Bits = 12;
744             NegOk = true;
745             break;
746           case ARM::tLEApcrel:
747             Bits = 8;
748             Scale = 4;
749             break;
750
751           case ARM::LDRi12:
752           case ARM::LDRcp:
753           case ARM::t2LDRpci:
754             Bits = 12;  // +-offset_12
755             NegOk = true;
756             break;
757
758           case ARM::tLDRpci:
759             Bits = 8;
760             Scale = 4;  // +(offset_8*4)
761             break;
762
763           case ARM::VLDRD:
764           case ARM::VLDRS:
765             Bits = 8;
766             Scale = 4;  // +-(offset_8*4)
767             NegOk = true;
768             break;
769           }
770
771           // Remember that this is a user of a CP entry.
772           unsigned CPI = I->getOperand(op).getIndex();
773           MachineInstr *CPEMI = CPEMIs[CPI];
774           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
775           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
776
777           // Increment corresponding CPEntry reference count.
778           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
779           assert(CPE && "Cannot find a corresponding CPEntry!");
780           CPE->RefCount++;
781
782           // Instructions can only use one CP entry, don't bother scanning the
783           // rest of the operands.
784           break;
785         }
786     }
787   }
788 }
789
790 /// computeBlockSize - Compute the size and some alignment information for MBB.
791 /// This function updates BBInfo directly.
792 void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
793   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
794   BBI.Size = 0;
795   BBI.Unalign = 0;
796   BBI.PostAlign = 0;
797
798   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
799        ++I) {
800     BBI.Size += TII->GetInstSizeInBytes(I);
801     // For inline asm, GetInstSizeInBytes returns a conservative estimate.
802     // The actual size may be smaller, but still a multiple of the instr size.
803     if (I->isInlineAsm())
804       BBI.Unalign = isThumb ? 1 : 2;
805     // Also consider instructions that may be shrunk later.
806     else if (isThumb && mayOptimizeThumb2Instruction(I))
807       BBI.Unalign = 1;
808   }
809
810   // tBR_JTr contains a .align 2 directive.
811   if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
812     BBI.PostAlign = 2;
813     MBB->getParent()->EnsureAlignment(2);
814   }
815 }
816
817 /// getOffsetOf - Return the current offset of the specified machine instruction
818 /// from the start of the function.  This offset changes as stuff is moved
819 /// around inside the function.
820 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
821   MachineBasicBlock *MBB = MI->getParent();
822
823   // The offset is composed of two things: the sum of the sizes of all MBB's
824   // before this instruction's block, and the offset from the start of the block
825   // it is in.
826   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
827
828   // Sum instructions before MI in MBB.
829   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
830     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
831     Offset += TII->GetInstSizeInBytes(I);
832   }
833   return Offset;
834 }
835
836 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
837 /// ID.
838 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
839                               const MachineBasicBlock *RHS) {
840   return LHS->getNumber() < RHS->getNumber();
841 }
842
843 /// updateForInsertedWaterBlock - When a block is newly inserted into the
844 /// machine function, it upsets all of the block numbers.  Renumber the blocks
845 /// and update the arrays that parallel this numbering.
846 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
847   // Renumber the MBB's to keep them consecutive.
848   NewBB->getParent()->RenumberBlocks(NewBB);
849
850   // Insert an entry into BBInfo to align it properly with the (newly
851   // renumbered) block numbers.
852   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
853
854   // Next, update WaterList.  Specifically, we need to add NewMBB as having
855   // available water after it.
856   water_iterator IP =
857     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
858                      CompareMBBNumbers);
859   WaterList.insert(IP, NewBB);
860 }
861
862
863 /// Split the basic block containing MI into two blocks, which are joined by
864 /// an unconditional branch.  Update data structures and renumber blocks to
865 /// account for this change and returns the newly created block.
866 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
867   MachineBasicBlock *OrigBB = MI->getParent();
868
869   // Create a new MBB for the code after the OrigBB.
870   MachineBasicBlock *NewBB =
871     MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
872   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
873   MF->insert(MBBI, NewBB);
874
875   // Splice the instructions starting with MI over to NewBB.
876   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
877
878   // Add an unconditional branch from OrigBB to NewBB.
879   // Note the new unconditional branch is not being recorded.
880   // There doesn't seem to be meaningful DebugInfo available; this doesn't
881   // correspond to anything in the source.
882   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
883   if (!isThumb)
884     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
885   else
886     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
887             .addImm(ARMCC::AL).addReg(0);
888   ++NumSplit;
889
890   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
891   NewBB->transferSuccessors(OrigBB);
892
893   // OrigBB branches to NewBB.
894   OrigBB->addSuccessor(NewBB);
895
896   // Update internal data structures to account for the newly inserted MBB.
897   // This is almost the same as updateForInsertedWaterBlock, except that
898   // the Water goes after OrigBB, not NewBB.
899   MF->RenumberBlocks(NewBB);
900
901   // Insert an entry into BBInfo to align it properly with the (newly
902   // renumbered) block numbers.
903   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
904
905   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
906   // available water after it (but not if it's already there, which happens
907   // when splitting before a conditional branch that is followed by an
908   // unconditional branch - in that case we want to insert NewBB).
909   water_iterator IP =
910     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
911                      CompareMBBNumbers);
912   MachineBasicBlock* WaterBB = *IP;
913   if (WaterBB == OrigBB)
914     WaterList.insert(llvm::next(IP), NewBB);
915   else
916     WaterList.insert(IP, OrigBB);
917   NewWaterList.insert(OrigBB);
918
919   // Figure out how large the OrigBB is.  As the first half of the original
920   // block, it cannot contain a tablejump.  The size includes
921   // the new jump we added.  (It should be possible to do this without
922   // recounting everything, but it's very confusing, and this is rarely
923   // executed.)
924   computeBlockSize(OrigBB);
925
926   // Figure out how large the NewMBB is.  As the second half of the original
927   // block, it may contain a tablejump.
928   computeBlockSize(NewBB);
929
930   // All BBOffsets following these blocks must be modified.
931   adjustBBOffsetsAfter(OrigBB);
932
933   return NewBB;
934 }
935
936 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
937 /// displacement computation.  Update U.KnownAlignment to match its current
938 /// basic block location.
939 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
940   unsigned UserOffset = getOffsetOf(U.MI);
941   const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
942   unsigned KnownBits = BBI.internalKnownBits();
943
944   // The value read from PC is offset from the actual instruction address.
945   UserOffset += (isThumb ? 4 : 8);
946
947   // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
948   // Make sure U.getMaxDisp() returns a constrained range.
949   U.KnownAlignment = (KnownBits >= 2);
950
951   // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
952   // purposes of the displacement computation; compensate for that here.
953   // For unknown alignments, getMaxDisp() constrains the range instead.
954   if (isThumb && U.KnownAlignment)
955     UserOffset &= ~3u;
956
957   return UserOffset;
958 }
959
960 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
961 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
962 /// constant pool entry).
963 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
964 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
965 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
966 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
967                                          unsigned TrialOffset, unsigned MaxDisp,
968                                          bool NegativeOK, bool IsSoImm) {
969   if (UserOffset <= TrialOffset) {
970     // User before the Trial.
971     if (TrialOffset - UserOffset <= MaxDisp)
972       return true;
973     // FIXME: Make use full range of soimm values.
974   } else if (NegativeOK) {
975     if (UserOffset - TrialOffset <= MaxDisp)
976       return true;
977     // FIXME: Make use full range of soimm values.
978   }
979   return false;
980 }
981
982 /// isWaterInRange - Returns true if a CPE placed after the specified
983 /// Water (a basic block) will be in range for the specific MI.
984 ///
985 /// Compute how much the function will grow by inserting a CPE after Water.
986 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
987                                         MachineBasicBlock* Water, CPUser &U,
988                                         unsigned &Growth) {
989   unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
990   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
991   unsigned NextBlockOffset, NextBlockAlignment;
992   MachineFunction::const_iterator NextBlock = Water;
993   if (++NextBlock == MF->end()) {
994     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
995     NextBlockAlignment = 0;
996   } else {
997     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
998     NextBlockAlignment = NextBlock->getAlignment();
999   }
1000   unsigned Size = U.CPEMI->getOperand(2).getImm();
1001   unsigned CPEEnd = CPEOffset + Size;
1002
1003   // The CPE may be able to hide in the alignment padding before the next
1004   // block. It may also cause more padding to be required if it is more aligned
1005   // that the next block.
1006   if (CPEEnd > NextBlockOffset) {
1007     Growth = CPEEnd - NextBlockOffset;
1008     // Compute the padding that would go at the end of the CPE to align the next
1009     // block.
1010     Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1011
1012     // If the CPE is to be inserted before the instruction, that will raise
1013     // the offset of the instruction. Also account for unknown alignment padding
1014     // in blocks between CPE and the user.
1015     if (CPEOffset < UserOffset)
1016       UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1017   } else
1018     // CPE fits in existing padding.
1019     Growth = 0;
1020
1021   return isOffsetInRange(UserOffset, CPEOffset, U);
1022 }
1023
1024 /// isCPEntryInRange - Returns true if the distance between specific MI and
1025 /// specific ConstPool entry instruction can fit in MI's displacement field.
1026 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1027                                       MachineInstr *CPEMI, unsigned MaxDisp,
1028                                       bool NegOk, bool DoDump) {
1029   unsigned CPEOffset  = getOffsetOf(CPEMI);
1030
1031   if (DoDump) {
1032     DEBUG({
1033       unsigned Block = MI->getParent()->getNumber();
1034       const BasicBlockInfo &BBI = BBInfo[Block];
1035       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1036              << " max delta=" << MaxDisp
1037              << format(" insn address=%#x", UserOffset)
1038              << " in BB#" << Block << ": "
1039              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1040              << format("CPE address=%#x offset=%+d: ", CPEOffset,
1041                        int(CPEOffset-UserOffset));
1042     });
1043   }
1044
1045   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1046 }
1047
1048 #ifndef NDEBUG
1049 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1050 /// unconditionally branches to its only successor.
1051 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1052   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1053     return false;
1054
1055   MachineBasicBlock *Succ = *MBB->succ_begin();
1056   MachineBasicBlock *Pred = *MBB->pred_begin();
1057   MachineInstr *PredMI = &Pred->back();
1058   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1059       || PredMI->getOpcode() == ARM::t2B)
1060     return PredMI->getOperand(0).getMBB() == Succ;
1061   return false;
1062 }
1063 #endif // NDEBUG
1064
1065 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1066   unsigned BBNum = BB->getNumber();
1067   for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1068     // Get the offset and known bits at the end of the layout predecessor.
1069     // Include the alignment of the current block.
1070     unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1071     unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1072     unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1073
1074     // This is where block i begins.  Stop if the offset is already correct,
1075     // and we have updated 2 blocks.  This is the maximum number of blocks
1076     // changed before calling this function.
1077     if (i > BBNum + 2 &&
1078         BBInfo[i].Offset == Offset &&
1079         BBInfo[i].KnownBits == KnownBits)
1080       break;
1081
1082     BBInfo[i].Offset = Offset;
1083     BBInfo[i].KnownBits = KnownBits;
1084   }
1085 }
1086
1087 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1088 /// and instruction CPEMI, and decrement its refcount.  If the refcount
1089 /// becomes 0 remove the entry and instruction.  Returns true if we removed
1090 /// the entry, false if we didn't.
1091
1092 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1093                                                     MachineInstr *CPEMI) {
1094   // Find the old entry. Eliminate it if it is no longer used.
1095   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1096   assert(CPE && "Unexpected!");
1097   if (--CPE->RefCount == 0) {
1098     removeDeadCPEMI(CPEMI);
1099     CPE->CPEMI = NULL;
1100     --NumCPEs;
1101     return true;
1102   }
1103   return false;
1104 }
1105
1106 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1107 /// if not, see if an in-range clone of the CPE is in range, and if so,
1108 /// change the data structures so the user references the clone.  Returns:
1109 /// 0 = no existing entry found
1110 /// 1 = entry found, and there were no code insertions or deletions
1111 /// 2 = entry found, and there were code insertions or deletions
1112 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1113 {
1114   MachineInstr *UserMI = U.MI;
1115   MachineInstr *CPEMI  = U.CPEMI;
1116
1117   // Check to see if the CPE is already in-range.
1118   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1119                        true)) {
1120     DEBUG(dbgs() << "In range\n");
1121     return 1;
1122   }
1123
1124   // No.  Look for previously created clones of the CPE that are in range.
1125   unsigned CPI = CPEMI->getOperand(1).getIndex();
1126   std::vector<CPEntry> &CPEs = CPEntries[CPI];
1127   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1128     // We already tried this one
1129     if (CPEs[i].CPEMI == CPEMI)
1130       continue;
1131     // Removing CPEs can leave empty entries, skip
1132     if (CPEs[i].CPEMI == NULL)
1133       continue;
1134     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1135                      U.NegOk)) {
1136       DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1137                    << CPEs[i].CPI << "\n");
1138       // Point the CPUser node to the replacement
1139       U.CPEMI = CPEs[i].CPEMI;
1140       // Change the CPI in the instruction operand to refer to the clone.
1141       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1142         if (UserMI->getOperand(j).isCPI()) {
1143           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1144           break;
1145         }
1146       // Adjust the refcount of the clone...
1147       CPEs[i].RefCount++;
1148       // ...and the original.  If we didn't remove the old entry, none of the
1149       // addresses changed, so we don't need another pass.
1150       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1151     }
1152   }
1153   return 0;
1154 }
1155
1156 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1157 /// the specific unconditional branch instruction.
1158 static inline unsigned getUnconditionalBrDisp(int Opc) {
1159   switch (Opc) {
1160   case ARM::tB:
1161     return ((1<<10)-1)*2;
1162   case ARM::t2B:
1163     return ((1<<23)-1)*2;
1164   default:
1165     break;
1166   }
1167
1168   return ((1<<23)-1)*4;
1169 }
1170
1171 /// findAvailableWater - Look for an existing entry in the WaterList in which
1172 /// we can place the CPE referenced from U so it's within range of U's MI.
1173 /// Returns true if found, false if not.  If it returns true, WaterIter
1174 /// is set to the WaterList entry.  For Thumb, prefer water that will not
1175 /// introduce padding to water that will.  To ensure that this pass
1176 /// terminates, the CPE location for a particular CPUser is only allowed to
1177 /// move to a lower address, so search backward from the end of the list and
1178 /// prefer the first water that is in range.
1179 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1180                                       water_iterator &WaterIter) {
1181   if (WaterList.empty())
1182     return false;
1183
1184   unsigned BestGrowth = ~0u;
1185   for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1186        --IP) {
1187     MachineBasicBlock* WaterBB = *IP;
1188     // Check if water is in range and is either at a lower address than the
1189     // current "high water mark" or a new water block that was created since
1190     // the previous iteration by inserting an unconditional branch.  In the
1191     // latter case, we want to allow resetting the high water mark back to
1192     // this new water since we haven't seen it before.  Inserting branches
1193     // should be relatively uncommon and when it does happen, we want to be
1194     // sure to take advantage of it for all the CPEs near that block, so that
1195     // we don't insert more branches than necessary.
1196     unsigned Growth;
1197     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1198         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1199          NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1200       // This is the least amount of required padding seen so far.
1201       BestGrowth = Growth;
1202       WaterIter = IP;
1203       DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1204                    << " Growth=" << Growth << '\n');
1205
1206       // Keep looking unless it is perfect.
1207       if (BestGrowth == 0)
1208         return true;
1209     }
1210     if (IP == B)
1211       break;
1212   }
1213   return BestGrowth != ~0u;
1214 }
1215
1216 /// createNewWater - No existing WaterList entry will work for
1217 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1218 /// block is used if in range, and the conditional branch munged so control
1219 /// flow is correct.  Otherwise the block is split to create a hole with an
1220 /// unconditional branch around it.  In either case NewMBB is set to a
1221 /// block following which the new island can be inserted (the WaterList
1222 /// is not adjusted).
1223 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1224                                         unsigned UserOffset,
1225                                         MachineBasicBlock *&NewMBB) {
1226   CPUser &U = CPUsers[CPUserIndex];
1227   MachineInstr *UserMI = U.MI;
1228   MachineInstr *CPEMI  = U.CPEMI;
1229   unsigned CPELogAlign = getCPELogAlign(CPEMI);
1230   MachineBasicBlock *UserMBB = UserMI->getParent();
1231   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1232
1233   // If the block does not end in an unconditional branch already, and if the
1234   // end of the block is within range, make new water there.  (The addition
1235   // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1236   // Thumb2, 2 on Thumb1.
1237   if (BBHasFallthrough(UserMBB)) {
1238     // Size of branch to insert.
1239     unsigned Delta = isThumb1 ? 2 : 4;
1240     // Compute the offset where the CPE will begin.
1241     unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1242
1243     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1244       DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1245             << format(", expected CPE offset %#x\n", CPEOffset));
1246       NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1247       // Add an unconditional branch from UserMBB to fallthrough block.  Record
1248       // it for branch lengthening; this new branch will not get out of range,
1249       // but if the preceding conditional branch is out of range, the targets
1250       // will be exchanged, and the altered branch may be out of range, so the
1251       // machinery has to know about it.
1252       int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1253       if (!isThumb)
1254         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1255       else
1256         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1257           .addImm(ARMCC::AL).addReg(0);
1258       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1259       ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1260                                       MaxDisp, false, UncondBr));
1261       BBInfo[UserMBB->getNumber()].Size += Delta;
1262       adjustBBOffsetsAfter(UserMBB);
1263       return;
1264     }
1265   }
1266
1267   // What a big block.  Find a place within the block to split it.  This is a
1268   // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1269   // entries are 4 bytes: if instruction I references island CPE, and
1270   // instruction I+1 references CPE', it will not work well to put CPE as far
1271   // forward as possible, since then CPE' cannot immediately follow it (that
1272   // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1273   // need to create a new island.  So, we make a first guess, then walk through
1274   // the instructions between the one currently being looked at and the
1275   // possible insertion point, and make sure any other instructions that
1276   // reference CPEs will be able to use the same island area; if not, we back
1277   // up the insertion point.
1278
1279   // Try to split the block so it's fully aligned.  Compute the latest split
1280   // point where we can add a 4-byte branch instruction, and then align to
1281   // LogAlign which is the largest possible alignment in the function.
1282   unsigned LogAlign = MF->getAlignment();
1283   assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1284   unsigned KnownBits = UserBBI.internalKnownBits();
1285   unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1286   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1287   DEBUG(dbgs() << format("Split in middle of big block before %#x",
1288                          BaseInsertOffset));
1289
1290   // The 4 in the following is for the unconditional branch we'll be inserting
1291   // (allows for long branch on Thumb1).  Alignment of the island is handled
1292   // inside isOffsetInRange.
1293   BaseInsertOffset -= 4;
1294
1295   DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1296                << " la=" << LogAlign
1297                << " kb=" << KnownBits
1298                << " up=" << UPad << '\n');
1299
1300   // This could point off the end of the block if we've already got constant
1301   // pool entries following this block; only the last one is in the water list.
1302   // Back past any possible branches (allow for a conditional and a maximally
1303   // long unconditional).
1304   if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1305     BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1306       (isThumb1 ? 6 : 8);
1307   unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1308     CPEMI->getOperand(2).getImm();
1309   MachineBasicBlock::iterator MI = UserMI;
1310   ++MI;
1311   unsigned CPUIndex = CPUserIndex+1;
1312   unsigned NumCPUsers = CPUsers.size();
1313   MachineInstr *LastIT = 0;
1314   for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1315        Offset < BaseInsertOffset;
1316        Offset += TII->GetInstSizeInBytes(MI),
1317        MI = llvm::next(MI)) {
1318     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1319       CPUser &U = CPUsers[CPUIndex];
1320       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1321         // Shift intertion point by one unit of alignment so it is within reach.
1322         BaseInsertOffset -= 1u << LogAlign;
1323         EndInsertOffset  -= 1u << LogAlign;
1324       }
1325       // This is overly conservative, as we don't account for CPEMIs being
1326       // reused within the block, but it doesn't matter much.  Also assume CPEs
1327       // are added in order with alignment padding.  We may eventually be able
1328       // to pack the aligned CPEs better.
1329       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1330       CPUIndex++;
1331     }
1332
1333     // Remember the last IT instruction.
1334     if (MI->getOpcode() == ARM::t2IT)
1335       LastIT = MI;
1336   }
1337
1338   --MI;
1339
1340   // Avoid splitting an IT block.
1341   if (LastIT) {
1342     unsigned PredReg = 0;
1343     ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
1344     if (CC != ARMCC::AL)
1345       MI = LastIT;
1346   }
1347   NewMBB = splitBlockBeforeInstr(MI);
1348 }
1349
1350 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1351 /// is out-of-range.  If so, pick up the constant pool value and move it some
1352 /// place in-range.  Return true if we changed any addresses (thus must run
1353 /// another pass of branch lengthening), false otherwise.
1354 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1355   CPUser &U = CPUsers[CPUserIndex];
1356   MachineInstr *UserMI = U.MI;
1357   MachineInstr *CPEMI  = U.CPEMI;
1358   unsigned CPI = CPEMI->getOperand(1).getIndex();
1359   unsigned Size = CPEMI->getOperand(2).getImm();
1360   // Compute this only once, it's expensive.
1361   unsigned UserOffset = getUserOffset(U);
1362
1363   // See if the current entry is within range, or there is a clone of it
1364   // in range.
1365   int result = findInRangeCPEntry(U, UserOffset);
1366   if (result==1) return false;
1367   else if (result==2) return true;
1368
1369   // No existing clone of this CPE is within range.
1370   // We will be generating a new clone.  Get a UID for it.
1371   unsigned ID = AFI->createPICLabelUId();
1372
1373   // Look for water where we can place this CPE.
1374   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1375   MachineBasicBlock *NewMBB;
1376   water_iterator IP;
1377   if (findAvailableWater(U, UserOffset, IP)) {
1378     DEBUG(dbgs() << "Found water in range\n");
1379     MachineBasicBlock *WaterBB = *IP;
1380
1381     // If the original WaterList entry was "new water" on this iteration,
1382     // propagate that to the new island.  This is just keeping NewWaterList
1383     // updated to match the WaterList, which will be updated below.
1384     if (NewWaterList.count(WaterBB)) {
1385       NewWaterList.erase(WaterBB);
1386       NewWaterList.insert(NewIsland);
1387     }
1388     // The new CPE goes before the following block (NewMBB).
1389     NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1390
1391   } else {
1392     // No water found.
1393     DEBUG(dbgs() << "No water found\n");
1394     createNewWater(CPUserIndex, UserOffset, NewMBB);
1395
1396     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1397     // called while handling branches so that the water will be seen on the
1398     // next iteration for constant pools, but in this context, we don't want
1399     // it.  Check for this so it will be removed from the WaterList.
1400     // Also remove any entry from NewWaterList.
1401     MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1402     IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1403     if (IP != WaterList.end())
1404       NewWaterList.erase(WaterBB);
1405
1406     // We are adding new water.  Update NewWaterList.
1407     NewWaterList.insert(NewIsland);
1408   }
1409
1410   // Remove the original WaterList entry; we want subsequent insertions in
1411   // this vicinity to go after the one we're about to insert.  This
1412   // considerably reduces the number of times we have to move the same CPE
1413   // more than once and is also important to ensure the algorithm terminates.
1414   if (IP != WaterList.end())
1415     WaterList.erase(IP);
1416
1417   // Okay, we know we can put an island before NewMBB now, do it!
1418   MF->insert(NewMBB, NewIsland);
1419
1420   // Update internal data structures to account for the newly inserted MBB.
1421   updateForInsertedWaterBlock(NewIsland);
1422
1423   // Decrement the old entry, and remove it if refcount becomes 0.
1424   decrementCPEReferenceCount(CPI, CPEMI);
1425
1426   // Now that we have an island to add the CPE to, clone the original CPE and
1427   // add it to the island.
1428   U.HighWaterMark = NewIsland;
1429   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1430                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1431   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1432   ++NumCPEs;
1433
1434   // Mark the basic block as aligned as required by the const-pool entry.
1435   NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1436
1437   // Increase the size of the island block to account for the new entry.
1438   BBInfo[NewIsland->getNumber()].Size += Size;
1439   adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1440
1441   // Finally, change the CPI in the instruction operand to be ID.
1442   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1443     if (UserMI->getOperand(i).isCPI()) {
1444       UserMI->getOperand(i).setIndex(ID);
1445       break;
1446     }
1447
1448   DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1449         << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1450
1451   return true;
1452 }
1453
1454 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1455 /// sizes and offsets of impacted basic blocks.
1456 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1457   MachineBasicBlock *CPEBB = CPEMI->getParent();
1458   unsigned Size = CPEMI->getOperand(2).getImm();
1459   CPEMI->eraseFromParent();
1460   BBInfo[CPEBB->getNumber()].Size -= Size;
1461   // All succeeding offsets have the current size value added in, fix this.
1462   if (CPEBB->empty()) {
1463     BBInfo[CPEBB->getNumber()].Size = 0;
1464
1465     // This block no longer needs to be aligned. <rdar://problem/10534709>.
1466     CPEBB->setAlignment(0);
1467   } else
1468     // Entries are sorted by descending alignment, so realign from the front.
1469     CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1470
1471   adjustBBOffsetsAfter(CPEBB);
1472   // An island has only one predecessor BB and one successor BB. Check if
1473   // this BB's predecessor jumps directly to this BB's successor. This
1474   // shouldn't happen currently.
1475   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1476   // FIXME: remove the empty blocks after all the work is done?
1477 }
1478
1479 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1480 /// are zero.
1481 bool ARMConstantIslands::removeUnusedCPEntries() {
1482   unsigned MadeChange = false;
1483   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1484       std::vector<CPEntry> &CPEs = CPEntries[i];
1485       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1486         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1487           removeDeadCPEMI(CPEs[j].CPEMI);
1488           CPEs[j].CPEMI = NULL;
1489           MadeChange = true;
1490         }
1491       }
1492   }
1493   return MadeChange;
1494 }
1495
1496 /// isBBInRange - Returns true if the distance between specific MI and
1497 /// specific BB can fit in MI's displacement field.
1498 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1499                                      unsigned MaxDisp) {
1500   unsigned PCAdj      = isThumb ? 4 : 8;
1501   unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
1502   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1503
1504   DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1505                << " from BB#" << MI->getParent()->getNumber()
1506                << " max delta=" << MaxDisp
1507                << " from " << getOffsetOf(MI) << " to " << DestOffset
1508                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1509
1510   if (BrOffset <= DestOffset) {
1511     // Branch before the Dest.
1512     if (DestOffset-BrOffset <= MaxDisp)
1513       return true;
1514   } else {
1515     if (BrOffset-DestOffset <= MaxDisp)
1516       return true;
1517   }
1518   return false;
1519 }
1520
1521 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1522 /// away to fit in its displacement field.
1523 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1524   MachineInstr *MI = Br.MI;
1525   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1526
1527   // Check to see if the DestBB is already in-range.
1528   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1529     return false;
1530
1531   if (!Br.isCond)
1532     return fixupUnconditionalBr(Br);
1533   return fixupConditionalBr(Br);
1534 }
1535
1536 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1537 /// too far away to fit in its displacement field. If the LR register has been
1538 /// spilled in the epilogue, then we can use BL to implement a far jump.
1539 /// Otherwise, add an intermediate branch instruction to a branch.
1540 bool
1541 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1542   MachineInstr *MI = Br.MI;
1543   MachineBasicBlock *MBB = MI->getParent();
1544   if (!isThumb1)
1545     llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1546
1547   // Use BL to implement far jump.
1548   Br.MaxDisp = (1 << 21) * 2;
1549   MI->setDesc(TII->get(ARM::tBfar));
1550   BBInfo[MBB->getNumber()].Size += 2;
1551   adjustBBOffsetsAfter(MBB);
1552   HasFarJump = true;
1553   ++NumUBrFixed;
1554
1555   DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1556
1557   return true;
1558 }
1559
1560 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1561 /// far away to fit in its displacement field. It is converted to an inverse
1562 /// conditional branch + an unconditional branch to the destination.
1563 bool
1564 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1565   MachineInstr *MI = Br.MI;
1566   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1567
1568   // Add an unconditional branch to the destination and invert the branch
1569   // condition to jump over it:
1570   // blt L1
1571   // =>
1572   // bge L2
1573   // b   L1
1574   // L2:
1575   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1576   CC = ARMCC::getOppositeCondition(CC);
1577   unsigned CCReg = MI->getOperand(2).getReg();
1578
1579   // If the branch is at the end of its MBB and that has a fall-through block,
1580   // direct the updated conditional branch to the fall-through block. Otherwise,
1581   // split the MBB before the next instruction.
1582   MachineBasicBlock *MBB = MI->getParent();
1583   MachineInstr *BMI = &MBB->back();
1584   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1585
1586   ++NumCBrFixed;
1587   if (BMI != MI) {
1588     if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1589         BMI->getOpcode() == Br.UncondBr) {
1590       // Last MI in the BB is an unconditional branch. Can we simply invert the
1591       // condition and swap destinations:
1592       // beq L1
1593       // b   L2
1594       // =>
1595       // bne L2
1596       // b   L1
1597       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1598       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1599         DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
1600                      << *BMI);
1601         BMI->getOperand(0).setMBB(DestBB);
1602         MI->getOperand(0).setMBB(NewDest);
1603         MI->getOperand(1).setImm(CC);
1604         return true;
1605       }
1606     }
1607   }
1608
1609   if (NeedSplit) {
1610     splitBlockBeforeInstr(MI);
1611     // No need for the branch to the next block. We're adding an unconditional
1612     // branch to the destination.
1613     int delta = TII->GetInstSizeInBytes(&MBB->back());
1614     BBInfo[MBB->getNumber()].Size -= delta;
1615     MBB->back().eraseFromParent();
1616     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1617   }
1618   MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1619
1620   DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
1621                << " also invert condition and change dest. to BB#"
1622                << NextBB->getNumber() << "\n");
1623
1624   // Insert a new conditional branch and a new unconditional branch.
1625   // Also update the ImmBranch as well as adding a new entry for the new branch.
1626   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1627     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1628   Br.MI = &MBB->back();
1629   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1630   if (isThumb)
1631     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1632             .addImm(ARMCC::AL).addReg(0);
1633   else
1634     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1635   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1636   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1637   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1638
1639   // Remove the old conditional branch.  It may or may not still be in MBB.
1640   BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1641   MI->eraseFromParent();
1642   adjustBBOffsetsAfter(MBB);
1643   return true;
1644 }
1645
1646 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1647 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1648 /// to do this if tBfar is not used.
1649 bool ARMConstantIslands::undoLRSpillRestore() {
1650   bool MadeChange = false;
1651   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1652     MachineInstr *MI = PushPopMIs[i];
1653     // First two operands are predicates.
1654     if (MI->getOpcode() == ARM::tPOP_RET &&
1655         MI->getOperand(2).getReg() == ARM::PC &&
1656         MI->getNumExplicitOperands() == 3) {
1657       // Create the new insn and copy the predicate from the old.
1658       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1659         .addOperand(MI->getOperand(0))
1660         .addOperand(MI->getOperand(1));
1661       MI->eraseFromParent();
1662       MadeChange = true;
1663     }
1664   }
1665   return MadeChange;
1666 }
1667
1668 // mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
1669 // below may shrink MI.
1670 bool
1671 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1672   switch(MI->getOpcode()) {
1673     // optimizeThumb2Instructions.
1674     case ARM::t2LEApcrel:
1675     case ARM::t2LDRpci:
1676     // optimizeThumb2Branches.
1677     case ARM::t2B:
1678     case ARM::t2Bcc:
1679     case ARM::tBcc:
1680     // optimizeThumb2JumpTables.
1681     case ARM::t2BR_JT:
1682       return true;
1683   }
1684   return false;
1685 }
1686
1687 bool ARMConstantIslands::optimizeThumb2Instructions() {
1688   bool MadeChange = false;
1689
1690   // Shrink ADR and LDR from constantpool.
1691   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1692     CPUser &U = CPUsers[i];
1693     unsigned Opcode = U.MI->getOpcode();
1694     unsigned NewOpc = 0;
1695     unsigned Scale = 1;
1696     unsigned Bits = 0;
1697     switch (Opcode) {
1698     default: break;
1699     case ARM::t2LEApcrel:
1700       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1701         NewOpc = ARM::tLEApcrel;
1702         Bits = 8;
1703         Scale = 4;
1704       }
1705       break;
1706     case ARM::t2LDRpci:
1707       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1708         NewOpc = ARM::tLDRpci;
1709         Bits = 8;
1710         Scale = 4;
1711       }
1712       break;
1713     }
1714
1715     if (!NewOpc)
1716       continue;
1717
1718     unsigned UserOffset = getUserOffset(U);
1719     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1720
1721     // Be conservative with inline asm.
1722     if (!U.KnownAlignment)
1723       MaxOffs -= 2;
1724
1725     // FIXME: Check if offset is multiple of scale if scale is not 4.
1726     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1727       DEBUG(dbgs() << "Shrink: " << *U.MI);
1728       U.MI->setDesc(TII->get(NewOpc));
1729       MachineBasicBlock *MBB = U.MI->getParent();
1730       BBInfo[MBB->getNumber()].Size -= 2;
1731       adjustBBOffsetsAfter(MBB);
1732       ++NumT2CPShrunk;
1733       MadeChange = true;
1734     }
1735   }
1736
1737   MadeChange |= optimizeThumb2Branches();
1738   MadeChange |= optimizeThumb2JumpTables();
1739   return MadeChange;
1740 }
1741
1742 bool ARMConstantIslands::optimizeThumb2Branches() {
1743   bool MadeChange = false;
1744
1745   for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1746     ImmBranch &Br = ImmBranches[i];
1747     unsigned Opcode = Br.MI->getOpcode();
1748     unsigned NewOpc = 0;
1749     unsigned Scale = 1;
1750     unsigned Bits = 0;
1751     switch (Opcode) {
1752     default: break;
1753     case ARM::t2B:
1754       NewOpc = ARM::tB;
1755       Bits = 11;
1756       Scale = 2;
1757       break;
1758     case ARM::t2Bcc: {
1759       NewOpc = ARM::tBcc;
1760       Bits = 8;
1761       Scale = 2;
1762       break;
1763     }
1764     }
1765     if (NewOpc) {
1766       unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1767       MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1768       if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1769         DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1770         Br.MI->setDesc(TII->get(NewOpc));
1771         MachineBasicBlock *MBB = Br.MI->getParent();
1772         BBInfo[MBB->getNumber()].Size -= 2;
1773         adjustBBOffsetsAfter(MBB);
1774         ++NumT2BrShrunk;
1775         MadeChange = true;
1776       }
1777     }
1778
1779     Opcode = Br.MI->getOpcode();
1780     if (Opcode != ARM::tBcc)
1781       continue;
1782
1783     // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1784     // so this transformation is not safe.
1785     if (!Br.MI->killsRegister(ARM::CPSR))
1786       continue;
1787
1788     NewOpc = 0;
1789     unsigned PredReg = 0;
1790     ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
1791     if (Pred == ARMCC::EQ)
1792       NewOpc = ARM::tCBZ;
1793     else if (Pred == ARMCC::NE)
1794       NewOpc = ARM::tCBNZ;
1795     if (!NewOpc)
1796       continue;
1797     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1798     // Check if the distance is within 126. Subtract starting offset by 2
1799     // because the cmp will be eliminated.
1800     unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1801     unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1802     if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1803       MachineBasicBlock::iterator CmpMI = Br.MI;
1804       if (CmpMI != Br.MI->getParent()->begin()) {
1805         --CmpMI;
1806         if (CmpMI->getOpcode() == ARM::tCMPi8) {
1807           unsigned Reg = CmpMI->getOperand(0).getReg();
1808           Pred = getInstrPredicate(CmpMI, PredReg);
1809           if (Pred == ARMCC::AL &&
1810               CmpMI->getOperand(1).getImm() == 0 &&
1811               isARMLowRegister(Reg)) {
1812             MachineBasicBlock *MBB = Br.MI->getParent();
1813             DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1814             MachineInstr *NewBR =
1815               BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1816               .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1817             CmpMI->eraseFromParent();
1818             Br.MI->eraseFromParent();
1819             Br.MI = NewBR;
1820             BBInfo[MBB->getNumber()].Size -= 2;
1821             adjustBBOffsetsAfter(MBB);
1822             ++NumCBZ;
1823             MadeChange = true;
1824           }
1825         }
1826       }
1827     }
1828   }
1829
1830   return MadeChange;
1831 }
1832
1833 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1834 /// jumptables when it's possible.
1835 bool ARMConstantIslands::optimizeThumb2JumpTables() {
1836   bool MadeChange = false;
1837
1838   // FIXME: After the tables are shrunk, can we get rid some of the
1839   // constantpool tables?
1840   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1841   if (MJTI == 0) return false;
1842
1843   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1844   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1845     MachineInstr *MI = T2JumpTables[i];
1846     const MCInstrDesc &MCID = MI->getDesc();
1847     unsigned NumOps = MCID.getNumOperands();
1848     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1849     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1850     unsigned JTI = JTOP.getIndex();
1851     assert(JTI < JT.size());
1852
1853     bool ByteOk = true;
1854     bool HalfWordOk = true;
1855     unsigned JTOffset = getOffsetOf(MI) + 4;
1856     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1857     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1858       MachineBasicBlock *MBB = JTBBs[j];
1859       unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1860       // Negative offset is not ok. FIXME: We should change BB layout to make
1861       // sure all the branches are forward.
1862       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1863         ByteOk = false;
1864       unsigned TBHLimit = ((1<<16)-1)*2;
1865       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1866         HalfWordOk = false;
1867       if (!ByteOk && !HalfWordOk)
1868         break;
1869     }
1870
1871     if (ByteOk || HalfWordOk) {
1872       MachineBasicBlock *MBB = MI->getParent();
1873       unsigned BaseReg = MI->getOperand(0).getReg();
1874       bool BaseRegKill = MI->getOperand(0).isKill();
1875       if (!BaseRegKill)
1876         continue;
1877       unsigned IdxReg = MI->getOperand(1).getReg();
1878       bool IdxRegKill = MI->getOperand(1).isKill();
1879
1880       // Scan backwards to find the instruction that defines the base
1881       // register. Due to post-RA scheduling, we can't count on it
1882       // immediately preceding the branch instruction.
1883       MachineBasicBlock::iterator PrevI = MI;
1884       MachineBasicBlock::iterator B = MBB->begin();
1885       while (PrevI != B && !PrevI->definesRegister(BaseReg))
1886         --PrevI;
1887
1888       // If for some reason we didn't find it, we can't do anything, so
1889       // just skip this one.
1890       if (!PrevI->definesRegister(BaseReg))
1891         continue;
1892
1893       MachineInstr *AddrMI = PrevI;
1894       bool OptOk = true;
1895       // Examine the instruction that calculates the jumptable entry address.
1896       // Make sure it only defines the base register and kills any uses
1897       // other than the index register.
1898       for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1899         const MachineOperand &MO = AddrMI->getOperand(k);
1900         if (!MO.isReg() || !MO.getReg())
1901           continue;
1902         if (MO.isDef() && MO.getReg() != BaseReg) {
1903           OptOk = false;
1904           break;
1905         }
1906         if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1907           OptOk = false;
1908           break;
1909         }
1910       }
1911       if (!OptOk)
1912         continue;
1913
1914       // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1915       // that gave us the initial base register definition.
1916       for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1917         ;
1918
1919       // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1920       // to delete it as well.
1921       MachineInstr *LeaMI = PrevI;
1922       if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1923            LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1924           LeaMI->getOperand(0).getReg() != BaseReg)
1925         OptOk = false;
1926
1927       if (!OptOk)
1928         continue;
1929
1930       DEBUG(dbgs() << "Shrink JT: " << *MI << "     addr: " << *AddrMI
1931                    << "      lea: " << *LeaMI);
1932       unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1933       MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1934         .addReg(IdxReg, getKillRegState(IdxRegKill))
1935         .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1936         .addImm(MI->getOperand(JTOpIdx+1).getImm());
1937       DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
1938       // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1939       // is 2-byte aligned. For now, asm printer will fix it up.
1940       unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1941       unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1942       OrigSize += TII->GetInstSizeInBytes(LeaMI);
1943       OrigSize += TII->GetInstSizeInBytes(MI);
1944
1945       AddrMI->eraseFromParent();
1946       LeaMI->eraseFromParent();
1947       MI->eraseFromParent();
1948
1949       int delta = OrigSize - NewSize;
1950       BBInfo[MBB->getNumber()].Size -= delta;
1951       adjustBBOffsetsAfter(MBB);
1952
1953       ++NumTBs;
1954       MadeChange = true;
1955     }
1956   }
1957
1958   return MadeChange;
1959 }
1960
1961 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
1962 /// jump tables always branch forwards, since that's what tbb and tbh need.
1963 bool ARMConstantIslands::reorderThumb2JumpTables() {
1964   bool MadeChange = false;
1965
1966   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1967   if (MJTI == 0) return false;
1968
1969   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1970   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1971     MachineInstr *MI = T2JumpTables[i];
1972     const MCInstrDesc &MCID = MI->getDesc();
1973     unsigned NumOps = MCID.getNumOperands();
1974     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1975     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1976     unsigned JTI = JTOP.getIndex();
1977     assert(JTI < JT.size());
1978
1979     // We prefer if target blocks for the jump table come after the jump
1980     // instruction so we can use TB[BH]. Loop through the target blocks
1981     // and try to adjust them such that that's true.
1982     int JTNumber = MI->getParent()->getNumber();
1983     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1984     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1985       MachineBasicBlock *MBB = JTBBs[j];
1986       int DTNumber = MBB->getNumber();
1987
1988       if (DTNumber < JTNumber) {
1989         // The destination precedes the switch. Try to move the block forward
1990         // so we have a positive offset.
1991         MachineBasicBlock *NewBB =
1992           adjustJTTargetBlockForward(MBB, MI->getParent());
1993         if (NewBB)
1994           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1995         MadeChange = true;
1996       }
1997     }
1998   }
1999
2000   return MadeChange;
2001 }
2002
2003 MachineBasicBlock *ARMConstantIslands::
2004 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2005   // If the destination block is terminated by an unconditional branch,
2006   // try to move it; otherwise, create a new block following the jump
2007   // table that branches back to the actual target. This is a very simple
2008   // heuristic. FIXME: We can definitely improve it.
2009   MachineBasicBlock *TBB = 0, *FBB = 0;
2010   SmallVector<MachineOperand, 4> Cond;
2011   SmallVector<MachineOperand, 4> CondPrior;
2012   MachineFunction::iterator BBi = BB;
2013   MachineFunction::iterator OldPrior = prior(BBi);
2014
2015   // If the block terminator isn't analyzable, don't try to move the block
2016   bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
2017
2018   // If the block ends in an unconditional branch, move it. The prior block
2019   // has to have an analyzable terminator for us to move this one. Be paranoid
2020   // and make sure we're not trying to move the entry block of the function.
2021   if (!B && Cond.empty() && BB != MF->begin() &&
2022       !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2023     BB->moveAfter(JTBB);
2024     OldPrior->updateTerminator();
2025     BB->updateTerminator();
2026     // Update numbering to account for the block being moved.
2027     MF->RenumberBlocks();
2028     ++NumJTMoved;
2029     return NULL;
2030   }
2031
2032   // Create a new MBB for the code after the jump BB.
2033   MachineBasicBlock *NewBB =
2034     MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2035   MachineFunction::iterator MBBI = JTBB; ++MBBI;
2036   MF->insert(MBBI, NewBB);
2037
2038   // Add an unconditional branch from NewBB to BB.
2039   // There doesn't seem to be meaningful DebugInfo available; this doesn't
2040   // correspond directly to anything in the source.
2041   assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
2042   BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2043           .addImm(ARMCC::AL).addReg(0);
2044
2045   // Update internal data structures to account for the newly inserted MBB.
2046   MF->RenumberBlocks(NewBB);
2047
2048   // Update the CFG.
2049   NewBB->addSuccessor(BB);
2050   JTBB->removeSuccessor(BB);
2051   JTBB->addSuccessor(NewBB);
2052
2053   ++NumJTInserted;
2054   return NewBB;
2055 }