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