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