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