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