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