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