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