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