MipsConstantIslandPass.cpp revision 50d3b27f431a213a53a0240849a8ce65dc46c8a5
1//===-- MipsConstantIslandPass.cpp - Emit Pc Relative loads----------------===//
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//
11// This pass is used to make Pc relative loads of constants.
12// For now, only Mips16 will use this.
13//
14// Loading constants inline is expensive on Mips16 and it's in general better
15// to place the constant nearby in code space and then it can be loaded with a
16// simple 16 bit load instruction.
17//
18// The constants can be not just numbers but addresses of functions and labels.
19// This can be particularly helpful in static relocation mode for embedded
20// non linux targets.
21//
22//
23
24#define DEBUG_TYPE "mips-constant-islands"
25
26#include "Mips.h"
27#include "MCTargetDesc/MipsBaseInfo.h"
28#include "MipsMachineFunction.h"
29#include "MipsTargetMachine.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/CodeGen/MachineBasicBlock.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/IR/Function.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/InstIterator.h"
39#include "llvm/Support/MathExtras.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetMachine.h"
43#include "llvm/Target/TargetRegisterInfo.h"
44#include "llvm/Support/Format.h"
45#include <algorithm>
46
47using namespace llvm;
48
49STATISTIC(NumCPEs,       "Number of constpool entries");
50STATISTIC(NumSplit,      "Number of uncond branches inserted");
51STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
52STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
53
54// FIXME: This option should be removed once it has received sufficient testing.
55static cl::opt<bool>
56AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
57          cl::desc("Align constant islands in code"));
58
59
60// Rather than do make check tests with huge amounts of code, we force
61// the test to use this amount.
62//
63static cl::opt<int> ConstantIslandsSmallOffset(
64  "mips-constant-islands-small-offset",
65  cl::init(0),
66  cl::desc("Make small offsets be this amount for testing purposes"),
67  cl::Hidden);
68
69//
70// For testing purposes we tell it to not use relaxed load forms so that it
71// will split blocks.
72//
73static cl::opt<bool> NoLoadRelaxation(
74  "mips-constant-islands-no-load-relaxation",
75  cl::init(false),
76  cl::desc("Don't relax loads to long loads - for testing purposes"),
77  cl::Hidden);
78
79
80namespace {
81
82
83  typedef MachineBasicBlock::iterator Iter;
84  typedef MachineBasicBlock::reverse_iterator ReverseIter;
85
86  /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
87  /// requires constant pool entries to be scattered among the instructions
88  /// inside a function.  To do this, it completely ignores the normal LLVM
89  /// constant pool; instead, it places constants wherever it feels like with
90  /// special instructions.
91  ///
92  /// The terminology used in this pass includes:
93  ///   Islands - Clumps of constants placed in the function.
94  ///   Water   - Potential places where an island could be formed.
95  ///   CPE     - A constant pool entry that has been placed somewhere, which
96  ///             tracks a list of users.
97
98  class MipsConstantIslands : public MachineFunctionPass {
99
100    /// BasicBlockInfo - Information about the offset and size of a single
101    /// basic block.
102    struct BasicBlockInfo {
103      /// Offset - Distance from the beginning of the function to the beginning
104      /// of this basic block.
105      ///
106      /// Offsets are computed assuming worst case padding before an aligned
107      /// block. This means that subtracting basic block offsets always gives a
108      /// conservative estimate of the real distance which may be smaller.
109      ///
110      /// Because worst case padding is used, the computed offset of an aligned
111      /// block may not actually be aligned.
112      unsigned Offset;
113
114      /// Size - Size of the basic block in bytes.  If the block contains
115      /// inline assembly, this is a worst case estimate.
116      ///
117      /// The size does not include any alignment padding whether from the
118      /// beginning of the block, or from an aligned jump table at the end.
119      unsigned Size;
120
121      // FIXME: ignore LogAlign for this patch
122      //
123      unsigned postOffset(unsigned LogAlign = 0) const {
124        unsigned PO = Offset + Size;
125        return PO;
126      }
127
128      BasicBlockInfo() : Offset(0), Size(0) {}
129
130    };
131
132    std::vector<BasicBlockInfo> BBInfo;
133
134    /// WaterList - A sorted list of basic blocks where islands could be placed
135    /// (i.e. blocks that don't fall through to the following block, due
136    /// to a return, unreachable, or unconditional branch).
137    std::vector<MachineBasicBlock*> WaterList;
138
139    /// NewWaterList - The subset of WaterList that was created since the
140    /// previous iteration by inserting unconditional branches.
141    SmallSet<MachineBasicBlock*, 4> NewWaterList;
142
143    typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
144
145    /// CPUser - One user of a constant pool, keeping the machine instruction
146    /// pointer, the constant pool being referenced, and the max displacement
147    /// allowed from the instruction to the CP.  The HighWaterMark records the
148    /// highest basic block where a new CPEntry can be placed.  To ensure this
149    /// pass terminates, the CP entries are initially placed at the end of the
150    /// function and then move monotonically to lower addresses.  The
151    /// exception to this rule is when the current CP entry for a particular
152    /// CPUser is out of range, but there is another CP entry for the same
153    /// constant value in range.  We want to use the existing in-range CP
154    /// entry, but if it later moves out of range, the search for new water
155    /// should resume where it left off.  The HighWaterMark is used to record
156    /// that point.
157    struct CPUser {
158      MachineInstr *MI;
159      MachineInstr *CPEMI;
160      MachineBasicBlock *HighWaterMark;
161    private:
162      unsigned MaxDisp;
163      unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
164                                // with different displacements
165      unsigned LongFormOpcode;
166    public:
167      bool NegOk;
168      CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
169             bool neg,
170             unsigned longformmaxdisp, unsigned longformopcode)
171        : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
172          LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
173          NegOk(neg){
174        HighWaterMark = CPEMI->getParent();
175      }
176      /// getMaxDisp - Returns the maximum displacement supported by MI.
177      unsigned getMaxDisp() const {
178        unsigned xMaxDisp = ConstantIslandsSmallOffset?
179                            ConstantIslandsSmallOffset: MaxDisp;
180        return xMaxDisp;
181      }
182      void setMaxDisp(unsigned val) {
183        MaxDisp = val;
184      }
185      unsigned getLongFormMaxDisp() const {
186        return LongFormMaxDisp;
187      }
188      unsigned getLongFormOpcode() const {
189          return LongFormOpcode;
190      }
191    };
192
193    /// CPUsers - Keep track of all of the machine instructions that use various
194    /// constant pools and their max displacement.
195    std::vector<CPUser> CPUsers;
196
197  /// CPEntry - One per constant pool entry, keeping the machine instruction
198  /// pointer, the constpool index, and the number of CPUser's which
199  /// reference this entry.
200  struct CPEntry {
201    MachineInstr *CPEMI;
202    unsigned CPI;
203    unsigned RefCount;
204    CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
205      : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
206  };
207
208  /// CPEntries - Keep track of all of the constant pool entry machine
209  /// instructions. For each original constpool index (i.e. those that
210  /// existed upon entry to this pass), it keeps a vector of entries.
211  /// Original elements are cloned as we go along; the clones are
212  /// put in the vector of the original element, but have distinct CPIs.
213  std::vector<std::vector<CPEntry> > CPEntries;
214
215  /// ImmBranch - One per immediate branch, keeping the machine instruction
216  /// pointer, conditional or unconditional, the max displacement,
217  /// and (if isCond is true) the corresponding unconditional branch
218  /// opcode.
219  struct ImmBranch {
220    MachineInstr *MI;
221    unsigned MaxDisp : 31;
222    bool isCond : 1;
223    int UncondBr;
224    ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
225      : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
226  };
227
228  /// ImmBranches - Keep track of all the immediate branch instructions.
229  ///
230  std::vector<ImmBranch> ImmBranches;
231
232  /// HasFarJump - True if any far jump instruction has been emitted during
233  /// the branch fix up pass.
234  bool HasFarJump;
235
236  const TargetMachine &TM;
237  bool IsPIC;
238  unsigned ABI;
239  const MipsSubtarget *STI;
240  const MipsInstrInfo *TII;
241  MipsFunctionInfo *MFI;
242  MachineFunction *MF;
243  MachineConstantPool *MCP;
244
245  unsigned PICLabelUId;
246  bool PrescannedForConstants;
247
248  void initPICLabelUId(unsigned UId) {
249    PICLabelUId = UId;
250  }
251
252
253  unsigned createPICLabelUId() {
254    return PICLabelUId++;
255  }
256
257  public:
258    static char ID;
259    MipsConstantIslands(TargetMachine &tm)
260      : MachineFunctionPass(ID), TM(tm),
261        IsPIC(TM.getRelocationModel() == Reloc::PIC_),
262        ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
263        STI(&TM.getSubtarget<MipsSubtarget>()), MF(0), MCP(0),
264        PrescannedForConstants(false){}
265
266    virtual const char *getPassName() const {
267      return "Mips Constant Islands";
268    }
269
270    bool runOnMachineFunction(MachineFunction &F);
271
272    void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
273    CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
274    unsigned getCPELogAlign(const MachineInstr *CPEMI);
275    void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
276    unsigned getOffsetOf(MachineInstr *MI) const;
277    unsigned getUserOffset(CPUser&) const;
278    void dumpBBs();
279    void verify();
280
281    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
282                         unsigned Disp, bool NegativeOK);
283    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
284                         const CPUser &U);
285
286    bool isLongFormOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
287                                const CPUser &U);
288
289    void computeBlockSize(MachineBasicBlock *MBB);
290    MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
291    void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
292    void adjustBBOffsetsAfter(MachineBasicBlock *BB);
293    bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
294    int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
295    int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
296    bool findAvailableWater(CPUser&U, unsigned UserOffset,
297                            water_iterator &WaterIter);
298    void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
299                        MachineBasicBlock *&NewMBB);
300    bool handleConstantPoolUser(unsigned CPUserIndex);
301    void removeDeadCPEMI(MachineInstr *CPEMI);
302    bool removeUnusedCPEntries();
303    bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
304                          MachineInstr *CPEMI, unsigned Disp, bool NegOk,
305                          bool DoDump = false);
306    bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
307                        CPUser &U, unsigned &Growth);
308    bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
309    bool fixupImmediateBr(ImmBranch &Br);
310    bool fixupConditionalBr(ImmBranch &Br);
311    bool fixupUnconditionalBr(ImmBranch &Br);
312
313    void prescanForConstants();
314
315  private:
316
317  };
318
319  char MipsConstantIslands::ID = 0;
320} // end of anonymous namespace
321
322
323bool MipsConstantIslands::isLongFormOffsetInRange
324  (unsigned UserOffset, unsigned TrialOffset,
325   const CPUser &U) {
326  return isOffsetInRange(UserOffset, TrialOffset,
327                         U.getLongFormMaxDisp(), U.NegOk);
328}
329
330bool MipsConstantIslands::isOffsetInRange
331  (unsigned UserOffset, unsigned TrialOffset,
332   const CPUser &U) {
333  return isOffsetInRange(UserOffset, TrialOffset,
334                         U.getMaxDisp(), U.NegOk);
335}
336/// print block size and offset information - debugging
337void MipsConstantIslands::dumpBBs() {
338  DEBUG({
339    for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
340      const BasicBlockInfo &BBI = BBInfo[J];
341      dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
342             << format(" size=%#x\n", BBInfo[J].Size);
343    }
344  });
345}
346/// createMipsLongBranchPass - Returns a pass that converts branches to long
347/// branches.
348FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
349  return new MipsConstantIslands(tm);
350}
351
352bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
353  // The intention is for this to be a mips16 only pass for now
354  // FIXME:
355  MF = &mf;
356  MCP = mf.getConstantPool();
357  DEBUG(dbgs() << "constant island machine function " << "\n");
358  if (!TM.getSubtarget<MipsSubtarget>().inMips16Mode() ||
359      !MipsSubtarget::useConstantIslands()) {
360    return false;
361  }
362  TII = (const MipsInstrInfo*)MF->getTarget().getInstrInfo();
363  MFI = MF->getInfo<MipsFunctionInfo>();
364  DEBUG(dbgs() << "constant island processing " << "\n");
365  //
366  // will need to make predermination if there is any constants we need to
367  // put in constant islands. TBD.
368  //
369  if (!PrescannedForConstants) prescanForConstants();
370
371  HasFarJump = false;
372  // This pass invalidates liveness information when it splits basic blocks.
373  MF->getRegInfo().invalidateLiveness();
374
375  // Renumber all of the machine basic blocks in the function, guaranteeing that
376  // the numbers agree with the position of the block in the function.
377  MF->RenumberBlocks();
378
379  bool MadeChange = false;
380
381  // Perform the initial placement of the constant pool entries.  To start with,
382  // we put them all at the end of the function.
383  std::vector<MachineInstr*> CPEMIs;
384  if (!MCP->isEmpty())
385    doInitialPlacement(CPEMIs);
386
387  /// The next UID to take is the first unused one.
388  initPICLabelUId(CPEMIs.size());
389
390  // Do the initial scan of the function, building up information about the
391  // sizes of each block, the location of all the water, and finding all of the
392  // constant pool users.
393  initializeFunctionInfo(CPEMIs);
394  CPEMIs.clear();
395  DEBUG(dumpBBs());
396
397  /// Remove dead constant pool entries.
398  MadeChange |= removeUnusedCPEntries();
399
400  // Iteratively place constant pool entries and fix up branches until there
401  // is no change.
402  unsigned NoCPIters = 0, NoBRIters = 0;
403  (void)NoBRIters;
404  while (true) {
405    DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
406    bool CPChange = false;
407    for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
408      CPChange |= handleConstantPoolUser(i);
409    if (CPChange && ++NoCPIters > 30)
410      report_fatal_error("Constant Island pass failed to converge!");
411    DEBUG(dumpBBs());
412
413    // Clear NewWaterList now.  If we split a block for branches, it should
414    // appear as "new water" for the next iteration of constant pool placement.
415    NewWaterList.clear();
416
417    DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
418    bool BRChange = false;
419#ifdef IN_PROGRESS
420    for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
421      BRChange |= fixupImmediateBr(ImmBranches[i]);
422    if (BRChange && ++NoBRIters > 30)
423      report_fatal_error("Branch Fix Up pass failed to converge!");
424    DEBUG(dumpBBs());
425#endif
426    if (!CPChange && !BRChange)
427      break;
428    MadeChange = true;
429  }
430
431  DEBUG(dbgs() << '\n'; dumpBBs());
432
433  BBInfo.clear();
434  WaterList.clear();
435  CPUsers.clear();
436  CPEntries.clear();
437  ImmBranches.clear();
438  return MadeChange;
439}
440
441/// doInitialPlacement - Perform the initial placement of the constant pool
442/// entries.  To start with, we put them all at the end of the function.
443void
444MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
445  // Create the basic block to hold the CPE's.
446  MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
447  MF->push_back(BB);
448
449
450  // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
451  unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
452
453  // Mark the basic block as required by the const-pool.
454  // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
455  BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
456
457  // The function needs to be as aligned as the basic blocks. The linker may
458  // move functions around based on their alignment.
459  MF->ensureAlignment(BB->getAlignment());
460
461  // Order the entries in BB by descending alignment.  That ensures correct
462  // alignment of all entries as long as BB is sufficiently aligned.  Keep
463  // track of the insertion point for each alignment.  We are going to bucket
464  // sort the entries as they are created.
465  SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
466
467  // Add all of the constants from the constant pool to the end block, use an
468  // identity mapping of CPI's to CPE's.
469  const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
470
471  const DataLayout &TD = *MF->getTarget().getDataLayout();
472  for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
473    unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
474    assert(Size >= 4 && "Too small constant pool entry");
475    unsigned Align = CPs[i].getAlignment();
476    assert(isPowerOf2_32(Align) && "Invalid alignment");
477    // Verify that all constant pool entries are a multiple of their alignment.
478    // If not, we would have to pad them out so that instructions stay aligned.
479    assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
480
481    // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
482    unsigned LogAlign = Log2_32(Align);
483    MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
484
485    MachineInstr *CPEMI =
486      BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
487        .addImm(i).addConstantPoolIndex(i).addImm(Size);
488
489    CPEMIs.push_back(CPEMI);
490
491    // Ensure that future entries with higher alignment get inserted before
492    // CPEMI. This is bucket sort with iterators.
493    for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
494      if (InsPoint[a] == InsAt)
495        InsPoint[a] = CPEMI;
496    // Add a new CPEntry, but no corresponding CPUser yet.
497    std::vector<CPEntry> CPEs;
498    CPEs.push_back(CPEntry(CPEMI, i));
499    CPEntries.push_back(CPEs);
500    ++NumCPEs;
501    DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
502                 << Size << ", align = " << Align <<'\n');
503  }
504  DEBUG(BB->dump());
505}
506
507/// BBHasFallthrough - Return true if the specified basic block can fallthrough
508/// into the block immediately after it.
509static bool BBHasFallthrough(MachineBasicBlock *MBB) {
510  // Get the next machine basic block in the function.
511  MachineFunction::iterator MBBI = MBB;
512  // Can't fall off end of function.
513  if (llvm::next(MBBI) == MBB->getParent()->end())
514    return false;
515
516  MachineBasicBlock *NextBB = llvm::next(MBBI);
517  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
518       E = MBB->succ_end(); I != E; ++I)
519    if (*I == NextBB)
520      return true;
521
522  return false;
523}
524
525/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
526/// look up the corresponding CPEntry.
527MipsConstantIslands::CPEntry
528*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
529                                        const MachineInstr *CPEMI) {
530  std::vector<CPEntry> &CPEs = CPEntries[CPI];
531  // Number of entries per constpool index should be small, just do a
532  // linear search.
533  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
534    if (CPEs[i].CPEMI == CPEMI)
535      return &CPEs[i];
536  }
537  return NULL;
538}
539
540/// getCPELogAlign - Returns the required alignment of the constant pool entry
541/// represented by CPEMI.  Alignment is measured in log2(bytes) units.
542unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
543  assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
544
545  // Everything is 4-byte aligned unless AlignConstantIslands is set.
546  if (!AlignConstantIslands)
547    return 2;
548
549  unsigned CPI = CPEMI->getOperand(1).getIndex();
550  assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
551  unsigned Align = MCP->getConstants()[CPI].getAlignment();
552  assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
553  return Log2_32(Align);
554}
555
556/// initializeFunctionInfo - Do the initial scan of the function, building up
557/// information about the sizes of each block, the location of all the water,
558/// and finding all of the constant pool users.
559void MipsConstantIslands::
560initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
561  BBInfo.clear();
562  BBInfo.resize(MF->getNumBlockIDs());
563
564  // First thing, compute the size of all basic blocks, and see if the function
565  // has any inline assembly in it. If so, we have to be conservative about
566  // alignment assumptions, as we don't know for sure the size of any
567  // instructions in the inline assembly.
568  for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
569    computeBlockSize(I);
570
571
572  // Compute block offsets.
573  adjustBBOffsetsAfter(MF->begin());
574
575  // Now go back through the instructions and build up our data structures.
576  for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
577       MBBI != E; ++MBBI) {
578    MachineBasicBlock &MBB = *MBBI;
579
580    // If this block doesn't fall through into the next MBB, then this is
581    // 'water' that a constant pool island could be placed.
582    if (!BBHasFallthrough(&MBB))
583      WaterList.push_back(&MBB);
584    for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
585         I != E; ++I) {
586      if (I->isDebugValue())
587        continue;
588
589      int Opc = I->getOpcode();
590#ifdef IN_PROGRESS
591      if (I->isBranch()) {
592        bool isCond = false;
593        unsigned Bits = 0;
594        unsigned Scale = 1;
595        int UOpc = Opc;
596        switch (Opc) {
597        default:
598          continue;  // Ignore other JT branches
599        }
600        // Record this immediate branch.
601        unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
602        ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
603      }
604#endif
605
606      if (Opc == Mips::CONSTPOOL_ENTRY)
607        continue;
608
609
610      // Scan the instructions for constant pool operands.
611      for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
612        if (I->getOperand(op).isCPI()) {
613
614          // We found one.  The addressing mode tells us the max displacement
615          // from the PC that this instruction permits.
616
617          // Basic size info comes from the TSFlags field.
618          unsigned Bits = 0;
619          unsigned Scale = 1;
620          bool NegOk = false;
621          unsigned LongFormBits = 0;
622          unsigned LongFormScale = 0;
623          unsigned LongFormOpcode = 0;
624          switch (Opc) {
625          default:
626            llvm_unreachable("Unknown addressing mode for CP reference!");
627          case Mips::LwRxPcTcp16:
628            Bits = 8;
629            Scale = 4;
630            LongFormOpcode = Mips::LwRxPcTcpX16;
631            LongFormBits = 16;
632            LongFormScale = 1;
633            break;
634          case Mips::LwRxPcTcpX16:
635            Bits = 16;
636            Scale = 1;
637            NegOk = true;
638            break;
639          }
640          // Remember that this is a user of a CP entry.
641          unsigned CPI = I->getOperand(op).getIndex();
642          MachineInstr *CPEMI = CPEMIs[CPI];
643          unsigned MaxOffs = ((1 << Bits)-1) * Scale;
644          unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
645          CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
646                                   LongFormMaxOffs, LongFormOpcode));
647
648          // Increment corresponding CPEntry reference count.
649          CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
650          assert(CPE && "Cannot find a corresponding CPEntry!");
651          CPE->RefCount++;
652
653          // Instructions can only use one CP entry, don't bother scanning the
654          // rest of the operands.
655          break;
656
657        }
658
659    }
660  }
661
662}
663
664/// computeBlockSize - Compute the size and some alignment information for MBB.
665/// This function updates BBInfo directly.
666void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
667  BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
668  BBI.Size = 0;
669
670  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
671       ++I)
672    BBI.Size += TII->GetInstSizeInBytes(I);
673
674}
675
676/// getOffsetOf - Return the current offset of the specified machine instruction
677/// from the start of the function.  This offset changes as stuff is moved
678/// around inside the function.
679unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
680  MachineBasicBlock *MBB = MI->getParent();
681
682  // The offset is composed of two things: the sum of the sizes of all MBB's
683  // before this instruction's block, and the offset from the start of the block
684  // it is in.
685  unsigned Offset = BBInfo[MBB->getNumber()].Offset;
686
687  // Sum instructions before MI in MBB.
688  for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
689    assert(I != MBB->end() && "Didn't find MI in its own basic block?");
690    Offset += TII->GetInstSizeInBytes(I);
691  }
692  return Offset;
693}
694
695/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
696/// ID.
697static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
698                              const MachineBasicBlock *RHS) {
699  return LHS->getNumber() < RHS->getNumber();
700}
701
702/// updateForInsertedWaterBlock - When a block is newly inserted into the
703/// machine function, it upsets all of the block numbers.  Renumber the blocks
704/// and update the arrays that parallel this numbering.
705void MipsConstantIslands::updateForInsertedWaterBlock
706  (MachineBasicBlock *NewBB) {
707  // Renumber the MBB's to keep them consecutive.
708  NewBB->getParent()->RenumberBlocks(NewBB);
709
710  // Insert an entry into BBInfo to align it properly with the (newly
711  // renumbered) block numbers.
712  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
713
714  // Next, update WaterList.  Specifically, we need to add NewMBB as having
715  // available water after it.
716  water_iterator IP =
717    std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
718                     CompareMBBNumbers);
719  WaterList.insert(IP, NewBB);
720}
721
722unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
723  return getOffsetOf(U.MI);
724}
725
726/// Split the basic block containing MI into two blocks, which are joined by
727/// an unconditional branch.  Update data structures and renumber blocks to
728/// account for this change and returns the newly created block.
729MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
730  (MachineInstr *MI) {
731  MachineBasicBlock *OrigBB = MI->getParent();
732
733  // Create a new MBB for the code after the OrigBB.
734  MachineBasicBlock *NewBB =
735    MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
736  MachineFunction::iterator MBBI = OrigBB; ++MBBI;
737  MF->insert(MBBI, NewBB);
738
739  // Splice the instructions starting with MI over to NewBB.
740  NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
741
742  // Add an unconditional branch from OrigBB to NewBB.
743  // Note the new unconditional branch is not being recorded.
744  // There doesn't seem to be meaningful DebugInfo available; this doesn't
745  // correspond to anything in the source.
746  BuildMI(OrigBB, DebugLoc(), TII->get(Mips::BimmX16)).addMBB(NewBB);
747  ++NumSplit;
748
749  // Update the CFG.  All succs of OrigBB are now succs of NewBB.
750  NewBB->transferSuccessors(OrigBB);
751
752  // OrigBB branches to NewBB.
753  OrigBB->addSuccessor(NewBB);
754
755  // Update internal data structures to account for the newly inserted MBB.
756  // This is almost the same as updateForInsertedWaterBlock, except that
757  // the Water goes after OrigBB, not NewBB.
758  MF->RenumberBlocks(NewBB);
759
760  // Insert an entry into BBInfo to align it properly with the (newly
761  // renumbered) block numbers.
762  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
763
764  // Next, update WaterList.  Specifically, we need to add OrigMBB as having
765  // available water after it (but not if it's already there, which happens
766  // when splitting before a conditional branch that is followed by an
767  // unconditional branch - in that case we want to insert NewBB).
768  water_iterator IP =
769    std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
770                     CompareMBBNumbers);
771  MachineBasicBlock* WaterBB = *IP;
772  if (WaterBB == OrigBB)
773    WaterList.insert(llvm::next(IP), NewBB);
774  else
775    WaterList.insert(IP, OrigBB);
776  NewWaterList.insert(OrigBB);
777
778  // Figure out how large the OrigBB is.  As the first half of the original
779  // block, it cannot contain a tablejump.  The size includes
780  // the new jump we added.  (It should be possible to do this without
781  // recounting everything, but it's very confusing, and this is rarely
782  // executed.)
783  computeBlockSize(OrigBB);
784
785  // Figure out how large the NewMBB is.  As the second half of the original
786  // block, it may contain a tablejump.
787  computeBlockSize(NewBB);
788
789  // All BBOffsets following these blocks must be modified.
790  adjustBBOffsetsAfter(OrigBB);
791
792  return NewBB;
793}
794
795
796
797/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
798/// reference) is within MaxDisp of TrialOffset (a proposed location of a
799/// constant pool entry).
800bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
801                                         unsigned TrialOffset, unsigned MaxDisp,
802                                         bool NegativeOK) {
803  if (UserOffset <= TrialOffset) {
804    // User before the Trial.
805    if (TrialOffset - UserOffset <= MaxDisp)
806      return true;
807  } else if (NegativeOK) {
808    if (UserOffset - TrialOffset <= MaxDisp)
809      return true;
810  }
811  return false;
812}
813
814/// isWaterInRange - Returns true if a CPE placed after the specified
815/// Water (a basic block) will be in range for the specific MI.
816///
817/// Compute how much the function will grow by inserting a CPE after Water.
818bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
819                                        MachineBasicBlock* Water, CPUser &U,
820                                        unsigned &Growth) {
821  unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
822  unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
823  unsigned NextBlockOffset, NextBlockAlignment;
824  MachineFunction::const_iterator NextBlock = Water;
825  if (++NextBlock == MF->end()) {
826    NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
827    NextBlockAlignment = 0;
828  } else {
829    NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
830    NextBlockAlignment = NextBlock->getAlignment();
831  }
832  unsigned Size = U.CPEMI->getOperand(2).getImm();
833  unsigned CPEEnd = CPEOffset + Size;
834
835  // The CPE may be able to hide in the alignment padding before the next
836  // block. It may also cause more padding to be required if it is more aligned
837  // that the next block.
838  if (CPEEnd > NextBlockOffset) {
839    Growth = CPEEnd - NextBlockOffset;
840    // Compute the padding that would go at the end of the CPE to align the next
841    // block.
842    Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
843
844    // If the CPE is to be inserted before the instruction, that will raise
845    // the offset of the instruction. Also account for unknown alignment padding
846    // in blocks between CPE and the user.
847    if (CPEOffset < UserOffset)
848      UserOffset += Growth;
849  } else
850    // CPE fits in existing padding.
851    Growth = 0;
852
853  return isOffsetInRange(UserOffset, CPEOffset, U);
854}
855
856/// isCPEntryInRange - Returns true if the distance between specific MI and
857/// specific ConstPool entry instruction can fit in MI's displacement field.
858bool MipsConstantIslands::isCPEntryInRange
859  (MachineInstr *MI, unsigned UserOffset,
860   MachineInstr *CPEMI, unsigned MaxDisp,
861   bool NegOk, bool DoDump) {
862  unsigned CPEOffset  = getOffsetOf(CPEMI);
863
864  if (DoDump) {
865    DEBUG({
866      unsigned Block = MI->getParent()->getNumber();
867      const BasicBlockInfo &BBI = BBInfo[Block];
868      dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
869             << " max delta=" << MaxDisp
870             << format(" insn address=%#x", UserOffset)
871             << " in BB#" << Block << ": "
872             << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
873             << format("CPE address=%#x offset=%+d: ", CPEOffset,
874                       int(CPEOffset-UserOffset));
875    });
876  }
877
878  return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
879}
880
881#ifndef NDEBUG
882/// BBIsJumpedOver - Return true of the specified basic block's only predecessor
883/// unconditionally branches to its only successor.
884static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
885  if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
886    return false;
887  MachineBasicBlock *Succ = *MBB->succ_begin();
888  MachineBasicBlock *Pred = *MBB->pred_begin();
889  MachineInstr *PredMI = &Pred->back();
890  if (PredMI->getOpcode() == Mips::BimmX16)
891    return PredMI->getOperand(0).getMBB() == Succ;
892  return false;
893}
894#endif
895
896void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
897  unsigned BBNum = BB->getNumber();
898  for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
899    // Get the offset and known bits at the end of the layout predecessor.
900    // Include the alignment of the current block.
901    unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
902    BBInfo[i].Offset = Offset;
903  }
904}
905
906/// decrementCPEReferenceCount - find the constant pool entry with index CPI
907/// and instruction CPEMI, and decrement its refcount.  If the refcount
908/// becomes 0 remove the entry and instruction.  Returns true if we removed
909/// the entry, false if we didn't.
910
911bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
912                                                    MachineInstr *CPEMI) {
913  // Find the old entry. Eliminate it if it is no longer used.
914  CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
915  assert(CPE && "Unexpected!");
916  if (--CPE->RefCount == 0) {
917    removeDeadCPEMI(CPEMI);
918    CPE->CPEMI = NULL;
919    --NumCPEs;
920    return true;
921  }
922  return false;
923}
924
925/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
926/// if not, see if an in-range clone of the CPE is in range, and if so,
927/// change the data structures so the user references the clone.  Returns:
928/// 0 = no existing entry found
929/// 1 = entry found, and there were no code insertions or deletions
930/// 2 = entry found, and there were code insertions or deletions
931int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
932{
933  MachineInstr *UserMI = U.MI;
934  MachineInstr *CPEMI  = U.CPEMI;
935
936  // Check to see if the CPE is already in-range.
937  if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
938                       true)) {
939    DEBUG(dbgs() << "In range\n");
940    return 1;
941  }
942
943  // No.  Look for previously created clones of the CPE that are in range.
944  unsigned CPI = CPEMI->getOperand(1).getIndex();
945  std::vector<CPEntry> &CPEs = CPEntries[CPI];
946  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
947    // We already tried this one
948    if (CPEs[i].CPEMI == CPEMI)
949      continue;
950    // Removing CPEs can leave empty entries, skip
951    if (CPEs[i].CPEMI == NULL)
952      continue;
953    if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
954                     U.NegOk)) {
955      DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
956                   << CPEs[i].CPI << "\n");
957      // Point the CPUser node to the replacement
958      U.CPEMI = CPEs[i].CPEMI;
959      // Change the CPI in the instruction operand to refer to the clone.
960      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
961        if (UserMI->getOperand(j).isCPI()) {
962          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
963          break;
964        }
965      // Adjust the refcount of the clone...
966      CPEs[i].RefCount++;
967      // ...and the original.  If we didn't remove the old entry, none of the
968      // addresses changed, so we don't need another pass.
969      return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
970    }
971  }
972  return 0;
973}
974
975/// LookForCPEntryInRange - see if the currently referenced CPE is in range;
976/// This version checks if the longer form of the instruction can be used to
977/// to satisfy things.
978/// if not, see if an in-range clone of the CPE is in range, and if so,
979/// change the data structures so the user references the clone.  Returns:
980/// 0 = no existing entry found
981/// 1 = entry found, and there were no code insertions or deletions
982/// 2 = entry found, and there were code insertions or deletions
983int MipsConstantIslands::findLongFormInRangeCPEntry
984  (CPUser& U, unsigned UserOffset)
985{
986  MachineInstr *UserMI = U.MI;
987  MachineInstr *CPEMI  = U.CPEMI;
988
989  // Check to see if the CPE is already in-range.
990  if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
991                       U.getLongFormMaxDisp(), U.NegOk,
992                       true)) {
993    DEBUG(dbgs() << "In range\n");
994    UserMI->setDesc(TII->get(U.getLongFormOpcode()));
995    U.setMaxDisp(U.getLongFormMaxDisp());
996    return 2;  // instruction is longer length now
997  }
998
999  // No.  Look for previously created clones of the CPE that are in range.
1000  unsigned CPI = CPEMI->getOperand(1).getIndex();
1001  std::vector<CPEntry> &CPEs = CPEntries[CPI];
1002  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1003    // We already tried this one
1004    if (CPEs[i].CPEMI == CPEMI)
1005      continue;
1006    // Removing CPEs can leave empty entries, skip
1007    if (CPEs[i].CPEMI == NULL)
1008      continue;
1009    if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1010                         U.getLongFormMaxDisp(), U.NegOk)) {
1011      DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1012                   << CPEs[i].CPI << "\n");
1013      // Point the CPUser node to the replacement
1014      U.CPEMI = CPEs[i].CPEMI;
1015      // Change the CPI in the instruction operand to refer to the clone.
1016      for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1017        if (UserMI->getOperand(j).isCPI()) {
1018          UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1019          break;
1020        }
1021      // Adjust the refcount of the clone...
1022      CPEs[i].RefCount++;
1023      // ...and the original.  If we didn't remove the old entry, none of the
1024      // addresses changed, so we don't need another pass.
1025      return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1026    }
1027  }
1028  return 0;
1029}
1030
1031/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1032/// the specific unconditional branch instruction.
1033static inline unsigned getUnconditionalBrDisp(int Opc) {
1034  switch (Opc) {
1035  case Mips::BimmX16:
1036    return ((1<<16)-1)*2;
1037  default:
1038    break;
1039  }
1040  return ((1<<16)-1)*2;
1041}
1042
1043/// findAvailableWater - Look for an existing entry in the WaterList in which
1044/// we can place the CPE referenced from U so it's within range of U's MI.
1045/// Returns true if found, false if not.  If it returns true, WaterIter
1046/// is set to the WaterList entry.
1047/// To ensure that this pass
1048/// terminates, the CPE location for a particular CPUser is only allowed to
1049/// move to a lower address, so search backward from the end of the list and
1050/// prefer the first water that is in range.
1051bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1052                                      water_iterator &WaterIter) {
1053  if (WaterList.empty())
1054    return false;
1055
1056  unsigned BestGrowth = ~0u;
1057  for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1058       --IP) {
1059    MachineBasicBlock* WaterBB = *IP;
1060    // Check if water is in range and is either at a lower address than the
1061    // current "high water mark" or a new water block that was created since
1062    // the previous iteration by inserting an unconditional branch.  In the
1063    // latter case, we want to allow resetting the high water mark back to
1064    // this new water since we haven't seen it before.  Inserting branches
1065    // should be relatively uncommon and when it does happen, we want to be
1066    // sure to take advantage of it for all the CPEs near that block, so that
1067    // we don't insert more branches than necessary.
1068    unsigned Growth;
1069    if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1070        (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1071         NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1072      // This is the least amount of required padding seen so far.
1073      BestGrowth = Growth;
1074      WaterIter = IP;
1075      DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1076                   << " Growth=" << Growth << '\n');
1077
1078      // Keep looking unless it is perfect.
1079      if (BestGrowth == 0)
1080        return true;
1081    }
1082    if (IP == B)
1083      break;
1084  }
1085  return BestGrowth != ~0u;
1086}
1087
1088/// createNewWater - No existing WaterList entry will work for
1089/// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1090/// block is used if in range, and the conditional branch munged so control
1091/// flow is correct.  Otherwise the block is split to create a hole with an
1092/// unconditional branch around it.  In either case NewMBB is set to a
1093/// block following which the new island can be inserted (the WaterList
1094/// is not adjusted).
1095void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1096                                        unsigned UserOffset,
1097                                        MachineBasicBlock *&NewMBB) {
1098  CPUser &U = CPUsers[CPUserIndex];
1099  MachineInstr *UserMI = U.MI;
1100  MachineInstr *CPEMI  = U.CPEMI;
1101  unsigned CPELogAlign = getCPELogAlign(CPEMI);
1102  MachineBasicBlock *UserMBB = UserMI->getParent();
1103  const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1104
1105  // If the block does not end in an unconditional branch already, and if the
1106  // end of the block is within range, make new water there.
1107  if (BBHasFallthrough(UserMBB)) {
1108    // Size of branch to insert.
1109    unsigned Delta = 2;
1110    // Compute the offset where the CPE will begin.
1111    unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1112
1113    if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1114      DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1115            << format(", expected CPE offset %#x\n", CPEOffset));
1116      NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1117      // Add an unconditional branch from UserMBB to fallthrough block.  Record
1118      // it for branch lengthening; this new branch will not get out of range,
1119      // but if the preceding conditional branch is out of range, the targets
1120      // will be exchanged, and the altered branch may be out of range, so the
1121      // machinery has to know about it.
1122      int UncondBr = Mips::BimmX16;
1123      BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1124      unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1125      ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1126                                      MaxDisp, false, UncondBr));
1127      BBInfo[UserMBB->getNumber()].Size += Delta;
1128      adjustBBOffsetsAfter(UserMBB);
1129      return;
1130    }
1131  }
1132
1133  // What a big block.  Find a place within the block to split it.
1134
1135  // Try to split the block so it's fully aligned.  Compute the latest split
1136  // point where we can add a 4-byte branch instruction, and then align to
1137  // LogAlign which is the largest possible alignment in the function.
1138  unsigned LogAlign = MF->getAlignment();
1139  assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1140  unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1141  DEBUG(dbgs() << format("Split in middle of big block before %#x",
1142                         BaseInsertOffset));
1143
1144  // The 4 in the following is for the unconditional branch we'll be inserting
1145  // Alignment of the island is handled
1146  // inside isOffsetInRange.
1147  BaseInsertOffset -= 4;
1148
1149  DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1150               << " la=" << LogAlign << '\n');
1151
1152  // This could point off the end of the block if we've already got constant
1153  // pool entries following this block; only the last one is in the water list.
1154  // Back past any possible branches (allow for a conditional and a maximally
1155  // long unconditional).
1156  if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1157    BaseInsertOffset = UserBBI.postOffset() - 8;
1158    DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1159  }
1160  unsigned EndInsertOffset = BaseInsertOffset + 4 +
1161    CPEMI->getOperand(2).getImm();
1162  MachineBasicBlock::iterator MI = UserMI;
1163  ++MI;
1164  unsigned CPUIndex = CPUserIndex+1;
1165  unsigned NumCPUsers = CPUsers.size();
1166  //MachineInstr *LastIT = 0;
1167  for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1168       Offset < BaseInsertOffset;
1169       Offset += TII->GetInstSizeInBytes(MI),
1170       MI = llvm::next(MI)) {
1171    assert(MI != UserMBB->end() && "Fell off end of block");
1172    if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1173      CPUser &U = CPUsers[CPUIndex];
1174      if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1175        // Shift intertion point by one unit of alignment so it is within reach.
1176        BaseInsertOffset -= 1u << LogAlign;
1177        EndInsertOffset  -= 1u << LogAlign;
1178      }
1179      // This is overly conservative, as we don't account for CPEMIs being
1180      // reused within the block, but it doesn't matter much.  Also assume CPEs
1181      // are added in order with alignment padding.  We may eventually be able
1182      // to pack the aligned CPEs better.
1183      EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1184      CPUIndex++;
1185    }
1186  }
1187
1188  --MI;
1189  NewMBB = splitBlockBeforeInstr(MI);
1190}
1191
1192/// handleConstantPoolUser - Analyze the specified user, checking to see if it
1193/// is out-of-range.  If so, pick up the constant pool value and move it some
1194/// place in-range.  Return true if we changed any addresses (thus must run
1195/// another pass of branch lengthening), false otherwise.
1196bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1197  CPUser &U = CPUsers[CPUserIndex];
1198  MachineInstr *UserMI = U.MI;
1199  MachineInstr *CPEMI  = U.CPEMI;
1200  unsigned CPI = CPEMI->getOperand(1).getIndex();
1201  unsigned Size = CPEMI->getOperand(2).getImm();
1202  // Compute this only once, it's expensive.
1203  unsigned UserOffset = getUserOffset(U);
1204
1205  // See if the current entry is within range, or there is a clone of it
1206  // in range.
1207  int result = findInRangeCPEntry(U, UserOffset);
1208  if (result==1) return false;
1209  else if (result==2) return true;
1210
1211
1212  // Look for water where we can place this CPE.
1213  MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1214  MachineBasicBlock *NewMBB;
1215  water_iterator IP;
1216  if (findAvailableWater(U, UserOffset, IP)) {
1217    DEBUG(dbgs() << "Found water in range\n");
1218    MachineBasicBlock *WaterBB = *IP;
1219
1220    // If the original WaterList entry was "new water" on this iteration,
1221    // propagate that to the new island.  This is just keeping NewWaterList
1222    // updated to match the WaterList, which will be updated below.
1223    if (NewWaterList.erase(WaterBB))
1224      NewWaterList.insert(NewIsland);
1225
1226    // The new CPE goes before the following block (NewMBB).
1227    NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1228
1229  } else {
1230    // No water found.
1231    // we first see if a longer form of the instrucion could have reached
1232    // the constant. in that case we won't bother to split
1233    if (!NoLoadRelaxation) {
1234      result = findLongFormInRangeCPEntry(U, UserOffset);
1235      if (result != 0) return true;
1236    }
1237    DEBUG(dbgs() << "No water found\n");
1238    createNewWater(CPUserIndex, UserOffset, NewMBB);
1239
1240    // splitBlockBeforeInstr adds to WaterList, which is important when it is
1241    // called while handling branches so that the water will be seen on the
1242    // next iteration for constant pools, but in this context, we don't want
1243    // it.  Check for this so it will be removed from the WaterList.
1244    // Also remove any entry from NewWaterList.
1245    MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1246    IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1247    if (IP != WaterList.end())
1248      NewWaterList.erase(WaterBB);
1249
1250    // We are adding new water.  Update NewWaterList.
1251    NewWaterList.insert(NewIsland);
1252  }
1253
1254  // Remove the original WaterList entry; we want subsequent insertions in
1255  // this vicinity to go after the one we're about to insert.  This
1256  // considerably reduces the number of times we have to move the same CPE
1257  // more than once and is also important to ensure the algorithm terminates.
1258  if (IP != WaterList.end())
1259    WaterList.erase(IP);
1260
1261  // Okay, we know we can put an island before NewMBB now, do it!
1262  MF->insert(NewMBB, NewIsland);
1263
1264  // Update internal data structures to account for the newly inserted MBB.
1265  updateForInsertedWaterBlock(NewIsland);
1266
1267  // Decrement the old entry, and remove it if refcount becomes 0.
1268  decrementCPEReferenceCount(CPI, CPEMI);
1269
1270  // Now that we have an island to add the CPE to, clone the original CPE and
1271  // add it to the island.
1272  U.HighWaterMark = NewIsland;
1273  U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1274                .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1275  CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1276  ++NumCPEs;
1277
1278  // Mark the basic block as aligned as required by the const-pool entry.
1279  NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1280
1281  // Increase the size of the island block to account for the new entry.
1282  BBInfo[NewIsland->getNumber()].Size += Size;
1283  adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1284
1285  // No existing clone of this CPE is within range.
1286  // We will be generating a new clone.  Get a UID for it.
1287  unsigned ID = createPICLabelUId();
1288
1289  // Finally, change the CPI in the instruction operand to be ID.
1290  for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1291    if (UserMI->getOperand(i).isCPI()) {
1292      UserMI->getOperand(i).setIndex(ID);
1293      break;
1294    }
1295
1296  DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1297        << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1298
1299  return true;
1300}
1301
1302/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1303/// sizes and offsets of impacted basic blocks.
1304void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1305  MachineBasicBlock *CPEBB = CPEMI->getParent();
1306  unsigned Size = CPEMI->getOperand(2).getImm();
1307  CPEMI->eraseFromParent();
1308  BBInfo[CPEBB->getNumber()].Size -= Size;
1309  // All succeeding offsets have the current size value added in, fix this.
1310  if (CPEBB->empty()) {
1311    BBInfo[CPEBB->getNumber()].Size = 0;
1312
1313    // This block no longer needs to be aligned.
1314    CPEBB->setAlignment(0);
1315  } else
1316    // Entries are sorted by descending alignment, so realign from the front.
1317    CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1318
1319  adjustBBOffsetsAfter(CPEBB);
1320  // An island has only one predecessor BB and one successor BB. Check if
1321  // this BB's predecessor jumps directly to this BB's successor. This
1322  // shouldn't happen currently.
1323  assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1324  // FIXME: remove the empty blocks after all the work is done?
1325}
1326
1327/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1328/// are zero.
1329bool MipsConstantIslands::removeUnusedCPEntries() {
1330  unsigned MadeChange = false;
1331  for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1332      std::vector<CPEntry> &CPEs = CPEntries[i];
1333      for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1334        if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1335          removeDeadCPEMI(CPEs[j].CPEMI);
1336          CPEs[j].CPEMI = NULL;
1337          MadeChange = true;
1338        }
1339      }
1340  }
1341  return MadeChange;
1342}
1343
1344/// isBBInRange - Returns true if the distance between specific MI and
1345/// specific BB can fit in MI's displacement field.
1346bool MipsConstantIslands::isBBInRange
1347  (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1348
1349unsigned PCAdj = 4;
1350
1351  unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
1352  unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1353
1354  DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1355               << " from BB#" << MI->getParent()->getNumber()
1356               << " max delta=" << MaxDisp
1357               << " from " << getOffsetOf(MI) << " to " << DestOffset
1358               << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1359
1360  if (BrOffset <= DestOffset) {
1361    // Branch before the Dest.
1362    if (DestOffset-BrOffset <= MaxDisp)
1363      return true;
1364  } else {
1365    if (BrOffset-DestOffset <= MaxDisp)
1366      return true;
1367  }
1368  return false;
1369}
1370
1371/// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1372/// away to fit in its displacement field.
1373bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1374  MachineInstr *MI = Br.MI;
1375  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1376
1377  // Check to see if the DestBB is already in-range.
1378  if (isBBInRange(MI, DestBB, Br.MaxDisp))
1379    return false;
1380
1381  if (!Br.isCond)
1382    return fixupUnconditionalBr(Br);
1383  return fixupConditionalBr(Br);
1384}
1385
1386/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1387/// too far away to fit in its displacement field. If the LR register has been
1388/// spilled in the epilogue, then we can use BL to implement a far jump.
1389/// Otherwise, add an intermediate branch instruction to a branch.
1390bool
1391MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1392  MachineInstr *MI = Br.MI;
1393  MachineBasicBlock *MBB = MI->getParent();
1394  // Use BL to implement far jump.
1395  Br.MaxDisp = ((1 << 16)-1) * 2;
1396  MI->setDesc(TII->get(Mips::BimmX16));
1397  BBInfo[MBB->getNumber()].Size += 2;
1398  adjustBBOffsetsAfter(MBB);
1399  HasFarJump = true;
1400  ++NumUBrFixed;
1401
1402  DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1403
1404  return true;
1405}
1406
1407/// fixupConditionalBr - Fix up a conditional branch whose destination is too
1408/// far away to fit in its displacement field. It is converted to an inverse
1409/// conditional branch + an unconditional branch to the destination.
1410bool
1411MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1412  MachineInstr *MI = Br.MI;
1413  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1414
1415  // Add an unconditional branch to the destination and invert the branch
1416  // condition to jump over it:
1417  // blt L1
1418  // =>
1419  // bge L2
1420  // b   L1
1421  // L2:
1422  unsigned CCReg = 0;  // FIXME
1423  unsigned CC=0; //FIXME
1424
1425  // If the branch is at the end of its MBB and that has a fall-through block,
1426  // direct the updated conditional branch to the fall-through block. Otherwise,
1427  // split the MBB before the next instruction.
1428  MachineBasicBlock *MBB = MI->getParent();
1429  MachineInstr *BMI = &MBB->back();
1430  bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1431
1432  ++NumCBrFixed;
1433  if (BMI != MI) {
1434    if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1435        BMI->getOpcode() == Br.UncondBr) {
1436      // Last MI in the BB is an unconditional branch. Can we simply invert the
1437      // condition and swap destinations:
1438      // beq L1
1439      // b   L2
1440      // =>
1441      // bne L2
1442      // b   L1
1443      MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1444      if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1445        DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
1446                     << *BMI);
1447        BMI->getOperand(0).setMBB(DestBB);
1448        MI->getOperand(0).setMBB(NewDest);
1449        return true;
1450      }
1451    }
1452  }
1453
1454  if (NeedSplit) {
1455    splitBlockBeforeInstr(MI);
1456    // No need for the branch to the next block. We're adding an unconditional
1457    // branch to the destination.
1458    int delta = TII->GetInstSizeInBytes(&MBB->back());
1459    BBInfo[MBB->getNumber()].Size -= delta;
1460    MBB->back().eraseFromParent();
1461    // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1462  }
1463  MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1464
1465  DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
1466               << " also invert condition and change dest. to BB#"
1467               << NextBB->getNumber() << "\n");
1468
1469  // Insert a new conditional branch and a new unconditional branch.
1470  // Also update the ImmBranch as well as adding a new entry for the new branch.
1471  BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1472    .addMBB(NextBB).addImm(CC).addReg(CCReg);
1473  Br.MI = &MBB->back();
1474  BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1475  BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1476  BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1477  unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1478  ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1479
1480  // Remove the old conditional branch.  It may or may not still be in MBB.
1481  BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1482  MI->eraseFromParent();
1483  adjustBBOffsetsAfter(MBB);
1484  return true;
1485}
1486
1487
1488void MipsConstantIslands::prescanForConstants() {
1489  unsigned J = 0;
1490  (void)J;
1491  PrescannedForConstants = true;
1492  for (MachineFunction::iterator B =
1493         MF->begin(), E = MF->end(); B != E; ++B) {
1494    for (MachineBasicBlock::instr_iterator I =
1495        B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1496      switch(I->getDesc().getOpcode()) {
1497        case Mips::LwConstant32: {
1498          DEBUG(dbgs() << "constant island constant " << *I << "\n");
1499          J = I->getNumOperands();
1500          DEBUG(dbgs() << "num operands " << J  << "\n");
1501          MachineOperand& Literal = I->getOperand(1);
1502          if (Literal.isImm()) {
1503            int64_t V = Literal.getImm();
1504            DEBUG(dbgs() << "literal " << V  << "\n");
1505            Type *Int32Ty =
1506              Type::getInt32Ty(MF->getFunction()->getContext());
1507            const Constant *C = ConstantInt::get(Int32Ty, V);
1508            unsigned index = MCP->getConstantPoolIndex(C, 4);
1509            I->getOperand(2).ChangeToImmediate(index);
1510            DEBUG(dbgs() << "constant island constant " << *I << "\n");
1511            I->setDesc(TII->get(Mips::LwRxPcTcp16));
1512            I->RemoveOperand(1);
1513            I->RemoveOperand(1);
1514            I->addOperand(MachineOperand::CreateCPI(index, 0));
1515            I->addOperand(MachineOperand::CreateImm(4));
1516          }
1517          break;
1518        }
1519        default:
1520          break;
1521      }
1522    }
1523  }
1524}
1525
1526