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