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