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