Fix a problem with blocks that need to be split twice.
[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 + 8 >= UserBBI.postOffset()) {
1305     BaseInsertOffset = UserBBI.postOffset() - UPad - 8;
1306     DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1307   }
1308   unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1309     CPEMI->getOperand(2).getImm();
1310   MachineBasicBlock::iterator MI = UserMI;
1311   ++MI;
1312   unsigned CPUIndex = CPUserIndex+1;
1313   unsigned NumCPUsers = CPUsers.size();
1314   MachineInstr *LastIT = 0;
1315   for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1316        Offset < BaseInsertOffset;
1317        Offset += TII->GetInstSizeInBytes(MI),
1318        MI = llvm::next(MI)) {
1319     assert(MI != UserMBB->end() && "Fell off end of block");
1320     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1321       CPUser &U = CPUsers[CPUIndex];
1322       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1323         // Shift intertion point by one unit of alignment so it is within reach.
1324         BaseInsertOffset -= 1u << LogAlign;
1325         EndInsertOffset  -= 1u << LogAlign;
1326       }
1327       // This is overly conservative, as we don't account for CPEMIs being
1328       // reused within the block, but it doesn't matter much.  Also assume CPEs
1329       // are added in order with alignment padding.  We may eventually be able
1330       // to pack the aligned CPEs better.
1331       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1332       CPUIndex++;
1333     }
1334
1335     // Remember the last IT instruction.
1336     if (MI->getOpcode() == ARM::t2IT)
1337       LastIT = MI;
1338   }
1339
1340   --MI;
1341
1342   // Avoid splitting an IT block.
1343   if (LastIT) {
1344     unsigned PredReg = 0;
1345     ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
1346     if (CC != ARMCC::AL)
1347       MI = LastIT;
1348   }
1349   NewMBB = splitBlockBeforeInstr(MI);
1350 }
1351
1352 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1353 /// is out-of-range.  If so, pick up the constant pool value and move it some
1354 /// place in-range.  Return true if we changed any addresses (thus must run
1355 /// another pass of branch lengthening), false otherwise.
1356 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1357   CPUser &U = CPUsers[CPUserIndex];
1358   MachineInstr *UserMI = U.MI;
1359   MachineInstr *CPEMI  = U.CPEMI;
1360   unsigned CPI = CPEMI->getOperand(1).getIndex();
1361   unsigned Size = CPEMI->getOperand(2).getImm();
1362   // Compute this only once, it's expensive.
1363   unsigned UserOffset = getUserOffset(U);
1364
1365   // See if the current entry is within range, or there is a clone of it
1366   // in range.
1367   int result = findInRangeCPEntry(U, UserOffset);
1368   if (result==1) return false;
1369   else if (result==2) return true;
1370
1371   // No existing clone of this CPE is within range.
1372   // We will be generating a new clone.  Get a UID for it.
1373   unsigned ID = AFI->createPICLabelUId();
1374
1375   // Look for water where we can place this CPE.
1376   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1377   MachineBasicBlock *NewMBB;
1378   water_iterator IP;
1379   if (findAvailableWater(U, UserOffset, IP)) {
1380     DEBUG(dbgs() << "Found water in range\n");
1381     MachineBasicBlock *WaterBB = *IP;
1382
1383     // If the original WaterList entry was "new water" on this iteration,
1384     // propagate that to the new island.  This is just keeping NewWaterList
1385     // updated to match the WaterList, which will be updated below.
1386     if (NewWaterList.count(WaterBB)) {
1387       NewWaterList.erase(WaterBB);
1388       NewWaterList.insert(NewIsland);
1389     }
1390     // The new CPE goes before the following block (NewMBB).
1391     NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1392
1393   } else {
1394     // No water found.
1395     DEBUG(dbgs() << "No water found\n");
1396     createNewWater(CPUserIndex, UserOffset, NewMBB);
1397
1398     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1399     // called while handling branches so that the water will be seen on the
1400     // next iteration for constant pools, but in this context, we don't want
1401     // it.  Check for this so it will be removed from the WaterList.
1402     // Also remove any entry from NewWaterList.
1403     MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1404     IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1405     if (IP != WaterList.end())
1406       NewWaterList.erase(WaterBB);
1407
1408     // We are adding new water.  Update NewWaterList.
1409     NewWaterList.insert(NewIsland);
1410   }
1411
1412   // Remove the original WaterList entry; we want subsequent insertions in
1413   // this vicinity to go after the one we're about to insert.  This
1414   // considerably reduces the number of times we have to move the same CPE
1415   // more than once and is also important to ensure the algorithm terminates.
1416   if (IP != WaterList.end())
1417     WaterList.erase(IP);
1418
1419   // Okay, we know we can put an island before NewMBB now, do it!
1420   MF->insert(NewMBB, NewIsland);
1421
1422   // Update internal data structures to account for the newly inserted MBB.
1423   updateForInsertedWaterBlock(NewIsland);
1424
1425   // Decrement the old entry, and remove it if refcount becomes 0.
1426   decrementCPEReferenceCount(CPI, CPEMI);
1427
1428   // Now that we have an island to add the CPE to, clone the original CPE and
1429   // add it to the island.
1430   U.HighWaterMark = NewIsland;
1431   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1432                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1433   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1434   ++NumCPEs;
1435
1436   // Mark the basic block as aligned as required by the const-pool entry.
1437   NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1438
1439   // Increase the size of the island block to account for the new entry.
1440   BBInfo[NewIsland->getNumber()].Size += Size;
1441   adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1442
1443   // Finally, change the CPI in the instruction operand to be ID.
1444   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1445     if (UserMI->getOperand(i).isCPI()) {
1446       UserMI->getOperand(i).setIndex(ID);
1447       break;
1448     }
1449
1450   DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1451         << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1452
1453   return true;
1454 }
1455
1456 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1457 /// sizes and offsets of impacted basic blocks.
1458 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1459   MachineBasicBlock *CPEBB = CPEMI->getParent();
1460   unsigned Size = CPEMI->getOperand(2).getImm();
1461   CPEMI->eraseFromParent();
1462   BBInfo[CPEBB->getNumber()].Size -= Size;
1463   // All succeeding offsets have the current size value added in, fix this.
1464   if (CPEBB->empty()) {
1465     BBInfo[CPEBB->getNumber()].Size = 0;
1466
1467     // This block no longer needs to be aligned. <rdar://problem/10534709>.
1468     CPEBB->setAlignment(0);
1469   } else
1470     // Entries are sorted by descending alignment, so realign from the front.
1471     CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1472
1473   adjustBBOffsetsAfter(CPEBB);
1474   // An island has only one predecessor BB and one successor BB. Check if
1475   // this BB's predecessor jumps directly to this BB's successor. This
1476   // shouldn't happen currently.
1477   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1478   // FIXME: remove the empty blocks after all the work is done?
1479 }
1480
1481 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1482 /// are zero.
1483 bool ARMConstantIslands::removeUnusedCPEntries() {
1484   unsigned MadeChange = false;
1485   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1486       std::vector<CPEntry> &CPEs = CPEntries[i];
1487       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1488         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1489           removeDeadCPEMI(CPEs[j].CPEMI);
1490           CPEs[j].CPEMI = NULL;
1491           MadeChange = true;
1492         }
1493       }
1494   }
1495   return MadeChange;
1496 }
1497
1498 /// isBBInRange - Returns true if the distance between specific MI and
1499 /// specific BB can fit in MI's displacement field.
1500 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1501                                      unsigned MaxDisp) {
1502   unsigned PCAdj      = isThumb ? 4 : 8;
1503   unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
1504   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1505
1506   DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1507                << " from BB#" << MI->getParent()->getNumber()
1508                << " max delta=" << MaxDisp
1509                << " from " << getOffsetOf(MI) << " to " << DestOffset
1510                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1511
1512   if (BrOffset <= DestOffset) {
1513     // Branch before the Dest.
1514     if (DestOffset-BrOffset <= MaxDisp)
1515       return true;
1516   } else {
1517     if (BrOffset-DestOffset <= MaxDisp)
1518       return true;
1519   }
1520   return false;
1521 }
1522
1523 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1524 /// away to fit in its displacement field.
1525 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1526   MachineInstr *MI = Br.MI;
1527   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1528
1529   // Check to see if the DestBB is already in-range.
1530   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1531     return false;
1532
1533   if (!Br.isCond)
1534     return fixupUnconditionalBr(Br);
1535   return fixupConditionalBr(Br);
1536 }
1537
1538 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1539 /// too far away to fit in its displacement field. If the LR register has been
1540 /// spilled in the epilogue, then we can use BL to implement a far jump.
1541 /// Otherwise, add an intermediate branch instruction to a branch.
1542 bool
1543 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1544   MachineInstr *MI = Br.MI;
1545   MachineBasicBlock *MBB = MI->getParent();
1546   if (!isThumb1)
1547     llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1548
1549   // Use BL to implement far jump.
1550   Br.MaxDisp = (1 << 21) * 2;
1551   MI->setDesc(TII->get(ARM::tBfar));
1552   BBInfo[MBB->getNumber()].Size += 2;
1553   adjustBBOffsetsAfter(MBB);
1554   HasFarJump = true;
1555   ++NumUBrFixed;
1556
1557   DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1558
1559   return true;
1560 }
1561
1562 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1563 /// far away to fit in its displacement field. It is converted to an inverse
1564 /// conditional branch + an unconditional branch to the destination.
1565 bool
1566 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1567   MachineInstr *MI = Br.MI;
1568   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1569
1570   // Add an unconditional branch to the destination and invert the branch
1571   // condition to jump over it:
1572   // blt L1
1573   // =>
1574   // bge L2
1575   // b   L1
1576   // L2:
1577   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1578   CC = ARMCC::getOppositeCondition(CC);
1579   unsigned CCReg = MI->getOperand(2).getReg();
1580
1581   // If the branch is at the end of its MBB and that has a fall-through block,
1582   // direct the updated conditional branch to the fall-through block. Otherwise,
1583   // split the MBB before the next instruction.
1584   MachineBasicBlock *MBB = MI->getParent();
1585   MachineInstr *BMI = &MBB->back();
1586   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1587
1588   ++NumCBrFixed;
1589   if (BMI != MI) {
1590     if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1591         BMI->getOpcode() == Br.UncondBr) {
1592       // Last MI in the BB is an unconditional branch. Can we simply invert the
1593       // condition and swap destinations:
1594       // beq L1
1595       // b   L2
1596       // =>
1597       // bne L2
1598       // b   L1
1599       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1600       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1601         DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
1602                      << *BMI);
1603         BMI->getOperand(0).setMBB(DestBB);
1604         MI->getOperand(0).setMBB(NewDest);
1605         MI->getOperand(1).setImm(CC);
1606         return true;
1607       }
1608     }
1609   }
1610
1611   if (NeedSplit) {
1612     splitBlockBeforeInstr(MI);
1613     // No need for the branch to the next block. We're adding an unconditional
1614     // branch to the destination.
1615     int delta = TII->GetInstSizeInBytes(&MBB->back());
1616     BBInfo[MBB->getNumber()].Size -= delta;
1617     MBB->back().eraseFromParent();
1618     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1619   }
1620   MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1621
1622   DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
1623                << " also invert condition and change dest. to BB#"
1624                << NextBB->getNumber() << "\n");
1625
1626   // Insert a new conditional branch and a new unconditional branch.
1627   // Also update the ImmBranch as well as adding a new entry for the new branch.
1628   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1629     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1630   Br.MI = &MBB->back();
1631   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1632   if (isThumb)
1633     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1634             .addImm(ARMCC::AL).addReg(0);
1635   else
1636     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1637   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1638   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1639   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1640
1641   // Remove the old conditional branch.  It may or may not still be in MBB.
1642   BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1643   MI->eraseFromParent();
1644   adjustBBOffsetsAfter(MBB);
1645   return true;
1646 }
1647
1648 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1649 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1650 /// to do this if tBfar is not used.
1651 bool ARMConstantIslands::undoLRSpillRestore() {
1652   bool MadeChange = false;
1653   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1654     MachineInstr *MI = PushPopMIs[i];
1655     // First two operands are predicates.
1656     if (MI->getOpcode() == ARM::tPOP_RET &&
1657         MI->getOperand(2).getReg() == ARM::PC &&
1658         MI->getNumExplicitOperands() == 3) {
1659       // Create the new insn and copy the predicate from the old.
1660       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1661         .addOperand(MI->getOperand(0))
1662         .addOperand(MI->getOperand(1));
1663       MI->eraseFromParent();
1664       MadeChange = true;
1665     }
1666   }
1667   return MadeChange;
1668 }
1669
1670 // mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
1671 // below may shrink MI.
1672 bool
1673 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1674   switch(MI->getOpcode()) {
1675     // optimizeThumb2Instructions.
1676     case ARM::t2LEApcrel:
1677     case ARM::t2LDRpci:
1678     // optimizeThumb2Branches.
1679     case ARM::t2B:
1680     case ARM::t2Bcc:
1681     case ARM::tBcc:
1682     // optimizeThumb2JumpTables.
1683     case ARM::t2BR_JT:
1684       return true;
1685   }
1686   return false;
1687 }
1688
1689 bool ARMConstantIslands::optimizeThumb2Instructions() {
1690   bool MadeChange = false;
1691
1692   // Shrink ADR and LDR from constantpool.
1693   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1694     CPUser &U = CPUsers[i];
1695     unsigned Opcode = U.MI->getOpcode();
1696     unsigned NewOpc = 0;
1697     unsigned Scale = 1;
1698     unsigned Bits = 0;
1699     switch (Opcode) {
1700     default: break;
1701     case ARM::t2LEApcrel:
1702       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1703         NewOpc = ARM::tLEApcrel;
1704         Bits = 8;
1705         Scale = 4;
1706       }
1707       break;
1708     case ARM::t2LDRpci:
1709       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1710         NewOpc = ARM::tLDRpci;
1711         Bits = 8;
1712         Scale = 4;
1713       }
1714       break;
1715     }
1716
1717     if (!NewOpc)
1718       continue;
1719
1720     unsigned UserOffset = getUserOffset(U);
1721     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1722
1723     // Be conservative with inline asm.
1724     if (!U.KnownAlignment)
1725       MaxOffs -= 2;
1726
1727     // FIXME: Check if offset is multiple of scale if scale is not 4.
1728     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1729       DEBUG(dbgs() << "Shrink: " << *U.MI);
1730       U.MI->setDesc(TII->get(NewOpc));
1731       MachineBasicBlock *MBB = U.MI->getParent();
1732       BBInfo[MBB->getNumber()].Size -= 2;
1733       adjustBBOffsetsAfter(MBB);
1734       ++NumT2CPShrunk;
1735       MadeChange = true;
1736     }
1737   }
1738
1739   MadeChange |= optimizeThumb2Branches();
1740   MadeChange |= optimizeThumb2JumpTables();
1741   return MadeChange;
1742 }
1743
1744 bool ARMConstantIslands::optimizeThumb2Branches() {
1745   bool MadeChange = false;
1746
1747   for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1748     ImmBranch &Br = ImmBranches[i];
1749     unsigned Opcode = Br.MI->getOpcode();
1750     unsigned NewOpc = 0;
1751     unsigned Scale = 1;
1752     unsigned Bits = 0;
1753     switch (Opcode) {
1754     default: break;
1755     case ARM::t2B:
1756       NewOpc = ARM::tB;
1757       Bits = 11;
1758       Scale = 2;
1759       break;
1760     case ARM::t2Bcc: {
1761       NewOpc = ARM::tBcc;
1762       Bits = 8;
1763       Scale = 2;
1764       break;
1765     }
1766     }
1767     if (NewOpc) {
1768       unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1769       MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1770       if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1771         DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1772         Br.MI->setDesc(TII->get(NewOpc));
1773         MachineBasicBlock *MBB = Br.MI->getParent();
1774         BBInfo[MBB->getNumber()].Size -= 2;
1775         adjustBBOffsetsAfter(MBB);
1776         ++NumT2BrShrunk;
1777         MadeChange = true;
1778       }
1779     }
1780
1781     Opcode = Br.MI->getOpcode();
1782     if (Opcode != ARM::tBcc)
1783       continue;
1784
1785     // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1786     // so this transformation is not safe.
1787     if (!Br.MI->killsRegister(ARM::CPSR))
1788       continue;
1789
1790     NewOpc = 0;
1791     unsigned PredReg = 0;
1792     ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
1793     if (Pred == ARMCC::EQ)
1794       NewOpc = ARM::tCBZ;
1795     else if (Pred == ARMCC::NE)
1796       NewOpc = ARM::tCBNZ;
1797     if (!NewOpc)
1798       continue;
1799     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1800     // Check if the distance is within 126. Subtract starting offset by 2
1801     // because the cmp will be eliminated.
1802     unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1803     unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1804     if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1805       MachineBasicBlock::iterator CmpMI = Br.MI;
1806       if (CmpMI != Br.MI->getParent()->begin()) {
1807         --CmpMI;
1808         if (CmpMI->getOpcode() == ARM::tCMPi8) {
1809           unsigned Reg = CmpMI->getOperand(0).getReg();
1810           Pred = getInstrPredicate(CmpMI, PredReg);
1811           if (Pred == ARMCC::AL &&
1812               CmpMI->getOperand(1).getImm() == 0 &&
1813               isARMLowRegister(Reg)) {
1814             MachineBasicBlock *MBB = Br.MI->getParent();
1815             DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1816             MachineInstr *NewBR =
1817               BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1818               .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1819             CmpMI->eraseFromParent();
1820             Br.MI->eraseFromParent();
1821             Br.MI = NewBR;
1822             BBInfo[MBB->getNumber()].Size -= 2;
1823             adjustBBOffsetsAfter(MBB);
1824             ++NumCBZ;
1825             MadeChange = true;
1826           }
1827         }
1828       }
1829     }
1830   }
1831
1832   return MadeChange;
1833 }
1834
1835 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1836 /// jumptables when it's possible.
1837 bool ARMConstantIslands::optimizeThumb2JumpTables() {
1838   bool MadeChange = false;
1839
1840   // FIXME: After the tables are shrunk, can we get rid some of the
1841   // constantpool tables?
1842   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1843   if (MJTI == 0) return false;
1844
1845   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1846   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1847     MachineInstr *MI = T2JumpTables[i];
1848     const MCInstrDesc &MCID = MI->getDesc();
1849     unsigned NumOps = MCID.getNumOperands();
1850     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1851     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1852     unsigned JTI = JTOP.getIndex();
1853     assert(JTI < JT.size());
1854
1855     bool ByteOk = true;
1856     bool HalfWordOk = true;
1857     unsigned JTOffset = getOffsetOf(MI) + 4;
1858     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1859     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1860       MachineBasicBlock *MBB = JTBBs[j];
1861       unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1862       // Negative offset is not ok. FIXME: We should change BB layout to make
1863       // sure all the branches are forward.
1864       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1865         ByteOk = false;
1866       unsigned TBHLimit = ((1<<16)-1)*2;
1867       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1868         HalfWordOk = false;
1869       if (!ByteOk && !HalfWordOk)
1870         break;
1871     }
1872
1873     if (ByteOk || HalfWordOk) {
1874       MachineBasicBlock *MBB = MI->getParent();
1875       unsigned BaseReg = MI->getOperand(0).getReg();
1876       bool BaseRegKill = MI->getOperand(0).isKill();
1877       if (!BaseRegKill)
1878         continue;
1879       unsigned IdxReg = MI->getOperand(1).getReg();
1880       bool IdxRegKill = MI->getOperand(1).isKill();
1881
1882       // Scan backwards to find the instruction that defines the base
1883       // register. Due to post-RA scheduling, we can't count on it
1884       // immediately preceding the branch instruction.
1885       MachineBasicBlock::iterator PrevI = MI;
1886       MachineBasicBlock::iterator B = MBB->begin();
1887       while (PrevI != B && !PrevI->definesRegister(BaseReg))
1888         --PrevI;
1889
1890       // If for some reason we didn't find it, we can't do anything, so
1891       // just skip this one.
1892       if (!PrevI->definesRegister(BaseReg))
1893         continue;
1894
1895       MachineInstr *AddrMI = PrevI;
1896       bool OptOk = true;
1897       // Examine the instruction that calculates the jumptable entry address.
1898       // Make sure it only defines the base register and kills any uses
1899       // other than the index register.
1900       for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1901         const MachineOperand &MO = AddrMI->getOperand(k);
1902         if (!MO.isReg() || !MO.getReg())
1903           continue;
1904         if (MO.isDef() && MO.getReg() != BaseReg) {
1905           OptOk = false;
1906           break;
1907         }
1908         if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1909           OptOk = false;
1910           break;
1911         }
1912       }
1913       if (!OptOk)
1914         continue;
1915
1916       // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1917       // that gave us the initial base register definition.
1918       for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1919         ;
1920
1921       // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1922       // to delete it as well.
1923       MachineInstr *LeaMI = PrevI;
1924       if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1925            LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1926           LeaMI->getOperand(0).getReg() != BaseReg)
1927         OptOk = false;
1928
1929       if (!OptOk)
1930         continue;
1931
1932       DEBUG(dbgs() << "Shrink JT: " << *MI << "     addr: " << *AddrMI
1933                    << "      lea: " << *LeaMI);
1934       unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1935       MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1936         .addReg(IdxReg, getKillRegState(IdxRegKill))
1937         .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1938         .addImm(MI->getOperand(JTOpIdx+1).getImm());
1939       DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
1940       // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1941       // is 2-byte aligned. For now, asm printer will fix it up.
1942       unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1943       unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1944       OrigSize += TII->GetInstSizeInBytes(LeaMI);
1945       OrigSize += TII->GetInstSizeInBytes(MI);
1946
1947       AddrMI->eraseFromParent();
1948       LeaMI->eraseFromParent();
1949       MI->eraseFromParent();
1950
1951       int delta = OrigSize - NewSize;
1952       BBInfo[MBB->getNumber()].Size -= delta;
1953       adjustBBOffsetsAfter(MBB);
1954
1955       ++NumTBs;
1956       MadeChange = true;
1957     }
1958   }
1959
1960   return MadeChange;
1961 }
1962
1963 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
1964 /// jump tables always branch forwards, since that's what tbb and tbh need.
1965 bool ARMConstantIslands::reorderThumb2JumpTables() {
1966   bool MadeChange = false;
1967
1968   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1969   if (MJTI == 0) return false;
1970
1971   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1972   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1973     MachineInstr *MI = T2JumpTables[i];
1974     const MCInstrDesc &MCID = MI->getDesc();
1975     unsigned NumOps = MCID.getNumOperands();
1976     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1977     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1978     unsigned JTI = JTOP.getIndex();
1979     assert(JTI < JT.size());
1980
1981     // We prefer if target blocks for the jump table come after the jump
1982     // instruction so we can use TB[BH]. Loop through the target blocks
1983     // and try to adjust them such that that's true.
1984     int JTNumber = MI->getParent()->getNumber();
1985     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1986     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1987       MachineBasicBlock *MBB = JTBBs[j];
1988       int DTNumber = MBB->getNumber();
1989
1990       if (DTNumber < JTNumber) {
1991         // The destination precedes the switch. Try to move the block forward
1992         // so we have a positive offset.
1993         MachineBasicBlock *NewBB =
1994           adjustJTTargetBlockForward(MBB, MI->getParent());
1995         if (NewBB)
1996           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1997         MadeChange = true;
1998       }
1999     }
2000   }
2001
2002   return MadeChange;
2003 }
2004
2005 MachineBasicBlock *ARMConstantIslands::
2006 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2007   // If the destination block is terminated by an unconditional branch,
2008   // try to move it; otherwise, create a new block following the jump
2009   // table that branches back to the actual target. This is a very simple
2010   // heuristic. FIXME: We can definitely improve it.
2011   MachineBasicBlock *TBB = 0, *FBB = 0;
2012   SmallVector<MachineOperand, 4> Cond;
2013   SmallVector<MachineOperand, 4> CondPrior;
2014   MachineFunction::iterator BBi = BB;
2015   MachineFunction::iterator OldPrior = prior(BBi);
2016
2017   // If the block terminator isn't analyzable, don't try to move the block
2018   bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
2019
2020   // If the block ends in an unconditional branch, move it. The prior block
2021   // has to have an analyzable terminator for us to move this one. Be paranoid
2022   // and make sure we're not trying to move the entry block of the function.
2023   if (!B && Cond.empty() && BB != MF->begin() &&
2024       !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2025     BB->moveAfter(JTBB);
2026     OldPrior->updateTerminator();
2027     BB->updateTerminator();
2028     // Update numbering to account for the block being moved.
2029     MF->RenumberBlocks();
2030     ++NumJTMoved;
2031     return NULL;
2032   }
2033
2034   // Create a new MBB for the code after the jump BB.
2035   MachineBasicBlock *NewBB =
2036     MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2037   MachineFunction::iterator MBBI = JTBB; ++MBBI;
2038   MF->insert(MBBI, NewBB);
2039
2040   // Add an unconditional branch from NewBB to BB.
2041   // There doesn't seem to be meaningful DebugInfo available; this doesn't
2042   // correspond directly to anything in the source.
2043   assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
2044   BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2045           .addImm(ARMCC::AL).addReg(0);
2046
2047   // Update internal data structures to account for the newly inserted MBB.
2048   MF->RenumberBlocks(NewBB);
2049
2050   // Update the CFG.
2051   NewBB->addSuccessor(BB);
2052   JTBB->removeSuccessor(BB);
2053   JTBB->addSuccessor(NewBB);
2054
2055   ++NumJTInserted;
2056   return NewBB;
2057 }