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