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