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