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