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