ARMConstantIslandPass.cpp revision ae73dc1448d25b02cabc7c64c86c64371453dda8
1//===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
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 "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/Statistic.h"
30using namespace llvm;
31
32STATISTIC(NumCPEs,     "Number of constpool entries");
33STATISTIC(NumSplit,    "Number of uncond branches inserted");
34STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
36
37namespace {
38  /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39  /// requires constant pool entries to be scattered among the instructions
40  /// inside a function.  To do this, it completely ignores the normal LLVM
41  /// constant pool; instead, it places constants wherever it feels like with
42  /// special instructions.
43  ///
44  /// The terminology used in this pass includes:
45  ///   Islands - Clumps of constants placed in the function.
46  ///   Water   - Potential places where an island could be formed.
47  ///   CPE     - A constant pool entry that has been placed somewhere, which
48  ///             tracks a list of users.
49  class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50    /// NextUID - Assign unique ID's to CPE's.
51    unsigned NextUID;
52
53    /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
54    /// by MBB Number.  The two-byte pads required for Thumb alignment are
55    /// counted as part of the following block (i.e., the offset and size for
56    /// a padded block will both be ==2 mod 4).
57    std::vector<unsigned> BBSizes;
58
59    /// BBOffsets - the offset of each MBB in bytes, starting from 0.
60    /// The two-byte pads required for Thumb alignment are counted as part of
61    /// the following block.
62    std::vector<unsigned> BBOffsets;
63
64    /// WaterList - A sorted list of basic blocks where islands could be placed
65    /// (i.e. blocks that don't fall through to the following block, due
66    /// to a return, unreachable, or unconditional branch).
67    std::vector<MachineBasicBlock*> WaterList;
68
69    /// CPUser - One user of a constant pool, keeping the machine instruction
70    /// pointer, the constant pool being referenced, and the max displacement
71    /// allowed from the instruction to the CP.
72    struct CPUser {
73      MachineInstr *MI;
74      MachineInstr *CPEMI;
75      unsigned MaxDisp;
76      CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
77        : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
78    };
79
80    /// CPUsers - Keep track of all of the machine instructions that use various
81    /// constant pools and their max displacement.
82    std::vector<CPUser> CPUsers;
83
84    /// CPEntry - One per constant pool entry, keeping the machine instruction
85    /// pointer, the constpool index, and the number of CPUser's which
86    /// reference this entry.
87    struct CPEntry {
88      MachineInstr *CPEMI;
89      unsigned CPI;
90      unsigned RefCount;
91      CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
92        : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
93    };
94
95    /// CPEntries - Keep track of all of the constant pool entry machine
96    /// instructions. For each original constpool index (i.e. those that
97    /// existed upon entry to this pass), it keeps a vector of entries.
98    /// Original elements are cloned as we go along; the clones are
99    /// put in the vector of the original element, but have distinct CPIs.
100    std::vector<std::vector<CPEntry> > CPEntries;
101
102    /// ImmBranch - One per immediate branch, keeping the machine instruction
103    /// pointer, conditional or unconditional, the max displacement,
104    /// and (if isCond is true) the corresponding unconditional branch
105    /// opcode.
106    struct ImmBranch {
107      MachineInstr *MI;
108      unsigned MaxDisp : 31;
109      bool isCond : 1;
110      int UncondBr;
111      ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
112        : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
113    };
114
115    /// ImmBranches - Keep track of all the immediate branch instructions.
116    ///
117    std::vector<ImmBranch> ImmBranches;
118
119    /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
120    ///
121    SmallVector<MachineInstr*, 4> PushPopMIs;
122
123    /// HasFarJump - True if any far jump instruction has been emitted during
124    /// the branch fix up pass.
125    bool HasFarJump;
126
127    const TargetInstrInfo *TII;
128    ARMFunctionInfo *AFI;
129    bool isThumb;
130  public:
131    static char ID;
132    ARMConstantIslands() : MachineFunctionPass(&ID) {}
133
134    virtual bool runOnMachineFunction(MachineFunction &Fn);
135
136    virtual const char *getPassName() const {
137      return "ARM constant island placement and branch shortening pass";
138    }
139
140  private:
141    void DoInitialPlacement(MachineFunction &Fn,
142                            std::vector<MachineInstr*> &CPEMIs);
143    CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
144    void InitialFunctionScan(MachineFunction &Fn,
145                             const std::vector<MachineInstr*> &CPEMIs);
146    MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
147    void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
148    void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
149    bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
150    int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
151    bool LookForWater(CPUser&U, unsigned UserOffset,
152                      MachineBasicBlock** NewMBB);
153    MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
154                        std::vector<MachineBasicBlock*>::iterator IP);
155    void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
156                      MachineBasicBlock** NewMBB);
157    bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
158    void RemoveDeadCPEMI(MachineInstr *CPEMI);
159    bool RemoveUnusedCPEntries();
160    bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
161                      MachineInstr *CPEMI, unsigned Disp,
162                      bool DoDump);
163    bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
164                        CPUser &U);
165    bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
166                        unsigned Disp, bool NegativeOK);
167    bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
168    bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
169    bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
170    bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
171    bool UndoLRSpillRestore();
172
173    unsigned GetOffsetOf(MachineInstr *MI) const;
174    void dumpBBs();
175    void verify(MachineFunction &Fn);
176  };
177  char ARMConstantIslands::ID = 0;
178}
179
180/// verify - check BBOffsets, BBSizes, alignment of islands
181void ARMConstantIslands::verify(MachineFunction &Fn) {
182  assert(BBOffsets.size() == BBSizes.size());
183  for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
184    assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
185  if (isThumb) {
186    for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
187         MBBI != E; ++MBBI) {
188      MachineBasicBlock *MBB = MBBI;
189      if (!MBB->empty() &&
190          MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
191        assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
192                BBSizes[MBB->getNumber()]%4 == 0) ||
193               (BBOffsets[MBB->getNumber()]%4 != 0 &&
194                BBSizes[MBB->getNumber()]%4 != 0));
195    }
196  }
197}
198
199/// print block size and offset information - debugging
200void ARMConstantIslands::dumpBBs() {
201  for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
202    DOUT << "block " << J << " offset " << BBOffsets[J] <<
203                            " size " << BBSizes[J] << "\n";
204  }
205}
206
207/// createARMConstantIslandPass - returns an instance of the constpool
208/// island pass.
209FunctionPass *llvm::createARMConstantIslandPass() {
210  return new ARMConstantIslands();
211}
212
213bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
214  MachineConstantPool &MCP = *Fn.getConstantPool();
215
216  TII = Fn.getTarget().getInstrInfo();
217  AFI = Fn.getInfo<ARMFunctionInfo>();
218  isThumb = AFI->isThumbFunction();
219
220  HasFarJump = false;
221
222  // Renumber all of the machine basic blocks in the function, guaranteeing that
223  // the numbers agree with the position of the block in the function.
224  Fn.RenumberBlocks();
225
226  /// Thumb functions containing constant pools get 2-byte alignment.  This is so
227  /// we can keep exact track of where the alignment padding goes.  Set default.
228  AFI->setAlign(isThumb ? 1U : 2U);
229
230  // Perform the initial placement of the constant pool entries.  To start with,
231  // we put them all at the end of the function.
232  std::vector<MachineInstr*> CPEMIs;
233  if (!MCP.isEmpty()) {
234    DoInitialPlacement(Fn, CPEMIs);
235    if (isThumb)
236      AFI->setAlign(2U);
237  }
238
239  /// The next UID to take is the first unused one.
240  NextUID = CPEMIs.size();
241
242  // Do the initial scan of the function, building up information about the
243  // sizes of each block, the location of all the water, and finding all of the
244  // constant pool users.
245  InitialFunctionScan(Fn, CPEMIs);
246  CPEMIs.clear();
247
248  /// Remove dead constant pool entries.
249  RemoveUnusedCPEntries();
250
251  // Iteratively place constant pool entries and fix up branches until there
252  // is no change.
253  bool MadeChange = false;
254  while (true) {
255    bool Change = false;
256    for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
257      Change |= HandleConstantPoolUser(Fn, i);
258    DEBUG(dumpBBs());
259    for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
260      Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
261    DEBUG(dumpBBs());
262    if (!Change)
263      break;
264    MadeChange = true;
265  }
266
267  // After a while, this might be made debug-only, but it is not expensive.
268  verify(Fn);
269
270  // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
271  // Undo the spill / restore of LR if possible.
272  if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
273    MadeChange |= UndoLRSpillRestore();
274
275  BBSizes.clear();
276  BBOffsets.clear();
277  WaterList.clear();
278  CPUsers.clear();
279  CPEntries.clear();
280  ImmBranches.clear();
281  PushPopMIs.clear();
282
283  return MadeChange;
284}
285
286/// DoInitialPlacement - Perform the initial placement of the constant pool
287/// entries.  To start with, we put them all at the end of the function.
288void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
289                                        std::vector<MachineInstr*> &CPEMIs){
290  // Create the basic block to hold the CPE's.
291  MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
292  Fn.push_back(BB);
293
294  // Add all of the constants from the constant pool to the end block, use an
295  // identity mapping of CPI's to CPE's.
296  const std::vector<MachineConstantPoolEntry> &CPs =
297    Fn.getConstantPool()->getConstants();
298
299  const TargetData &TD = *Fn.getTarget().getTargetData();
300  for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
301    unsigned Size = TD.getABITypeSize(CPs[i].getType());
302    // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
303    // we would have to pad them out or something so that instructions stay
304    // aligned.
305    assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
306    MachineInstr *CPEMI =
307      BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
308                           .addImm(i).addConstantPoolIndex(i).addImm(Size);
309    CPEMIs.push_back(CPEMI);
310
311    // Add a new CPEntry, but no corresponding CPUser yet.
312    std::vector<CPEntry> CPEs;
313    CPEs.push_back(CPEntry(CPEMI, i));
314    CPEntries.push_back(CPEs);
315    NumCPEs++;
316    DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
317  }
318}
319
320/// BBHasFallthrough - Return true if the specified basic block can fallthrough
321/// into the block immediately after it.
322static bool BBHasFallthrough(MachineBasicBlock *MBB) {
323  // Get the next machine basic block in the function.
324  MachineFunction::iterator MBBI = MBB;
325  if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
326    return false;
327
328  MachineBasicBlock *NextBB = next(MBBI);
329  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
330       E = MBB->succ_end(); I != E; ++I)
331    if (*I == NextBB)
332      return true;
333
334  return false;
335}
336
337/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
338/// look up the corresponding CPEntry.
339ARMConstantIslands::CPEntry
340*ARMConstantIslands::findConstPoolEntry(unsigned CPI,
341                                        const MachineInstr *CPEMI) {
342  std::vector<CPEntry> &CPEs = CPEntries[CPI];
343  // Number of entries per constpool index should be small, just do a
344  // linear search.
345  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
346    if (CPEs[i].CPEMI == CPEMI)
347      return &CPEs[i];
348  }
349  return NULL;
350}
351
352/// InitialFunctionScan - Do the initial scan of the function, building up
353/// information about the sizes of each block, the location of all the water,
354/// and finding all of the constant pool users.
355void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
356                                 const std::vector<MachineInstr*> &CPEMIs) {
357  unsigned Offset = 0;
358  for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
359       MBBI != E; ++MBBI) {
360    MachineBasicBlock &MBB = *MBBI;
361
362    // If this block doesn't fall through into the next MBB, then this is
363    // 'water' that a constant pool island could be placed.
364    if (!BBHasFallthrough(&MBB))
365      WaterList.push_back(&MBB);
366
367    unsigned MBBSize = 0;
368    for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
369         I != E; ++I) {
370      // Add instruction size to MBBSize.
371      MBBSize += TII->GetInstSizeInBytes(I);
372
373      int Opc = I->getOpcode();
374      if (I->getDesc().isBranch()) {
375        bool isCond = false;
376        unsigned Bits = 0;
377        unsigned Scale = 1;
378        int UOpc = Opc;
379        switch (Opc) {
380        case ARM::tBR_JTr:
381          // A Thumb table jump may involve padding; for the offsets to
382          // be right, functions containing these must be 4-byte aligned.
383          AFI->setAlign(2U);
384          if ((Offset+MBBSize)%4 != 0)
385            MBBSize += 2;           // padding
386          continue;   // Does not get an entry in ImmBranches
387        default:
388          continue;  // Ignore other JT branches
389        case ARM::Bcc:
390          isCond = true;
391          UOpc = ARM::B;
392          // Fallthrough
393        case ARM::B:
394          Bits = 24;
395          Scale = 4;
396          break;
397        case ARM::tBcc:
398          isCond = true;
399          UOpc = ARM::tB;
400          Bits = 8;
401          Scale = 2;
402          break;
403        case ARM::tB:
404          Bits = 11;
405          Scale = 2;
406          break;
407        }
408
409        // Record this immediate branch.
410        unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
411        ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
412      }
413
414      if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
415        PushPopMIs.push_back(I);
416
417      // Scan the instructions for constant pool operands.
418      for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
419        if (I->getOperand(op).isConstantPoolIndex()) {
420          // We found one.  The addressing mode tells us the max displacement
421          // from the PC that this instruction permits.
422
423          // Basic size info comes from the TSFlags field.
424          unsigned Bits = 0;
425          unsigned Scale = 1;
426          unsigned TSFlags = I->getDesc().TSFlags;
427          switch (TSFlags & ARMII::AddrModeMask) {
428          default:
429            // Constant pool entries can reach anything.
430            if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
431              continue;
432            if (I->getOpcode() == ARM::tLEApcrel) {
433              Bits = 8;  // Taking the address of a CP entry.
434              break;
435            }
436            assert(0 && "Unknown addressing mode for CP reference!");
437          case ARMII::AddrMode1: // AM1: 8 bits << 2
438            Bits = 8;
439            Scale = 4;  // Taking the address of a CP entry.
440            break;
441          case ARMII::AddrMode2:
442            Bits = 12;  // +-offset_12
443            break;
444          case ARMII::AddrMode3:
445            Bits = 8;   // +-offset_8
446            break;
447            // addrmode4 has no immediate offset.
448          case ARMII::AddrMode5:
449            Bits = 8;
450            Scale = 4;  // +-(offset_8*4)
451            break;
452          case ARMII::AddrModeT1:
453            Bits = 5;  // +offset_5
454            break;
455          case ARMII::AddrModeT2:
456            Bits = 5;
457            Scale = 2;  // +(offset_5*2)
458            break;
459          case ARMII::AddrModeT4:
460            Bits = 5;
461            Scale = 4;  // +(offset_5*4)
462            break;
463          case ARMII::AddrModeTs:
464            Bits = 8;
465            Scale = 4;  // +(offset_8*4)
466            break;
467          }
468
469          // Remember that this is a user of a CP entry.
470          unsigned CPI = I->getOperand(op).getIndex();
471          MachineInstr *CPEMI = CPEMIs[CPI];
472          unsigned MaxOffs = ((1 << Bits)-1) * Scale;
473          CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
474
475          // Increment corresponding CPEntry reference count.
476          CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
477          assert(CPE && "Cannot find a corresponding CPEntry!");
478          CPE->RefCount++;
479
480          // Instructions can only use one CP entry, don't bother scanning the
481          // rest of the operands.
482          break;
483        }
484    }
485
486    // In thumb mode, if this block is a constpool island, we may need padding
487    // so it's aligned on 4 byte boundary.
488    if (isThumb &&
489        !MBB.empty() &&
490        MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
491        (Offset%4) != 0)
492      MBBSize += 2;
493
494    BBSizes.push_back(MBBSize);
495    BBOffsets.push_back(Offset);
496    Offset += MBBSize;
497  }
498}
499
500/// GetOffsetOf - Return the current offset of the specified machine instruction
501/// from the start of the function.  This offset changes as stuff is moved
502/// around inside the function.
503unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
504  MachineBasicBlock *MBB = MI->getParent();
505
506  // The offset is composed of two things: the sum of the sizes of all MBB's
507  // before this instruction's block, and the offset from the start of the block
508  // it is in.
509  unsigned Offset = BBOffsets[MBB->getNumber()];
510
511  // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
512  // alignment padding, and compensate if so.
513  if (isThumb &&
514      MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
515      Offset%4 != 0)
516    Offset += 2;
517
518  // Sum instructions before MI in MBB.
519  for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
520    assert(I != MBB->end() && "Didn't find MI in its own basic block?");
521    if (&*I == MI) return Offset;
522    Offset += TII->GetInstSizeInBytes(I);
523  }
524}
525
526/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
527/// ID.
528static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
529                              const MachineBasicBlock *RHS) {
530  return LHS->getNumber() < RHS->getNumber();
531}
532
533/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
534/// machine function, it upsets all of the block numbers.  Renumber the blocks
535/// and update the arrays that parallel this numbering.
536void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
537  // Renumber the MBB's to keep them consequtive.
538  NewBB->getParent()->RenumberBlocks(NewBB);
539
540  // Insert a size into BBSizes to align it properly with the (newly
541  // renumbered) block numbers.
542  BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
543
544  // Likewise for BBOffsets.
545  BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
546
547  // Next, update WaterList.  Specifically, we need to add NewMBB as having
548  // available water after it.
549  std::vector<MachineBasicBlock*>::iterator IP =
550    std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
551                     CompareMBBNumbers);
552  WaterList.insert(IP, NewBB);
553}
554
555
556/// Split the basic block containing MI into two blocks, which are joined by
557/// an unconditional branch.  Update datastructures and renumber blocks to
558/// account for this change and returns the newly created block.
559MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
560  MachineBasicBlock *OrigBB = MI->getParent();
561  MachineFunction &MF = *OrigBB->getParent();
562
563  // Create a new MBB for the code after the OrigBB.
564  MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
565  MachineFunction::iterator MBBI = OrigBB; ++MBBI;
566  MF.insert(MBBI, NewBB);
567
568  // Splice the instructions starting with MI over to NewBB.
569  NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
570
571  // Add an unconditional branch from OrigBB to NewBB.
572  // Note the new unconditional branch is not being recorded.
573  BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
574  NumSplit++;
575
576  // Update the CFG.  All succs of OrigBB are now succs of NewBB.
577  while (!OrigBB->succ_empty()) {
578    MachineBasicBlock *Succ = *OrigBB->succ_begin();
579    OrigBB->removeSuccessor(Succ);
580    NewBB->addSuccessor(Succ);
581
582    // This pass should be run after register allocation, so there should be no
583    // PHI nodes to update.
584    assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
585           && "PHI nodes should be eliminated by now!");
586  }
587
588  // OrigBB branches to NewBB.
589  OrigBB->addSuccessor(NewBB);
590
591  // Update internal data structures to account for the newly inserted MBB.
592  // This is almost the same as UpdateForInsertedWaterBlock, except that
593  // the Water goes after OrigBB, not NewBB.
594  MF.RenumberBlocks(NewBB);
595
596  // Insert a size into BBSizes to align it properly with the (newly
597  // renumbered) block numbers.
598  BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
599
600  // Likewise for BBOffsets.
601  BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
602
603  // Next, update WaterList.  Specifically, we need to add OrigMBB as having
604  // available water after it (but not if it's already there, which happens
605  // when splitting before a conditional branch that is followed by an
606  // unconditional branch - in that case we want to insert NewBB).
607  std::vector<MachineBasicBlock*>::iterator IP =
608    std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
609                     CompareMBBNumbers);
610  MachineBasicBlock* WaterBB = *IP;
611  if (WaterBB == OrigBB)
612    WaterList.insert(next(IP), NewBB);
613  else
614    WaterList.insert(IP, OrigBB);
615
616  // Figure out how large the first NewMBB is.  (It cannot
617  // contain a constpool_entry or tablejump.)
618  unsigned NewBBSize = 0;
619  for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
620       I != E; ++I)
621    NewBBSize += TII->GetInstSizeInBytes(I);
622
623  unsigned OrigBBI = OrigBB->getNumber();
624  unsigned NewBBI = NewBB->getNumber();
625  // Set the size of NewBB in BBSizes.
626  BBSizes[NewBBI] = NewBBSize;
627
628  // We removed instructions from UserMBB, subtract that off from its size.
629  // Add 2 or 4 to the block to count the unconditional branch we added to it.
630  unsigned delta = isThumb ? 2 : 4;
631  BBSizes[OrigBBI] -= NewBBSize - delta;
632
633  // ...and adjust BBOffsets for NewBB accordingly.
634  BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
635
636  // All BBOffsets following these blocks must be modified.
637  AdjustBBOffsetsAfter(NewBB, delta);
638
639  return NewBB;
640}
641
642/// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
643/// reference) is within MaxDisp of TrialOffset (a proposed location of a
644/// constant pool entry).
645bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
646                      unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
647  // On Thumb offsets==2 mod 4 are rounded down by the hardware for
648  // purposes of the displacement computation; compensate for that here.
649  // Effectively, the valid range of displacements is 2 bytes smaller for such
650  // references.
651  if (isThumb && UserOffset%4 !=0)
652    UserOffset -= 2;
653  // CPEs will be rounded up to a multiple of 4.
654  if (isThumb && TrialOffset%4 != 0)
655    TrialOffset += 2;
656
657  if (UserOffset <= TrialOffset) {
658    // User before the Trial.
659    if (TrialOffset-UserOffset <= MaxDisp)
660      return true;
661  } else if (NegativeOK) {
662    if (UserOffset-TrialOffset <= MaxDisp)
663      return true;
664  }
665  return false;
666}
667
668/// WaterIsInRange - Returns true if a CPE placed after the specified
669/// Water (a basic block) will be in range for the specific MI.
670
671bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
672                         MachineBasicBlock* Water, CPUser &U)
673{
674  unsigned MaxDisp = U.MaxDisp;
675  MachineFunction::iterator I = next(MachineFunction::iterator(Water));
676  unsigned CPEOffset = BBOffsets[Water->getNumber()] +
677                       BBSizes[Water->getNumber()];
678
679  // If the CPE is to be inserted before the instruction, that will raise
680  // the offset of the instruction.  (Currently applies only to ARM, so
681  // no alignment compensation attempted here.)
682  if (CPEOffset < UserOffset)
683    UserOffset += U.CPEMI->getOperand(2).getImm();
684
685  return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
686}
687
688/// CPEIsInRange - Returns true if the distance between specific MI and
689/// specific ConstPool entry instruction can fit in MI's displacement field.
690bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
691                                      MachineInstr *CPEMI,
692                                      unsigned MaxDisp, bool DoDump) {
693  unsigned CPEOffset  = GetOffsetOf(CPEMI);
694  assert(CPEOffset%4 == 0 && "Misaligned CPE");
695
696  if (DoDump) {
697    DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
698         << " max delta=" << MaxDisp
699         << " insn address=" << UserOffset
700         << " CPE address=" << CPEOffset
701         << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
702  }
703
704  return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
705}
706
707/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
708/// unconditionally branches to its only successor.
709static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
710  if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
711    return false;
712
713  MachineBasicBlock *Succ = *MBB->succ_begin();
714  MachineBasicBlock *Pred = *MBB->pred_begin();
715  MachineInstr *PredMI = &Pred->back();
716  if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
717    return PredMI->getOperand(0).getMBB() == Succ;
718  return false;
719}
720
721void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
722                                              int delta) {
723  MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
724  for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
725    BBOffsets[i] += delta;
726    // If some existing blocks have padding, adjust the padding as needed, a
727    // bit tricky.  delta can be negative so don't use % on that.
728    if (isThumb) {
729      MachineBasicBlock *MBB = MBBI;
730      if (!MBB->empty()) {
731        // Constant pool entries require padding.
732        if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
733          unsigned oldOffset = BBOffsets[i] - delta;
734          if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
735            // add new padding
736            BBSizes[i] += 2;
737            delta += 2;
738          } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
739            // remove existing padding
740            BBSizes[i] -=2;
741            delta -= 2;
742          }
743        }
744        // Thumb jump tables require padding.  They should be at the end;
745        // following unconditional branches are removed by AnalyzeBranch.
746        MachineInstr *ThumbJTMI = NULL;
747        if (prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
748          ThumbJTMI = prior(MBB->end());
749        if (ThumbJTMI) {
750          unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
751          unsigned oldMIOffset = newMIOffset - delta;
752          if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
753            // remove existing padding
754            BBSizes[i] -= 2;
755            delta -= 2;
756          } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
757            // add new padding
758            BBSizes[i] += 2;
759            delta += 2;
760          }
761        }
762        if (delta==0)
763          return;
764      }
765      MBBI = next(MBBI);
766    }
767  }
768}
769
770/// DecrementOldEntry - find the constant pool entry with index CPI
771/// and instruction CPEMI, and decrement its refcount.  If the refcount
772/// becomes 0 remove the entry and instruction.  Returns true if we removed
773/// the entry, false if we didn't.
774
775bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
776  // Find the old entry. Eliminate it if it is no longer used.
777  CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
778  assert(CPE && "Unexpected!");
779  if (--CPE->RefCount == 0) {
780    RemoveDeadCPEMI(CPEMI);
781    CPE->CPEMI = NULL;
782    NumCPEs--;
783    return true;
784  }
785  return false;
786}
787
788/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
789/// if not, see if an in-range clone of the CPE is in range, and if so,
790/// change the data structures so the user references the clone.  Returns:
791/// 0 = no existing entry found
792/// 1 = entry found, and there were no code insertions or deletions
793/// 2 = entry found, and there were code insertions or deletions
794int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
795{
796  MachineInstr *UserMI = U.MI;
797  MachineInstr *CPEMI  = U.CPEMI;
798
799  // Check to see if the CPE is already in-range.
800  if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
801    DOUT << "In range\n";
802    return 1;
803  }
804
805  // No.  Look for previously created clones of the CPE that are in range.
806  unsigned CPI = CPEMI->getOperand(1).getIndex();
807  std::vector<CPEntry> &CPEs = CPEntries[CPI];
808  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
809    // We already tried this one
810    if (CPEs[i].CPEMI == CPEMI)
811      continue;
812    // Removing CPEs can leave empty entries, skip
813    if (CPEs[i].CPEMI == NULL)
814      continue;
815    if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
816      DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
817      // Point the CPUser node to the replacement
818      U.CPEMI = CPEs[i].CPEMI;
819      // Change the CPI in the instruction operand to refer to the clone.
820      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
821        if (UserMI->getOperand(j).isConstantPoolIndex()) {
822          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
823          break;
824        }
825      // Adjust the refcount of the clone...
826      CPEs[i].RefCount++;
827      // ...and the original.  If we didn't remove the old entry, none of the
828      // addresses changed, so we don't need another pass.
829      return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
830    }
831  }
832  return 0;
833}
834
835/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
836/// the specific unconditional branch instruction.
837static inline unsigned getUnconditionalBrDisp(int Opc) {
838  return (Opc == ARM::tB) ? ((1<<10)-1)*2 : ((1<<23)-1)*4;
839}
840
841/// AcceptWater - Small amount of common code factored out of the following.
842
843MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
844                          std::vector<MachineBasicBlock*>::iterator IP) {
845  DOUT << "found water in range\n";
846  // Remove the original WaterList entry; we want subsequent
847  // insertions in this vicinity to go after the one we're
848  // about to insert.  This considerably reduces the number
849  // of times we have to move the same CPE more than once.
850  WaterList.erase(IP);
851  // CPE goes before following block (NewMBB).
852  return next(MachineFunction::iterator(WaterBB));
853}
854
855/// LookForWater - look for an existing entry in the WaterList in which
856/// we can place the CPE referenced from U so it's within range of U's MI.
857/// Returns true if found, false if not.  If it returns true, *NewMBB
858/// is set to the WaterList entry.
859/// For ARM, we prefer the water that's farthest away.  For Thumb, prefer
860/// water that will not introduce padding to water that will; within each
861/// group, prefer the water that's farthest away.
862
863bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
864                                      MachineBasicBlock** NewMBB) {
865  std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
866  MachineBasicBlock* WaterBBThatWouldPad = NULL;
867  if (!WaterList.empty()) {
868    for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
869        B = WaterList.begin();; --IP) {
870      MachineBasicBlock* WaterBB = *IP;
871      if (WaterIsInRange(UserOffset, WaterBB, U)) {
872        if (isThumb &&
873            (BBOffsets[WaterBB->getNumber()] +
874             BBSizes[WaterBB->getNumber()])%4 != 0) {
875          // This is valid Water, but would introduce padding.  Remember
876          // it in case we don't find any Water that doesn't do this.
877          if (!WaterBBThatWouldPad) {
878            WaterBBThatWouldPad = WaterBB;
879            IPThatWouldPad = IP;
880          }
881        } else {
882          *NewMBB = AcceptWater(WaterBB, IP);
883          return true;
884        }
885    }
886      if (IP == B)
887        break;
888    }
889  }
890  if (isThumb && WaterBBThatWouldPad) {
891    *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
892    return true;
893  }
894  return false;
895}
896
897/// CreateNewWater - No existing WaterList entry will work for
898/// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
899/// block is used if in range, and the conditional branch munged so control
900/// flow is correct.  Otherwise the block is split to create a hole with an
901/// unconditional branch around it.  In either case *NewMBB is set to a
902/// block following which the new island can be inserted (the WaterList
903/// is not adjusted).
904
905void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
906                        unsigned UserOffset, MachineBasicBlock** NewMBB) {
907  CPUser &U = CPUsers[CPUserIndex];
908  MachineInstr *UserMI = U.MI;
909  MachineInstr *CPEMI  = U.CPEMI;
910  MachineBasicBlock *UserMBB = UserMI->getParent();
911  unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
912                               BBSizes[UserMBB->getNumber()];
913  assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
914
915  // If the use is at the end of the block, or the end of the block
916  // is within range, make new water there.  (The addition below is
917  // for the unconditional branch we will be adding:  4 bytes on ARM,
918  // 2 on Thumb.  Possible Thumb alignment padding is allowed for
919  // inside OffsetIsInRange.
920  // If the block ends in an unconditional branch already, it is water,
921  // and is known to be out of range, so we'll always be adding a branch.)
922  if (&UserMBB->back() == UserMI ||
923      OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
924           U.MaxDisp, !isThumb)) {
925    DOUT << "Split at end of block\n";
926    if (&UserMBB->back() == UserMI)
927      assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
928    *NewMBB = next(MachineFunction::iterator(UserMBB));
929    // Add an unconditional branch from UserMBB to fallthrough block.
930    // Record it for branch lengthening; this new branch will not get out of
931    // range, but if the preceding conditional branch is out of range, the
932    // targets will be exchanged, and the altered branch may be out of
933    // range, so the machinery has to know about it.
934    int UncondBr = isThumb ? ARM::tB : ARM::B;
935    BuildMI(UserMBB, TII->get(UncondBr)).addMBB(*NewMBB);
936    unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
937    ImmBranches.push_back(ImmBranch(&UserMBB->back(),
938                          MaxDisp, false, UncondBr));
939    int delta = isThumb ? 2 : 4;
940    BBSizes[UserMBB->getNumber()] += delta;
941    AdjustBBOffsetsAfter(UserMBB, delta);
942  } else {
943    // What a big block.  Find a place within the block to split it.
944    // This is a little tricky on Thumb since instructions are 2 bytes
945    // and constant pool entries are 4 bytes: if instruction I references
946    // island CPE, and instruction I+1 references CPE', it will
947    // not work well to put CPE as far forward as possible, since then
948    // CPE' cannot immediately follow it (that location is 2 bytes
949    // farther away from I+1 than CPE was from I) and we'd need to create
950    // a new island.  So, we make a first guess, then walk through the
951    // instructions between the one currently being looked at and the
952    // possible insertion point, and make sure any other instructions
953    // that reference CPEs will be able to use the same island area;
954    // if not, we back up the insertion point.
955
956    // The 4 in the following is for the unconditional branch we'll be
957    // inserting (allows for long branch on Thumb).  Alignment of the
958    // island is handled inside OffsetIsInRange.
959    unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
960    // This could point off the end of the block if we've already got
961    // constant pool entries following this block; only the last one is
962    // in the water list.  Back past any possible branches (allow for a
963    // conditional and a maximally long unconditional).
964    if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
965      BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
966                              (isThumb ? 6 : 8);
967    unsigned EndInsertOffset = BaseInsertOffset +
968           CPEMI->getOperand(2).getImm();
969    MachineBasicBlock::iterator MI = UserMI;
970    ++MI;
971    unsigned CPUIndex = CPUserIndex+1;
972    for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
973         Offset < BaseInsertOffset;
974         Offset += TII->GetInstSizeInBytes(MI),
975            MI = next(MI)) {
976      if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
977        if (!OffsetIsInRange(Offset, EndInsertOffset,
978              CPUsers[CPUIndex].MaxDisp, !isThumb)) {
979          BaseInsertOffset -= (isThumb ? 2 : 4);
980          EndInsertOffset -= (isThumb ? 2 : 4);
981        }
982        // This is overly conservative, as we don't account for CPEMIs
983        // being reused within the block, but it doesn't matter much.
984        EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
985        CPUIndex++;
986      }
987    }
988    DOUT << "Split in middle of big block\n";
989    *NewMBB = SplitBlockBeforeInstr(prior(MI));
990  }
991}
992
993/// HandleConstantPoolUser - Analyze the specified user, checking to see if it
994/// is out-of-range.  If so, pick it up the constant pool value and move it some
995/// place in-range.  Return true if we changed any addresses (thus must run
996/// another pass of branch lengthening), false otherwise.
997bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
998                                                unsigned CPUserIndex){
999  CPUser &U = CPUsers[CPUserIndex];
1000  MachineInstr *UserMI = U.MI;
1001  MachineInstr *CPEMI  = U.CPEMI;
1002  unsigned CPI = CPEMI->getOperand(1).getIndex();
1003  unsigned Size = CPEMI->getOperand(2).getImm();
1004  MachineBasicBlock *NewMBB;
1005  // Compute this only once, it's expensive.  The 4 or 8 is the value the
1006  //  hardware keeps in the PC (2 insns ahead of the reference).
1007  unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1008
1009  // Special case: tLEApcrel are two instructions MI's. The actual user is the
1010  // second instruction.
1011  if (UserMI->getOpcode() == ARM::tLEApcrel)
1012    UserOffset += 2;
1013
1014  // See if the current entry is within range, or there is a clone of it
1015  // in range.
1016  int result = LookForExistingCPEntry(U, UserOffset);
1017  if (result==1) return false;
1018  else if (result==2) return true;
1019
1020  // No existing clone of this CPE is within range.
1021  // We will be generating a new clone.  Get a UID for it.
1022  unsigned ID  = NextUID++;
1023
1024  // Look for water where we can place this CPE.  We look for the farthest one
1025  // away that will work.  Forward references only for now (although later
1026  // we might find some that are backwards).
1027
1028  if (!LookForWater(U, UserOffset, &NewMBB)) {
1029    // No water found.
1030    DOUT << "No water found\n";
1031    CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1032  }
1033
1034  // Okay, we know we can put an island before NewMBB now, do it!
1035  MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1036  Fn.insert(NewMBB, NewIsland);
1037
1038  // Update internal data structures to account for the newly inserted MBB.
1039  UpdateForInsertedWaterBlock(NewIsland);
1040
1041  // Decrement the old entry, and remove it if refcount becomes 0.
1042  DecrementOldEntry(CPI, CPEMI);
1043
1044  // Now that we have an island to add the CPE to, clone the original CPE and
1045  // add it to the island.
1046  U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
1047                .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1048  CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1049  NumCPEs++;
1050
1051  BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1052  // Compensate for .align 2 in thumb mode.
1053  if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1054    Size += 2;
1055  // Increase the size of the island block to account for the new entry.
1056  BBSizes[NewIsland->getNumber()] += Size;
1057  AdjustBBOffsetsAfter(NewIsland, Size);
1058
1059  // Finally, change the CPI in the instruction operand to be ID.
1060  for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1061    if (UserMI->getOperand(i).isCPI()) {
1062      UserMI->getOperand(i).setIndex(ID);
1063      break;
1064    }
1065
1066  DOUT << "  Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
1067
1068  return true;
1069}
1070
1071/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1072/// sizes and offsets of impacted basic blocks.
1073void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1074  MachineBasicBlock *CPEBB = CPEMI->getParent();
1075  unsigned Size = CPEMI->getOperand(2).getImm();
1076  CPEMI->eraseFromParent();
1077  BBSizes[CPEBB->getNumber()] -= Size;
1078  // All succeeding offsets have the current size value added in, fix this.
1079  if (CPEBB->empty()) {
1080    // In thumb mode, the size of island may be  padded by two to compensate for
1081    // the alignment requirement.  Then it will now be 2 when the block is
1082    // empty, so fix this.
1083    // All succeeding offsets have the current size value added in, fix this.
1084    if (BBSizes[CPEBB->getNumber()] != 0) {
1085      Size += BBSizes[CPEBB->getNumber()];
1086      BBSizes[CPEBB->getNumber()] = 0;
1087    }
1088  }
1089  AdjustBBOffsetsAfter(CPEBB, -Size);
1090  // An island has only one predecessor BB and one successor BB. Check if
1091  // this BB's predecessor jumps directly to this BB's successor. This
1092  // shouldn't happen currently.
1093  assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1094  // FIXME: remove the empty blocks after all the work is done?
1095}
1096
1097/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1098/// are zero.
1099bool ARMConstantIslands::RemoveUnusedCPEntries() {
1100  unsigned MadeChange = false;
1101  for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1102      std::vector<CPEntry> &CPEs = CPEntries[i];
1103      for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1104        if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1105          RemoveDeadCPEMI(CPEs[j].CPEMI);
1106          CPEs[j].CPEMI = NULL;
1107          MadeChange = true;
1108        }
1109      }
1110  }
1111  return MadeChange;
1112}
1113
1114/// BBIsInRange - Returns true if the distance between specific MI and
1115/// specific BB can fit in MI's displacement field.
1116bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1117                                     unsigned MaxDisp) {
1118  unsigned PCAdj      = isThumb ? 4 : 8;
1119  unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
1120  unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1121
1122  DOUT << "Branch of destination BB#" << DestBB->getNumber()
1123       << " from BB#" << MI->getParent()->getNumber()
1124       << " max delta=" << MaxDisp
1125       << " from " << GetOffsetOf(MI) << " to " << DestOffset
1126       << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1127
1128  if (BrOffset <= DestOffset) {
1129    // Branch before the Dest.
1130    if (DestOffset-BrOffset <= MaxDisp)
1131      return true;
1132  } else {
1133    if (BrOffset-DestOffset <= MaxDisp)
1134      return true;
1135  }
1136  return false;
1137}
1138
1139/// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1140/// away to fit in its displacement field.
1141bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1142  MachineInstr *MI = Br.MI;
1143  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1144
1145  // Check to see if the DestBB is already in-range.
1146  if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1147    return false;
1148
1149  if (!Br.isCond)
1150    return FixUpUnconditionalBr(Fn, Br);
1151  return FixUpConditionalBr(Fn, Br);
1152}
1153
1154/// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1155/// too far away to fit in its displacement field. If the LR register has been
1156/// spilled in the epilogue, then we can use BL to implement a far jump.
1157/// Otherwise, add an intermediate branch instruction to to a branch.
1158bool
1159ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1160  MachineInstr *MI = Br.MI;
1161  MachineBasicBlock *MBB = MI->getParent();
1162  assert(isThumb && "Expected a Thumb function!");
1163
1164  // Use BL to implement far jump.
1165  Br.MaxDisp = (1 << 21) * 2;
1166  MI->setDesc(TII->get(ARM::tBfar));
1167  BBSizes[MBB->getNumber()] += 2;
1168  AdjustBBOffsetsAfter(MBB, 2);
1169  HasFarJump = true;
1170  NumUBrFixed++;
1171
1172  DOUT << "  Changed B to long jump " << *MI;
1173
1174  return true;
1175}
1176
1177/// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1178/// far away to fit in its displacement field. It is converted to an inverse
1179/// conditional branch + an unconditional branch to the destination.
1180bool
1181ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1182  MachineInstr *MI = Br.MI;
1183  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1184
1185  // Add a unconditional branch to the destination and invert the branch
1186  // condition to jump over it:
1187  // blt L1
1188  // =>
1189  // bge L2
1190  // b   L1
1191  // L2:
1192  ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1193  CC = ARMCC::getOppositeCondition(CC);
1194  unsigned CCReg = MI->getOperand(2).getReg();
1195
1196  // If the branch is at the end of its MBB and that has a fall-through block,
1197  // direct the updated conditional branch to the fall-through block. Otherwise,
1198  // split the MBB before the next instruction.
1199  MachineBasicBlock *MBB = MI->getParent();
1200  MachineInstr *BMI = &MBB->back();
1201  bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1202
1203  NumCBrFixed++;
1204  if (BMI != MI) {
1205    if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1206        BMI->getOpcode() == Br.UncondBr) {
1207      // Last MI in the BB is a unconditional branch. Can we simply invert the
1208      // condition and swap destinations:
1209      // beq L1
1210      // b   L2
1211      // =>
1212      // bne L2
1213      // b   L1
1214      MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1215      if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1216        DOUT << "  Invert Bcc condition and swap its destination with " << *BMI;
1217        BMI->getOperand(0).setMBB(DestBB);
1218        MI->getOperand(0).setMBB(NewDest);
1219        MI->getOperand(1).setImm(CC);
1220        return true;
1221      }
1222    }
1223  }
1224
1225  if (NeedSplit) {
1226    SplitBlockBeforeInstr(MI);
1227    // No need for the branch to the next block. We're adding a unconditional
1228    // branch to the destination.
1229    int delta = TII->GetInstSizeInBytes(&MBB->back());
1230    BBSizes[MBB->getNumber()] -= delta;
1231    MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1232    AdjustBBOffsetsAfter(SplitBB, -delta);
1233    MBB->back().eraseFromParent();
1234    // BBOffsets[SplitBB] is wrong temporarily, fixed below
1235  }
1236  MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1237
1238  DOUT << "  Insert B to BB#" << DestBB->getNumber()
1239       << " also invert condition and change dest. to BB#"
1240       << NextBB->getNumber() << "\n";
1241
1242  // Insert a new conditional branch and a new unconditional branch.
1243  // Also update the ImmBranch as well as adding a new entry for the new branch.
1244  BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB)
1245    .addImm(CC).addReg(CCReg);
1246  Br.MI = &MBB->back();
1247  BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1248  BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
1249  BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1250  unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1251  ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1252
1253  // Remove the old conditional branch.  It may or may not still be in MBB.
1254  BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1255  MI->eraseFromParent();
1256
1257  // The net size change is an addition of one unconditional branch.
1258  int delta = TII->GetInstSizeInBytes(&MBB->back());
1259  AdjustBBOffsetsAfter(MBB, delta);
1260  return true;
1261}
1262
1263/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1264/// LR / restores LR to pc.
1265bool ARMConstantIslands::UndoLRSpillRestore() {
1266  bool MadeChange = false;
1267  for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1268    MachineInstr *MI = PushPopMIs[i];
1269    if (MI->getOpcode() == ARM::tPOP_RET &&
1270        MI->getOperand(0).getReg() == ARM::PC &&
1271        MI->getNumExplicitOperands() == 1) {
1272      BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
1273      MI->eraseFromParent();
1274      MadeChange = true;
1275    }
1276  }
1277  return MadeChange;
1278}
1279