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