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