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