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)
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 0;
630   case ARM::JUMPTABLE_TBH:
631   case ARM::JUMPTABLE_INSTS:
632     return 1;
633   case ARM::JUMPTABLE_ADDRS:
634     return 2;
635   default:
636     llvm_unreachable("unknown constpool entry kind");
637   }
638 
639   unsigned CPI = getCombinedIndex(CPEMI);
640   assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
641   unsigned Align = MCP->getConstants()[CPI].getAlignment();
642   assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
643   return Log2_32(Align);
644 }
645 
646 /// scanFunctionJumpTables - Do a scan of the function, building up
647 /// information about the sizes of each block and the locations of all
648 /// the jump tables.
649 void ARMConstantIslands::scanFunctionJumpTables() {
650   for (MachineBasicBlock &MBB : *MF) {
651     for (MachineInstr &I : MBB)
652       if (I.isBranch() &&
653           (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
654         T2JumpTables.push_back(&I);
655   }
656 }
657 
658 /// initializeFunctionInfo - Do the initial scan of the function, building up
659 /// information about the sizes of each block, the location of all the water,
660 /// and finding all of the constant pool users.
661 void ARMConstantIslands::
662 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
663 
664   BBInfo = computeAllBlockSizes(MF);
665 
666   // The known bits of the entry block offset are determined by the function
667   // alignment.
668   BBInfo.front().KnownBits = MF->getAlignment();
669 
670   // Compute block offsets and known bits.
671   adjustBBOffsetsAfter(&MF->front());
672 
673   // Now go back through the instructions and build up our data structures.
674   for (MachineBasicBlock &MBB : *MF) {
675     // If this block doesn't fall through into the next MBB, then this is
676     // 'water' that a constant pool island could be placed.
677     if (!BBHasFallthrough(&MBB))
678       WaterList.push_back(&MBB);
679 
680     for (MachineInstr &I : MBB) {
681       if (I.isDebugValue())
682         continue;
683 
684       unsigned Opc = I.getOpcode();
685       if (I.isBranch()) {
686         bool isCond = false;
687         unsigned Bits = 0;
688         unsigned Scale = 1;
689         int UOpc = Opc;
690         switch (Opc) {
691         default:
692           continue;  // Ignore other JT branches
693         case ARM::t2BR_JT:
694         case ARM::tBR_JTr:
695           T2JumpTables.push_back(&I);
696           continue;   // Does not get an entry in ImmBranches
697         case ARM::Bcc:
698           isCond = true;
699           UOpc = ARM::B;
700           LLVM_FALLTHROUGH;
701         case ARM::B:
702           Bits = 24;
703           Scale = 4;
704           break;
705         case ARM::tBcc:
706           isCond = true;
707           UOpc = ARM::tB;
708           Bits = 8;
709           Scale = 2;
710           break;
711         case ARM::tB:
712           Bits = 11;
713           Scale = 2;
714           break;
715         case ARM::t2Bcc:
716           isCond = true;
717           UOpc = ARM::t2B;
718           Bits = 20;
719           Scale = 2;
720           break;
721         case ARM::t2B:
722           Bits = 24;
723           Scale = 2;
724           break;
725         }
726 
727         // Record this immediate branch.
728         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
729         ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
730       }
731 
732       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
733         PushPopMIs.push_back(&I);
734 
735       if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
736           Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
737           Opc == ARM::JUMPTABLE_TBH)
738         continue;
739 
740       // Scan the instructions for constant pool operands.
741       for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)
742         if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) {
743           // We found one.  The addressing mode tells us the max displacement
744           // from the PC that this instruction permits.
745 
746           // Basic size info comes from the TSFlags field.
747           unsigned Bits = 0;
748           unsigned Scale = 1;
749           bool NegOk = false;
750           bool IsSoImm = false;
751 
752           switch (Opc) {
753           default:
754             llvm_unreachable("Unknown addressing mode for CP reference!");
755 
756           // Taking the address of a CP entry.
757           case ARM::LEApcrel:
758           case ARM::LEApcrelJT:
759             // This takes a SoImm, which is 8 bit immediate rotated. We'll
760             // pretend the maximum offset is 255 * 4. Since each instruction
761             // 4 byte wide, this is always correct. We'll check for other
762             // displacements that fits in a SoImm as well.
763             Bits = 8;
764             Scale = 4;
765             NegOk = true;
766             IsSoImm = true;
767             break;
768           case ARM::t2LEApcrel:
769           case ARM::t2LEApcrelJT:
770             Bits = 12;
771             NegOk = true;
772             break;
773           case ARM::tLEApcrel:
774           case ARM::tLEApcrelJT:
775             Bits = 8;
776             Scale = 4;
777             break;
778 
779           case ARM::LDRBi12:
780           case ARM::LDRi12:
781           case ARM::LDRcp:
782           case ARM::t2LDRpci:
783           case ARM::t2LDRHpci:
784             Bits = 12;  // +-offset_12
785             NegOk = true;
786             break;
787 
788           case ARM::tLDRpci:
789             Bits = 8;
790             Scale = 4;  // +(offset_8*4)
791             break;
792 
793           case ARM::VLDRD:
794           case ARM::VLDRS:
795             Bits = 8;
796             Scale = 4;  // +-(offset_8*4)
797             NegOk = true;
798             break;
799 
800           case ARM::tLDRHi:
801             Bits = 5;
802             Scale = 2; // +(offset_5*2)
803             break;
804           }
805 
806           // Remember that this is a user of a CP entry.
807           unsigned CPI = I.getOperand(op).getIndex();
808           if (I.getOperand(op).isJTI()) {
809             JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));
810             CPI = JumpTableEntryIndices[CPI];
811           }
812 
813           MachineInstr *CPEMI = CPEMIs[CPI];
814           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
815           CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
816 
817           // Increment corresponding CPEntry reference count.
818           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
819           assert(CPE && "Cannot find a corresponding CPEntry!");
820           CPE->RefCount++;
821 
822           // Instructions can only use one CP entry, don't bother scanning the
823           // rest of the operands.
824           break;
825         }
826     }
827   }
828 }
829 
830 /// getOffsetOf - Return the current offset of the specified machine instruction
831 /// from the start of the function.  This offset changes as stuff is moved
832 /// around inside the function.
833 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
834   MachineBasicBlock *MBB = MI->getParent();
835 
836   // The offset is composed of two things: the sum of the sizes of all MBB's
837   // before this instruction's block, and the offset from the start of the block
838   // it is in.
839   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
840 
841   // Sum instructions before MI in MBB.
842   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
843     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
844     Offset += TII->getInstSizeInBytes(*I);
845   }
846   return Offset;
847 }
848 
849 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
850 /// ID.
851 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
852                               const MachineBasicBlock *RHS) {
853   return LHS->getNumber() < RHS->getNumber();
854 }
855 
856 /// updateForInsertedWaterBlock - When a block is newly inserted into the
857 /// machine function, it upsets all of the block numbers.  Renumber the blocks
858 /// and update the arrays that parallel this numbering.
859 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
860   // Renumber the MBB's to keep them consecutive.
861   NewBB->getParent()->RenumberBlocks(NewBB);
862 
863   // Insert an entry into BBInfo to align it properly with the (newly
864   // renumbered) block numbers.
865   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
866 
867   // Next, update WaterList.  Specifically, we need to add NewMBB as having
868   // available water after it.
869   water_iterator IP =
870     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
871                      CompareMBBNumbers);
872   WaterList.insert(IP, NewBB);
873 }
874 
875 
876 /// Split the basic block containing MI into two blocks, which are joined by
877 /// an unconditional branch.  Update data structures and renumber blocks to
878 /// account for this change and returns the newly created block.
879 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
880   MachineBasicBlock *OrigBB = MI->getParent();
881 
882   // Create a new MBB for the code after the OrigBB.
883   MachineBasicBlock *NewBB =
884     MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
885   MachineFunction::iterator MBBI = ++OrigBB->getIterator();
886   MF->insert(MBBI, NewBB);
887 
888   // Splice the instructions starting with MI over to NewBB.
889   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
890 
891   // Add an unconditional branch from OrigBB to NewBB.
892   // Note the new unconditional branch is not being recorded.
893   // There doesn't seem to be meaningful DebugInfo available; this doesn't
894   // correspond to anything in the source.
895   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
896   if (!isThumb)
897     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
898   else
899     BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
900             .addImm(ARMCC::AL).addReg(0);
901   ++NumSplit;
902 
903   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
904   NewBB->transferSuccessors(OrigBB);
905 
906   // OrigBB branches to NewBB.
907   OrigBB->addSuccessor(NewBB);
908 
909   // Update internal data structures to account for the newly inserted MBB.
910   // This is almost the same as updateForInsertedWaterBlock, except that
911   // the Water goes after OrigBB, not NewBB.
912   MF->RenumberBlocks(NewBB);
913 
914   // Insert an entry into BBInfo to align it properly with the (newly
915   // renumbered) block numbers.
916   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
917 
918   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
919   // available water after it (but not if it's already there, which happens
920   // when splitting before a conditional branch that is followed by an
921   // unconditional branch - in that case we want to insert NewBB).
922   water_iterator IP =
923     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
924                      CompareMBBNumbers);
925   MachineBasicBlock* WaterBB = *IP;
926   if (WaterBB == OrigBB)
927     WaterList.insert(std::next(IP), NewBB);
928   else
929     WaterList.insert(IP, OrigBB);
930   NewWaterList.insert(OrigBB);
931 
932   // Figure out how large the OrigBB is.  As the first half of the original
933   // block, it cannot contain a tablejump.  The size includes
934   // the new jump we added.  (It should be possible to do this without
935   // recounting everything, but it's very confusing, and this is rarely
936   // executed.)
937   computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
938 
939   // Figure out how large the NewMBB is.  As the second half of the original
940   // block, it may contain a tablejump.
941   computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
942 
943   // All BBOffsets following these blocks must be modified.
944   adjustBBOffsetsAfter(OrigBB);
945 
946   return NewBB;
947 }
948 
949 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
950 /// displacement computation.  Update U.KnownAlignment to match its current
951 /// basic block location.
952 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
953   unsigned UserOffset = getOffsetOf(U.MI);
954   const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
955   unsigned KnownBits = BBI.internalKnownBits();
956 
957   // The value read from PC is offset from the actual instruction address.
958   UserOffset += (isThumb ? 4 : 8);
959 
960   // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
961   // Make sure U.getMaxDisp() returns a constrained range.
962   U.KnownAlignment = (KnownBits >= 2);
963 
964   // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
965   // purposes of the displacement computation; compensate for that here.
966   // For unknown alignments, getMaxDisp() constrains the range instead.
967   if (isThumb && U.KnownAlignment)
968     UserOffset &= ~3u;
969 
970   return UserOffset;
971 }
972 
973 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
974 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
975 /// constant pool entry).
976 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
977 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
978 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
979 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
980                                          unsigned TrialOffset, unsigned MaxDisp,
981                                          bool NegativeOK, bool IsSoImm) {
982   if (UserOffset <= TrialOffset) {
983     // User before the Trial.
984     if (TrialOffset - UserOffset <= MaxDisp)
985       return true;
986     // FIXME: Make use full range of soimm values.
987   } else if (NegativeOK) {
988     if (UserOffset - TrialOffset <= MaxDisp)
989       return true;
990     // FIXME: Make use full range of soimm values.
991   }
992   return false;
993 }
994 
995 /// isWaterInRange - Returns true if a CPE placed after the specified
996 /// Water (a basic block) will be in range for the specific MI.
997 ///
998 /// Compute how much the function will grow by inserting a CPE after Water.
999 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
1000                                         MachineBasicBlock* Water, CPUser &U,
1001                                         unsigned &Growth) {
1002   unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1003   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1004   unsigned NextBlockOffset, NextBlockAlignment;
1005   MachineFunction::const_iterator NextBlock = Water->getIterator();
1006   if (++NextBlock == MF->end()) {
1007     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1008     NextBlockAlignment = 0;
1009   } else {
1010     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1011     NextBlockAlignment = NextBlock->getAlignment();
1012   }
1013   unsigned Size = U.CPEMI->getOperand(2).getImm();
1014   unsigned CPEEnd = CPEOffset + Size;
1015 
1016   // The CPE may be able to hide in the alignment padding before the next
1017   // block. It may also cause more padding to be required if it is more aligned
1018   // that the next block.
1019   if (CPEEnd > NextBlockOffset) {
1020     Growth = CPEEnd - NextBlockOffset;
1021     // Compute the padding that would go at the end of the CPE to align the next
1022     // block.
1023     Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
1024 
1025     // If the CPE is to be inserted before the instruction, that will raise
1026     // the offset of the instruction. Also account for unknown alignment padding
1027     // in blocks between CPE and the user.
1028     if (CPEOffset < UserOffset)
1029       UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1030   } else
1031     // CPE fits in existing padding.
1032     Growth = 0;
1033 
1034   return isOffsetInRange(UserOffset, CPEOffset, U);
1035 }
1036 
1037 /// isCPEntryInRange - Returns true if the distance between specific MI and
1038 /// specific ConstPool entry instruction can fit in MI's displacement field.
1039 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1040                                       MachineInstr *CPEMI, unsigned MaxDisp,
1041                                       bool NegOk, bool DoDump) {
1042   unsigned CPEOffset  = getOffsetOf(CPEMI);
1043 
1044   if (DoDump) {
1045     DEBUG({
1046       unsigned Block = MI->getParent()->getNumber();
1047       const BasicBlockInfo &BBI = BBInfo[Block];
1048       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1049              << " max delta=" << MaxDisp
1050              << format(" insn address=%#x", UserOffset)
1051              << " in BB#" << Block << ": "
1052              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1053              << format("CPE address=%#x offset=%+d: ", CPEOffset,
1054                        int(CPEOffset-UserOffset));
1055     });
1056   }
1057 
1058   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1059 }
1060 
1061 #ifndef NDEBUG
1062 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1063 /// unconditionally branches to its only successor.
1064 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1065   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1066     return false;
1067 
1068   MachineBasicBlock *Succ = *MBB->succ_begin();
1069   MachineBasicBlock *Pred = *MBB->pred_begin();
1070   MachineInstr *PredMI = &Pred->back();
1071   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1072       || PredMI->getOpcode() == ARM::t2B)
1073     return PredMI->getOperand(0).getMBB() == Succ;
1074   return false;
1075 }
1076 #endif // NDEBUG
1077 
1078 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1079   unsigned BBNum = BB->getNumber();
1080   for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1081     // Get the offset and known bits at the end of the layout predecessor.
1082     // Include the alignment of the current block.
1083     unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1084     unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1085     unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1086 
1087     // This is where block i begins.  Stop if the offset is already correct,
1088     // and we have updated 2 blocks.  This is the maximum number of blocks
1089     // changed before calling this function.
1090     if (i > BBNum + 2 &&
1091         BBInfo[i].Offset == Offset &&
1092         BBInfo[i].KnownBits == KnownBits)
1093       break;
1094 
1095     BBInfo[i].Offset = Offset;
1096     BBInfo[i].KnownBits = KnownBits;
1097   }
1098 }
1099 
1100 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1101 /// and instruction CPEMI, and decrement its refcount.  If the refcount
1102 /// becomes 0 remove the entry and instruction.  Returns true if we removed
1103 /// the entry, false if we didn't.
1104 
1105 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1106                                                     MachineInstr *CPEMI) {
1107   // Find the old entry. Eliminate it if it is no longer used.
1108   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1109   assert(CPE && "Unexpected!");
1110   if (--CPE->RefCount == 0) {
1111     removeDeadCPEMI(CPEMI);
1112     CPE->CPEMI = nullptr;
1113     --NumCPEs;
1114     return true;
1115   }
1116   return false;
1117 }
1118 
1119 unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1120   if (CPEMI->getOperand(1).isCPI())
1121     return CPEMI->getOperand(1).getIndex();
1122 
1123   return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1124 }
1125 
1126 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1127 /// if not, see if an in-range clone of the CPE is in range, and if so,
1128 /// change the data structures so the user references the clone.  Returns:
1129 /// 0 = no existing entry found
1130 /// 1 = entry found, and there were no code insertions or deletions
1131 /// 2 = entry found, and there were code insertions or deletions
1132 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1133 {
1134   MachineInstr *UserMI = U.MI;
1135   MachineInstr *CPEMI  = U.CPEMI;
1136 
1137   // Check to see if the CPE is already in-range.
1138   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1139                        true)) {
1140     DEBUG(dbgs() << "In range\n");
1141     return 1;
1142   }
1143 
1144   // No.  Look for previously created clones of the CPE that are in range.
1145   unsigned CPI = getCombinedIndex(CPEMI);
1146   std::vector<CPEntry> &CPEs = CPEntries[CPI];
1147   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1148     // We already tried this one
1149     if (CPEs[i].CPEMI == CPEMI)
1150       continue;
1151     // Removing CPEs can leave empty entries, skip
1152     if (CPEs[i].CPEMI == nullptr)
1153       continue;
1154     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1155                      U.NegOk)) {
1156       DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1157                    << CPEs[i].CPI << "\n");
1158       // Point the CPUser node to the replacement
1159       U.CPEMI = CPEs[i].CPEMI;
1160       // Change the CPI in the instruction operand to refer to the clone.
1161       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1162         if (UserMI->getOperand(j).isCPI()) {
1163           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1164           break;
1165         }
1166       // Adjust the refcount of the clone...
1167       CPEs[i].RefCount++;
1168       // ...and the original.  If we didn't remove the old entry, none of the
1169       // addresses changed, so we don't need another pass.
1170       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1171     }
1172   }
1173   return 0;
1174 }
1175 
1176 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1177 /// the specific unconditional branch instruction.
1178 static inline unsigned getUnconditionalBrDisp(int Opc) {
1179   switch (Opc) {
1180   case ARM::tB:
1181     return ((1<<10)-1)*2;
1182   case ARM::t2B:
1183     return ((1<<23)-1)*2;
1184   default:
1185     break;
1186   }
1187 
1188   return ((1<<23)-1)*4;
1189 }
1190 
1191 /// findAvailableWater - Look for an existing entry in the WaterList in which
1192 /// we can place the CPE referenced from U so it's within range of U's MI.
1193 /// Returns true if found, false if not.  If it returns true, WaterIter
1194 /// is set to the WaterList entry.  For Thumb, prefer water that will not
1195 /// introduce padding to water that will.  To ensure that this pass
1196 /// terminates, the CPE location for a particular CPUser is only allowed to
1197 /// move to a lower address, so search backward from the end of the list and
1198 /// prefer the first water that is in range.
1199 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1200                                             water_iterator &WaterIter,
1201                                             bool CloserWater) {
1202   if (WaterList.empty())
1203     return false;
1204 
1205   unsigned BestGrowth = ~0u;
1206   // The nearest water without splitting the UserBB is right after it.
1207   // If the distance is still large (we have a big BB), then we need to split it
1208   // if we don't converge after certain iterations. This helps the following
1209   // situation to converge:
1210   //   BB0:
1211   //      Big BB
1212   //   BB1:
1213   //      Constant Pool
1214   // When a CP access is out of range, BB0 may be used as water. However,
1215   // inserting islands between BB0 and BB1 makes other accesses out of range.
1216   MachineBasicBlock *UserBB = U.MI->getParent();
1217   unsigned MinNoSplitDisp =
1218       BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1219   if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1220     return false;
1221   for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1222        --IP) {
1223     MachineBasicBlock* WaterBB = *IP;
1224     // Check if water is in range and is either at a lower address than the
1225     // current "high water mark" or a new water block that was created since
1226     // the previous iteration by inserting an unconditional branch.  In the
1227     // latter case, we want to allow resetting the high water mark back to
1228     // this new water since we haven't seen it before.  Inserting branches
1229     // should be relatively uncommon and when it does happen, we want to be
1230     // sure to take advantage of it for all the CPEs near that block, so that
1231     // we don't insert more branches than necessary.
1232     // When CloserWater is true, we try to find the lowest address after (or
1233     // equal to) user MI's BB no matter of padding growth.
1234     unsigned Growth;
1235     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1236         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1237          NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1238         Growth < BestGrowth) {
1239       // This is the least amount of required padding seen so far.
1240       BestGrowth = Growth;
1241       WaterIter = IP;
1242       DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1243                    << " Growth=" << Growth << '\n');
1244 
1245       if (CloserWater && WaterBB == U.MI->getParent())
1246         return true;
1247       // Keep looking unless it is perfect and we're not looking for the lowest
1248       // possible address.
1249       if (!CloserWater && BestGrowth == 0)
1250         return true;
1251     }
1252     if (IP == B)
1253       break;
1254   }
1255   return BestGrowth != ~0u;
1256 }
1257 
1258 /// createNewWater - No existing WaterList entry will work for
1259 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1260 /// block is used if in range, and the conditional branch munged so control
1261 /// flow is correct.  Otherwise the block is split to create a hole with an
1262 /// unconditional branch around it.  In either case NewMBB is set to a
1263 /// block following which the new island can be inserted (the WaterList
1264 /// is not adjusted).
1265 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1266                                         unsigned UserOffset,
1267                                         MachineBasicBlock *&NewMBB) {
1268   CPUser &U = CPUsers[CPUserIndex];
1269   MachineInstr *UserMI = U.MI;
1270   MachineInstr *CPEMI  = U.CPEMI;
1271   unsigned CPELogAlign = getCPELogAlign(CPEMI);
1272   MachineBasicBlock *UserMBB = UserMI->getParent();
1273   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1274 
1275   // If the block does not end in an unconditional branch already, and if the
1276   // end of the block is within range, make new water there.  (The addition
1277   // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1278   // Thumb2, 2 on Thumb1.
1279   if (BBHasFallthrough(UserMBB)) {
1280     // Size of branch to insert.
1281     unsigned Delta = isThumb1 ? 2 : 4;
1282     // Compute the offset where the CPE will begin.
1283     unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1284 
1285     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1286       DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1287             << format(", expected CPE offset %#x\n", CPEOffset));
1288       NewMBB = &*++UserMBB->getIterator();
1289       // Add an unconditional branch from UserMBB to fallthrough block.  Record
1290       // it for branch lengthening; this new branch will not get out of range,
1291       // but if the preceding conditional branch is out of range, the targets
1292       // will be exchanged, and the altered branch may be out of range, so the
1293       // machinery has to know about it.
1294       int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1295       if (!isThumb)
1296         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1297       else
1298         BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1299           .addImm(ARMCC::AL).addReg(0);
1300       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1301       ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1302                                       MaxDisp, false, UncondBr));
1303       computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
1304       adjustBBOffsetsAfter(UserMBB);
1305       return;
1306     }
1307   }
1308 
1309   // What a big block.  Find a place within the block to split it.  This is a
1310   // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1311   // entries are 4 bytes: if instruction I references island CPE, and
1312   // instruction I+1 references CPE', it will not work well to put CPE as far
1313   // forward as possible, since then CPE' cannot immediately follow it (that
1314   // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1315   // need to create a new island.  So, we make a first guess, then walk through
1316   // the instructions between the one currently being looked at and the
1317   // possible insertion point, and make sure any other instructions that
1318   // reference CPEs will be able to use the same island area; if not, we back
1319   // up the insertion point.
1320 
1321   // Try to split the block so it's fully aligned.  Compute the latest split
1322   // point where we can add a 4-byte branch instruction, and then align to
1323   // LogAlign which is the largest possible alignment in the function.
1324   unsigned LogAlign = MF->getAlignment();
1325   assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1326   unsigned KnownBits = UserBBI.internalKnownBits();
1327   unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1328   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1329   DEBUG(dbgs() << format("Split in middle of big block before %#x",
1330                          BaseInsertOffset));
1331 
1332   // The 4 in the following is for the unconditional branch we'll be inserting
1333   // (allows for long branch on Thumb1).  Alignment of the island is handled
1334   // inside isOffsetInRange.
1335   BaseInsertOffset -= 4;
1336 
1337   DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1338                << " la=" << LogAlign
1339                << " kb=" << KnownBits
1340                << " up=" << UPad << '\n');
1341 
1342   // This could point off the end of the block if we've already got constant
1343   // pool entries following this block; only the last one is in the water list.
1344   // Back past any possible branches (allow for a conditional and a maximally
1345   // long unconditional).
1346   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1347     // Ensure BaseInsertOffset is larger than the offset of the instruction
1348     // following UserMI so that the loop which searches for the split point
1349     // iterates at least once.
1350     BaseInsertOffset =
1351         std::max(UserBBI.postOffset() - UPad - 8,
1352                  UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
1353     DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1354   }
1355   unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1356     CPEMI->getOperand(2).getImm();
1357   MachineBasicBlock::iterator MI = UserMI;
1358   ++MI;
1359   unsigned CPUIndex = CPUserIndex+1;
1360   unsigned NumCPUsers = CPUsers.size();
1361   MachineInstr *LastIT = nullptr;
1362   for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1363        Offset < BaseInsertOffset;
1364        Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1365     assert(MI != UserMBB->end() && "Fell off end of block");
1366     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
1367       CPUser &U = CPUsers[CPUIndex];
1368       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1369         // Shift intertion point by one unit of alignment so it is within reach.
1370         BaseInsertOffset -= 1u << LogAlign;
1371         EndInsertOffset  -= 1u << LogAlign;
1372       }
1373       // This is overly conservative, as we don't account for CPEMIs being
1374       // reused within the block, but it doesn't matter much.  Also assume CPEs
1375       // are added in order with alignment padding.  We may eventually be able
1376       // to pack the aligned CPEs better.
1377       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1378       CPUIndex++;
1379     }
1380 
1381     // Remember the last IT instruction.
1382     if (MI->getOpcode() == ARM::t2IT)
1383       LastIT = &*MI;
1384   }
1385 
1386   --MI;
1387 
1388   // Avoid splitting an IT block.
1389   if (LastIT) {
1390     unsigned PredReg = 0;
1391     ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
1392     if (CC != ARMCC::AL)
1393       MI = LastIT;
1394   }
1395 
1396   // We really must not split an IT block.
1397   DEBUG(unsigned PredReg;
1398         assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
1399 
1400   NewMBB = splitBlockBeforeInstr(&*MI);
1401 }
1402 
1403 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1404 /// is out-of-range.  If so, pick up the constant pool value and move it some
1405 /// place in-range.  Return true if we changed any addresses (thus must run
1406 /// another pass of branch lengthening), false otherwise.
1407 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1408                                                 bool CloserWater) {
1409   CPUser &U = CPUsers[CPUserIndex];
1410   MachineInstr *UserMI = U.MI;
1411   MachineInstr *CPEMI  = U.CPEMI;
1412   unsigned CPI = getCombinedIndex(CPEMI);
1413   unsigned Size = CPEMI->getOperand(2).getImm();
1414   // Compute this only once, it's expensive.
1415   unsigned UserOffset = getUserOffset(U);
1416 
1417   // See if the current entry is within range, or there is a clone of it
1418   // in range.
1419   int result = findInRangeCPEntry(U, UserOffset);
1420   if (result==1) return false;
1421   else if (result==2) return true;
1422 
1423   // No existing clone of this CPE is within range.
1424   // We will be generating a new clone.  Get a UID for it.
1425   unsigned ID = AFI->createPICLabelUId();
1426 
1427   // Look for water where we can place this CPE.
1428   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1429   MachineBasicBlock *NewMBB;
1430   water_iterator IP;
1431   if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
1432     DEBUG(dbgs() << "Found water in range\n");
1433     MachineBasicBlock *WaterBB = *IP;
1434 
1435     // If the original WaterList entry was "new water" on this iteration,
1436     // propagate that to the new island.  This is just keeping NewWaterList
1437     // updated to match the WaterList, which will be updated below.
1438     if (NewWaterList.erase(WaterBB))
1439       NewWaterList.insert(NewIsland);
1440 
1441     // The new CPE goes before the following block (NewMBB).
1442     NewMBB = &*++WaterBB->getIterator();
1443   } else {
1444     // No water found.
1445     DEBUG(dbgs() << "No water found\n");
1446     createNewWater(CPUserIndex, UserOffset, NewMBB);
1447 
1448     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1449     // called while handling branches so that the water will be seen on the
1450     // next iteration for constant pools, but in this context, we don't want
1451     // it.  Check for this so it will be removed from the WaterList.
1452     // Also remove any entry from NewWaterList.
1453     MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1454     IP = find(WaterList, WaterBB);
1455     if (IP != WaterList.end())
1456       NewWaterList.erase(WaterBB);
1457 
1458     // We are adding new water.  Update NewWaterList.
1459     NewWaterList.insert(NewIsland);
1460   }
1461 
1462   // Remove the original WaterList entry; we want subsequent insertions in
1463   // this vicinity to go after the one we're about to insert.  This
1464   // considerably reduces the number of times we have to move the same CPE
1465   // more than once and is also important to ensure the algorithm terminates.
1466   if (IP != WaterList.end())
1467     WaterList.erase(IP);
1468 
1469   // Okay, we know we can put an island before NewMBB now, do it!
1470   MF->insert(NewMBB->getIterator(), NewIsland);
1471 
1472   // Update internal data structures to account for the newly inserted MBB.
1473   updateForInsertedWaterBlock(NewIsland);
1474 
1475   // Now that we have an island to add the CPE to, clone the original CPE and
1476   // add it to the island.
1477   U.HighWaterMark = NewIsland;
1478   U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1479                 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size);
1480   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1481   ++NumCPEs;
1482 
1483   // Decrement the old entry, and remove it if refcount becomes 0.
1484   decrementCPEReferenceCount(CPI, CPEMI);
1485 
1486   // Mark the basic block as aligned as required by the const-pool entry.
1487   NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1488 
1489   // Increase the size of the island block to account for the new entry.
1490   BBInfo[NewIsland->getNumber()].Size += Size;
1491   adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1492 
1493   // Finally, change the CPI in the instruction operand to be ID.
1494   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1495     if (UserMI->getOperand(i).isCPI()) {
1496       UserMI->getOperand(i).setIndex(ID);
1497       break;
1498     }
1499 
1500   DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1501         << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1502 
1503   return true;
1504 }
1505 
1506 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1507 /// sizes and offsets of impacted basic blocks.
1508 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1509   MachineBasicBlock *CPEBB = CPEMI->getParent();
1510   unsigned Size = CPEMI->getOperand(2).getImm();
1511   CPEMI->eraseFromParent();
1512   BBInfo[CPEBB->getNumber()].Size -= Size;
1513   // All succeeding offsets have the current size value added in, fix this.
1514   if (CPEBB->empty()) {
1515     BBInfo[CPEBB->getNumber()].Size = 0;
1516 
1517     // This block no longer needs to be aligned.
1518     CPEBB->setAlignment(0);
1519   } else
1520     // Entries are sorted by descending alignment, so realign from the front.
1521     CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
1522 
1523   adjustBBOffsetsAfter(CPEBB);
1524   // An island has only one predecessor BB and one successor BB. Check if
1525   // this BB's predecessor jumps directly to this BB's successor. This
1526   // shouldn't happen currently.
1527   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1528   // FIXME: remove the empty blocks after all the work is done?
1529 }
1530 
1531 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1532 /// are zero.
1533 bool ARMConstantIslands::removeUnusedCPEntries() {
1534   unsigned MadeChange = false;
1535   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1536       std::vector<CPEntry> &CPEs = CPEntries[i];
1537       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1538         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1539           removeDeadCPEMI(CPEs[j].CPEMI);
1540           CPEs[j].CPEMI = nullptr;
1541           MadeChange = true;
1542         }
1543       }
1544   }
1545   return MadeChange;
1546 }
1547 
1548 /// isBBInRange - Returns true if the distance between specific MI and
1549 /// specific BB can fit in MI's displacement field.
1550 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1551                                      unsigned MaxDisp) {
1552   unsigned PCAdj      = isThumb ? 4 : 8;
1553   unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
1554   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1555 
1556   DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1557                << " from BB#" << MI->getParent()->getNumber()
1558                << " max delta=" << MaxDisp
1559                << " from " << getOffsetOf(MI) << " to " << DestOffset
1560                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1561 
1562   if (BrOffset <= DestOffset) {
1563     // Branch before the Dest.
1564     if (DestOffset-BrOffset <= MaxDisp)
1565       return true;
1566   } else {
1567     if (BrOffset-DestOffset <= MaxDisp)
1568       return true;
1569   }
1570   return false;
1571 }
1572 
1573 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1574 /// away to fit in its displacement field.
1575 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1576   MachineInstr *MI = Br.MI;
1577   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1578 
1579   // Check to see if the DestBB is already in-range.
1580   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1581     return false;
1582 
1583   if (!Br.isCond)
1584     return fixupUnconditionalBr(Br);
1585   return fixupConditionalBr(Br);
1586 }
1587 
1588 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1589 /// too far away to fit in its displacement field. If the LR register has been
1590 /// spilled in the epilogue, then we can use BL to implement a far jump.
1591 /// Otherwise, add an intermediate branch instruction to a branch.
1592 bool
1593 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1594   MachineInstr *MI = Br.MI;
1595   MachineBasicBlock *MBB = MI->getParent();
1596   if (!isThumb1)
1597     llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1598 
1599   // Use BL to implement far jump.
1600   Br.MaxDisp = (1 << 21) * 2;
1601   MI->setDesc(TII->get(ARM::tBfar));
1602   BBInfo[MBB->getNumber()].Size += 2;
1603   adjustBBOffsetsAfter(MBB);
1604   HasFarJump = true;
1605   ++NumUBrFixed;
1606 
1607   DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1608 
1609   return true;
1610 }
1611 
1612 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1613 /// far away to fit in its displacement field. It is converted to an inverse
1614 /// conditional branch + an unconditional branch to the destination.
1615 bool
1616 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1617   MachineInstr *MI = Br.MI;
1618   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1619 
1620   // Add an unconditional branch to the destination and invert the branch
1621   // condition to jump over it:
1622   // blt L1
1623   // =>
1624   // bge L2
1625   // b   L1
1626   // L2:
1627   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1628   CC = ARMCC::getOppositeCondition(CC);
1629   unsigned CCReg = MI->getOperand(2).getReg();
1630 
1631   // If the branch is at the end of its MBB and that has a fall-through block,
1632   // direct the updated conditional branch to the fall-through block. Otherwise,
1633   // split the MBB before the next instruction.
1634   MachineBasicBlock *MBB = MI->getParent();
1635   MachineInstr *BMI = &MBB->back();
1636   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1637 
1638   ++NumCBrFixed;
1639   if (BMI != MI) {
1640     if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1641         BMI->getOpcode() == Br.UncondBr) {
1642       // Last MI in the BB is an unconditional branch. Can we simply invert the
1643       // condition and swap destinations:
1644       // beq L1
1645       // b   L2
1646       // =>
1647       // bne L2
1648       // b   L1
1649       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1650       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1651         DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
1652                      << *BMI);
1653         BMI->getOperand(0).setMBB(DestBB);
1654         MI->getOperand(0).setMBB(NewDest);
1655         MI->getOperand(1).setImm(CC);
1656         return true;
1657       }
1658     }
1659   }
1660 
1661   if (NeedSplit) {
1662     splitBlockBeforeInstr(MI);
1663     // No need for the branch to the next block. We're adding an unconditional
1664     // branch to the destination.
1665     int delta = TII->getInstSizeInBytes(MBB->back());
1666     BBInfo[MBB->getNumber()].Size -= delta;
1667     MBB->back().eraseFromParent();
1668     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1669   }
1670   MachineBasicBlock *NextBB = &*++MBB->getIterator();
1671 
1672   DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
1673                << " also invert condition and change dest. to BB#"
1674                << NextBB->getNumber() << "\n");
1675 
1676   // Insert a new conditional branch and a new unconditional branch.
1677   // Also update the ImmBranch as well as adding a new entry for the new branch.
1678   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1679     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1680   Br.MI = &MBB->back();
1681   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1682   if (isThumb)
1683     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1684             .addImm(ARMCC::AL).addReg(0);
1685   else
1686     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1687   BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1688   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1689   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1690 
1691   // Remove the old conditional branch.  It may or may not still be in MBB.
1692   BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1693   MI->eraseFromParent();
1694   adjustBBOffsetsAfter(MBB);
1695   return true;
1696 }
1697 
1698 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1699 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1700 /// to do this if tBfar is not used.
1701 bool ARMConstantIslands::undoLRSpillRestore() {
1702   bool MadeChange = false;
1703   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1704     MachineInstr *MI = PushPopMIs[i];
1705     // First two operands are predicates.
1706     if (MI->getOpcode() == ARM::tPOP_RET &&
1707         MI->getOperand(2).getReg() == ARM::PC &&
1708         MI->getNumExplicitOperands() == 3) {
1709       // Create the new insn and copy the predicate from the old.
1710       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1711         .addOperand(MI->getOperand(0))
1712         .addOperand(MI->getOperand(1));
1713       MI->eraseFromParent();
1714       MadeChange = true;
1715     }
1716   }
1717   return MadeChange;
1718 }
1719 
1720 bool ARMConstantIslands::optimizeThumb2Instructions() {
1721   bool MadeChange = false;
1722 
1723   // Shrink ADR and LDR from constantpool.
1724   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1725     CPUser &U = CPUsers[i];
1726     unsigned Opcode = U.MI->getOpcode();
1727     unsigned NewOpc = 0;
1728     unsigned Scale = 1;
1729     unsigned Bits = 0;
1730     switch (Opcode) {
1731     default: break;
1732     case ARM::t2LEApcrel:
1733       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1734         NewOpc = ARM::tLEApcrel;
1735         Bits = 8;
1736         Scale = 4;
1737       }
1738       break;
1739     case ARM::t2LDRpci:
1740       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1741         NewOpc = ARM::tLDRpci;
1742         Bits = 8;
1743         Scale = 4;
1744       }
1745       break;
1746     }
1747 
1748     if (!NewOpc)
1749       continue;
1750 
1751     unsigned UserOffset = getUserOffset(U);
1752     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1753 
1754     // Be conservative with inline asm.
1755     if (!U.KnownAlignment)
1756       MaxOffs -= 2;
1757 
1758     // FIXME: Check if offset is multiple of scale if scale is not 4.
1759     if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1760       DEBUG(dbgs() << "Shrink: " << *U.MI);
1761       U.MI->setDesc(TII->get(NewOpc));
1762       MachineBasicBlock *MBB = U.MI->getParent();
1763       BBInfo[MBB->getNumber()].Size -= 2;
1764       adjustBBOffsetsAfter(MBB);
1765       ++NumT2CPShrunk;
1766       MadeChange = true;
1767     }
1768   }
1769 
1770   return MadeChange;
1771 }
1772 
1773 bool ARMConstantIslands::optimizeThumb2Branches() {
1774   bool MadeChange = false;
1775 
1776   // The order in which branches appear in ImmBranches is approximately their
1777   // order within the function body. By visiting later branches first, we reduce
1778   // the distance between earlier forward branches and their targets, making it
1779   // more likely that the cbn?z optimization, which can only apply to forward
1780   // branches, will succeed.
1781   for (unsigned i = ImmBranches.size(); i != 0; --i) {
1782     ImmBranch &Br = ImmBranches[i-1];
1783     unsigned Opcode = Br.MI->getOpcode();
1784     unsigned NewOpc = 0;
1785     unsigned Scale = 1;
1786     unsigned Bits = 0;
1787     switch (Opcode) {
1788     default: break;
1789     case ARM::t2B:
1790       NewOpc = ARM::tB;
1791       Bits = 11;
1792       Scale = 2;
1793       break;
1794     case ARM::t2Bcc: {
1795       NewOpc = ARM::tBcc;
1796       Bits = 8;
1797       Scale = 2;
1798       break;
1799     }
1800     }
1801     if (NewOpc) {
1802       unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1803       MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1804       if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1805         DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1806         Br.MI->setDesc(TII->get(NewOpc));
1807         MachineBasicBlock *MBB = Br.MI->getParent();
1808         BBInfo[MBB->getNumber()].Size -= 2;
1809         adjustBBOffsetsAfter(MBB);
1810         ++NumT2BrShrunk;
1811         MadeChange = true;
1812       }
1813     }
1814 
1815     Opcode = Br.MI->getOpcode();
1816     if (Opcode != ARM::tBcc)
1817       continue;
1818 
1819     // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1820     // so this transformation is not safe.
1821     if (!Br.MI->killsRegister(ARM::CPSR))
1822       continue;
1823 
1824     NewOpc = 0;
1825     unsigned PredReg = 0;
1826     ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
1827     if (Pred == ARMCC::EQ)
1828       NewOpc = ARM::tCBZ;
1829     else if (Pred == ARMCC::NE)
1830       NewOpc = ARM::tCBNZ;
1831     if (!NewOpc)
1832       continue;
1833     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1834     // Check if the distance is within 126. Subtract starting offset by 2
1835     // because the cmp will be eliminated.
1836     unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1837     unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1838     if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1839       MachineBasicBlock::iterator CmpMI = Br.MI;
1840       if (CmpMI != Br.MI->getParent()->begin()) {
1841         --CmpMI;
1842         if (CmpMI->getOpcode() == ARM::tCMPi8) {
1843           unsigned Reg = CmpMI->getOperand(0).getReg();
1844           Pred = getInstrPredicate(*CmpMI, PredReg);
1845           if (Pred == ARMCC::AL &&
1846               CmpMI->getOperand(1).getImm() == 0 &&
1847               isARMLowRegister(Reg)) {
1848             MachineBasicBlock *MBB = Br.MI->getParent();
1849             DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1850             MachineInstr *NewBR =
1851               BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1852               .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1853             CmpMI->eraseFromParent();
1854             Br.MI->eraseFromParent();
1855             Br.MI = NewBR;
1856             BBInfo[MBB->getNumber()].Size -= 2;
1857             adjustBBOffsetsAfter(MBB);
1858             ++NumCBZ;
1859             MadeChange = true;
1860           }
1861         }
1862       }
1863     }
1864   }
1865 
1866   return MadeChange;
1867 }
1868 
1869 static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1870                               unsigned BaseReg) {
1871   if (I.getOpcode() != ARM::t2ADDrs)
1872     return false;
1873 
1874   if (I.getOperand(0).getReg() != EntryReg)
1875     return false;
1876 
1877   if (I.getOperand(1).getReg() != BaseReg)
1878     return false;
1879 
1880   // FIXME: what about CC and IdxReg?
1881   return true;
1882 }
1883 
1884 /// \brief While trying to form a TBB/TBH instruction, we may (if the table
1885 /// doesn't immediately follow the BR_JT) need access to the start of the
1886 /// jump-table. We know one instruction that produces such a register; this
1887 /// function works out whether that definition can be preserved to the BR_JT,
1888 /// possibly by removing an intervening addition (which is usually needed to
1889 /// calculate the actual entry to jump to).
1890 bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1891                                               MachineInstr *LEAMI,
1892                                               unsigned &DeadSize,
1893                                               bool &CanDeleteLEA,
1894                                               bool &BaseRegKill) {
1895   if (JumpMI->getParent() != LEAMI->getParent())
1896     return false;
1897 
1898   // Now we hope that we have at least these instructions in the basic block:
1899   //     BaseReg = t2LEA ...
1900   //     [...]
1901   //     EntryReg = t2ADDrs BaseReg, ...
1902   //     [...]
1903   //     t2BR_JT EntryReg
1904   //
1905   // We have to be very conservative about what we recognise here though. The
1906   // main perturbing factors to watch out for are:
1907   //    + Spills at any point in the chain: not direct problems but we would
1908   //      expect a blocking Def of the spilled register so in practice what we
1909   //      can do is limited.
1910   //    + EntryReg == BaseReg: this is the one situation we should allow a Def
1911   //      of BaseReg, but only if the t2ADDrs can be removed.
1912   //    + Some instruction other than t2ADDrs computing the entry. Not seen in
1913   //      the wild, but we should be careful.
1914   unsigned EntryReg = JumpMI->getOperand(0).getReg();
1915   unsigned BaseReg = LEAMI->getOperand(0).getReg();
1916 
1917   CanDeleteLEA = true;
1918   BaseRegKill = false;
1919   MachineInstr *RemovableAdd = nullptr;
1920   MachineBasicBlock::iterator I(LEAMI);
1921   for (++I; &*I != JumpMI; ++I) {
1922     if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
1923       RemovableAdd = &*I;
1924       break;
1925     }
1926 
1927     for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1928       const MachineOperand &MO = I->getOperand(K);
1929       if (!MO.isReg() || !MO.getReg())
1930         continue;
1931       if (MO.isDef() && MO.getReg() == BaseReg)
1932         return false;
1933       if (MO.isUse() && MO.getReg() == BaseReg) {
1934         BaseRegKill = BaseRegKill || MO.isKill();
1935         CanDeleteLEA = false;
1936       }
1937     }
1938   }
1939 
1940   if (!RemovableAdd)
1941     return true;
1942 
1943   // Check the add really is removable, and that nothing else in the block
1944   // clobbers BaseReg.
1945   for (++I; &*I != JumpMI; ++I) {
1946     for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
1947       const MachineOperand &MO = I->getOperand(K);
1948       if (!MO.isReg() || !MO.getReg())
1949         continue;
1950       if (MO.isDef() && MO.getReg() == BaseReg)
1951         return false;
1952       if (MO.isUse() && MO.getReg() == EntryReg)
1953         RemovableAdd = nullptr;
1954     }
1955   }
1956 
1957   if (RemovableAdd) {
1958     RemovableAdd->eraseFromParent();
1959     DeadSize += isThumb2 ? 4 : 2;
1960   } else if (BaseReg == EntryReg) {
1961     // The add wasn't removable, but clobbered the base for the TBB. So we can't
1962     // preserve it.
1963     return false;
1964   }
1965 
1966   // We reached the end of the block without seeing another definition of
1967   // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
1968   // used in the TBB/TBH if necessary.
1969   return true;
1970 }
1971 
1972 /// \brief Returns whether CPEMI is the first instruction in the block
1973 /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
1974 /// we can switch the first register to PC and usually remove the address
1975 /// calculation that preceded it.
1976 static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
1977   MachineFunction::iterator MBB = JTMI->getParent()->getIterator();
1978   MachineFunction *MF = MBB->getParent();
1979   ++MBB;
1980 
1981   return MBB != MF->end() && MBB->begin() != MBB->end() &&
1982          &*MBB->begin() == CPEMI;
1983 }
1984 
1985 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1986 /// jumptables when it's possible.
1987 bool ARMConstantIslands::optimizeThumb2JumpTables() {
1988   bool MadeChange = false;
1989 
1990   // FIXME: After the tables are shrunk, can we get rid some of the
1991   // constantpool tables?
1992   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1993   if (!MJTI) return false;
1994 
1995   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1996   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1997     MachineInstr *MI = T2JumpTables[i];
1998     const MCInstrDesc &MCID = MI->getDesc();
1999     unsigned NumOps = MCID.getNumOperands();
2000     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2001     MachineOperand JTOP = MI->getOperand(JTOpIdx);
2002     unsigned JTI = JTOP.getIndex();
2003     assert(JTI < JT.size());
2004 
2005     bool ByteOk = true;
2006     bool HalfWordOk = true;
2007     unsigned JTOffset = getOffsetOf(MI) + 4;
2008     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2009     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2010       MachineBasicBlock *MBB = JTBBs[j];
2011       unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
2012       // Negative offset is not ok. FIXME: We should change BB layout to make
2013       // sure all the branches are forward.
2014       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
2015         ByteOk = false;
2016       unsigned TBHLimit = ((1<<16)-1)*2;
2017       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
2018         HalfWordOk = false;
2019       if (!ByteOk && !HalfWordOk)
2020         break;
2021     }
2022 
2023     if (!ByteOk && !HalfWordOk)
2024       continue;
2025 
2026     CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2027     MachineBasicBlock *MBB = MI->getParent();
2028     if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2029       continue;
2030 
2031     unsigned DeadSize = 0;
2032     bool CanDeleteLEA = false;
2033     bool BaseRegKill = false;
2034 
2035     unsigned IdxReg = ~0U;
2036     bool IdxRegKill = true;
2037     if (isThumb2) {
2038       IdxReg = MI->getOperand(1).getReg();
2039       IdxRegKill = MI->getOperand(1).isKill();
2040 
2041       bool PreservedBaseReg =
2042         preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2043       if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2044         continue;
2045     } else {
2046       // We're in thumb-1 mode, so we must have something like:
2047       //   %idx = tLSLri %idx, 2
2048       //   %base = tLEApcrelJT
2049       //   %t = tLDRr %idx, %base
2050       unsigned BaseReg = User.MI->getOperand(0).getReg();
2051 
2052       MachineInstr *Shift = User.MI->getPrevNode();
2053       if (Shift->getOpcode() != ARM::tLSLri ||
2054           Shift->getOperand(3).getImm() != 2 ||
2055           !Shift->getOperand(2).isKill())
2056         continue;
2057       IdxReg = Shift->getOperand(2).getReg();
2058       unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
2059 
2060       MachineInstr *Load = User.MI->getNextNode();
2061       if (Load->getOpcode() != ARM::tLDRr)
2062         continue;
2063       if (Load->getOperand(1).getReg() != ShiftedIdxReg ||
2064           Load->getOperand(2).getReg() != BaseReg ||
2065           !Load->getOperand(1).isKill())
2066         continue;
2067 
2068       // If we're in PIC mode, there should be another ADD following.
2069       if (isPositionIndependentOrROPI) {
2070         MachineInstr *Add = Load->getNextNode();
2071         if (Add->getOpcode() != ARM::tADDrr ||
2072             Add->getOperand(2).getReg() != Load->getOperand(0).getReg() ||
2073             Add->getOperand(3).getReg() != BaseReg ||
2074             !Add->getOperand(2).isKill())
2075           continue;
2076         if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2077           continue;
2078 
2079         Add->eraseFromParent();
2080         DeadSize += 2;
2081       } else {
2082         if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2083           continue;
2084       }
2085 
2086 
2087       // Now safe to delete the load and lsl. The LEA will be removed later.
2088       CanDeleteLEA = true;
2089       Shift->eraseFromParent();
2090       Load->eraseFromParent();
2091       DeadSize += 4;
2092     }
2093 
2094     DEBUG(dbgs() << "Shrink JT: " << *MI);
2095     MachineInstr *CPEMI = User.CPEMI;
2096     unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2097     if (!isThumb2)
2098       Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2099 
2100     MachineBasicBlock::iterator MI_JT = MI;
2101     MachineInstr *NewJTMI =
2102         BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
2103             .addReg(User.MI->getOperand(0).getReg(),
2104                     getKillRegState(BaseRegKill))
2105             .addReg(IdxReg, getKillRegState(IdxRegKill))
2106             .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2107             .addImm(CPEMI->getOperand(0).getImm());
2108     DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
2109 
2110     unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2111     CPEMI->setDesc(TII->get(JTOpc));
2112 
2113     if (jumpTableFollowsTB(MI, User.CPEMI)) {
2114       NewJTMI->getOperand(0).setReg(ARM::PC);
2115       NewJTMI->getOperand(0).setIsKill(false);
2116 
2117       if (CanDeleteLEA)  {
2118         User.MI->eraseFromParent();
2119         DeadSize += isThumb2 ? 4 : 2;
2120 
2121         // The LEA was eliminated, the TBB instruction becomes the only new user
2122         // of the jump table.
2123         User.MI = NewJTMI;
2124         User.MaxDisp = 4;
2125         User.NegOk = false;
2126         User.IsSoImm = false;
2127         User.KnownAlignment = false;
2128       } else {
2129         // The LEA couldn't be eliminated, so we must add another CPUser to
2130         // record the TBB or TBH use.
2131         int CPEntryIdx = JumpTableEntryIndices[JTI];
2132         auto &CPEs = CPEntries[CPEntryIdx];
2133         auto Entry =
2134             find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
2135         ++Entry->RefCount;
2136         CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2137       }
2138     }
2139 
2140     unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2141     unsigned OrigSize = TII->getInstSizeInBytes(*MI);
2142     MI->eraseFromParent();
2143 
2144     int Delta = OrigSize - NewSize + DeadSize;
2145     BBInfo[MBB->getNumber()].Size -= Delta;
2146     adjustBBOffsetsAfter(MBB);
2147 
2148     ++NumTBs;
2149     MadeChange = true;
2150   }
2151 
2152   return MadeChange;
2153 }
2154 
2155 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
2156 /// jump tables always branch forwards, since that's what tbb and tbh need.
2157 bool ARMConstantIslands::reorderThumb2JumpTables() {
2158   bool MadeChange = false;
2159 
2160   MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2161   if (!MJTI) return false;
2162 
2163   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2164   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2165     MachineInstr *MI = T2JumpTables[i];
2166     const MCInstrDesc &MCID = MI->getDesc();
2167     unsigned NumOps = MCID.getNumOperands();
2168     unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2169     MachineOperand JTOP = MI->getOperand(JTOpIdx);
2170     unsigned JTI = JTOP.getIndex();
2171     assert(JTI < JT.size());
2172 
2173     // We prefer if target blocks for the jump table come after the jump
2174     // instruction so we can use TB[BH]. Loop through the target blocks
2175     // and try to adjust them such that that's true.
2176     int JTNumber = MI->getParent()->getNumber();
2177     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2178     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2179       MachineBasicBlock *MBB = JTBBs[j];
2180       int DTNumber = MBB->getNumber();
2181 
2182       if (DTNumber < JTNumber) {
2183         // The destination precedes the switch. Try to move the block forward
2184         // so we have a positive offset.
2185         MachineBasicBlock *NewBB =
2186           adjustJTTargetBlockForward(MBB, MI->getParent());
2187         if (NewBB)
2188           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2189         MadeChange = true;
2190       }
2191     }
2192   }
2193 
2194   return MadeChange;
2195 }
2196 
2197 MachineBasicBlock *ARMConstantIslands::
2198 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2199   // If the destination block is terminated by an unconditional branch,
2200   // try to move it; otherwise, create a new block following the jump
2201   // table that branches back to the actual target. This is a very simple
2202   // heuristic. FIXME: We can definitely improve it.
2203   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2204   SmallVector<MachineOperand, 4> Cond;
2205   SmallVector<MachineOperand, 4> CondPrior;
2206   MachineFunction::iterator BBi = BB->getIterator();
2207   MachineFunction::iterator OldPrior = std::prev(BBi);
2208 
2209   // If the block terminator isn't analyzable, don't try to move the block
2210   bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
2211 
2212   // If the block ends in an unconditional branch, move it. The prior block
2213   // has to have an analyzable terminator for us to move this one. Be paranoid
2214   // and make sure we're not trying to move the entry block of the function.
2215   if (!B && Cond.empty() && BB != &MF->front() &&
2216       !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2217     BB->moveAfter(JTBB);
2218     OldPrior->updateTerminator();
2219     BB->updateTerminator();
2220     // Update numbering to account for the block being moved.
2221     MF->RenumberBlocks();
2222     ++NumJTMoved;
2223     return nullptr;
2224   }
2225 
2226   // Create a new MBB for the code after the jump BB.
2227   MachineBasicBlock *NewBB =
2228     MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2229   MachineFunction::iterator MBBI = ++JTBB->getIterator();
2230   MF->insert(MBBI, NewBB);
2231 
2232   // Add an unconditional branch from NewBB to BB.
2233   // There doesn't seem to be meaningful DebugInfo available; this doesn't
2234   // correspond directly to anything in the source.
2235   if (isThumb2)
2236     BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2237         .addMBB(BB)
2238         .addImm(ARMCC::AL)
2239         .addReg(0);
2240   else
2241     BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2242         .addMBB(BB)
2243         .addImm(ARMCC::AL)
2244         .addReg(0);
2245 
2246   // Update internal data structures to account for the newly inserted MBB.
2247   MF->RenumberBlocks(NewBB);
2248 
2249   // Update the CFG.
2250   NewBB->addSuccessor(BB);
2251   JTBB->replaceSuccessor(BB, NewBB);
2252 
2253   ++NumJTInserted;
2254   return NewBB;
2255 }
2256