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