Fix definition for Mips16 pc relative load word instructions.
[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 "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
47 using namespace llvm;
48
49 STATISTIC(NumCPEs,       "Number of constpool entries");
50 STATISTIC(NumSplit,      "Number of uncond branches inserted");
51 STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
52 STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
53
54 // FIXME: This option should be removed once it has received sufficient testing.
55 static cl::opt<bool>
56 AlignConstantIslands("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 //
63 static cl::opt<int> ConstantIslandsSmallOffset(
64   "mips-constant-islands-small-offset",
65   cl::init(0),
66   cl::desc("Make small offsets be this amount for testing purposes"),
67   cl::Hidden);
68
69
70 namespace {
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
310 bool MipsConstantIslands::isLongFormOffsetInRange
311   (unsigned UserOffset, unsigned TrialOffset,
312    const CPUser &U) {
313   return isOffsetInRange(UserOffset, TrialOffset,
314                          U.getLongFormMaxDisp(), U.NegOk);
315 }
316
317 bool 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
324 void 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.
335 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
336   return new MipsConstantIslands(tm);
337 }
338
339 bool 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.
430 void
431 MipsConstantIslands::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.
496 static 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.
514 MipsConstantIslands::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.
529 unsigned 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.
546 void MipsConstantIslands::
547 initializeFunctionInfo(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       if (I->isBranch()) {
578         bool isCond = false;
579         unsigned Bits = 0;
580         unsigned Scale = 1;
581         int UOpc = Opc;
582
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       }
592
593
594       if (Opc == Mips::CONSTPOOL_ENTRY)
595         continue;
596
597
598       // Scan the instructions for constant pool operands.
599       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
600         if (I->getOperand(op).isCPI()) {
601
602           // We found one.  The addressing mode tells us the max displacement
603           // from the PC that this instruction permits.
604
605           // Basic size info comes from the TSFlags field.
606           unsigned Bits = 0;
607           unsigned Scale = 1;
608           bool NegOk = false;
609           unsigned LongFormBits = 0;
610           unsigned LongFormScale = 0;
611           unsigned LongFormOpcode = 0;
612           switch (Opc) {
613           default:
614             llvm_unreachable("Unknown addressing mode for CP reference!");
615           case Mips::LwRxPcTcp16:
616             Bits = 8;
617             Scale = 4;
618             LongFormOpcode = Mips::LwRxPcTcpX16;
619             break;
620           case Mips::LwRxPcTcpX16:
621             Bits = 16;
622             Scale = 1;
623             NegOk = true;
624             break;
625           }
626           // Remember that this is a user of a CP entry.
627           unsigned CPI = I->getOperand(op).getIndex();
628           MachineInstr *CPEMI = CPEMIs[CPI];
629           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
630           unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
631           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
632                                    LongFormMaxOffs, LongFormOpcode));
633
634           // Increment corresponding CPEntry reference count.
635           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
636           assert(CPE && "Cannot find a corresponding CPEntry!");
637           CPE->RefCount++;
638
639           // Instructions can only use one CP entry, don't bother scanning the
640           // rest of the operands.
641           break;
642
643         }
644
645     }
646   }
647
648 }
649
650 /// computeBlockSize - Compute the size and some alignment information for MBB.
651 /// This function updates BBInfo directly.
652 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
653   BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
654   BBI.Size = 0;
655
656   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
657        ++I)
658     BBI.Size += TII->GetInstSizeInBytes(I);
659
660 }
661
662 /// getOffsetOf - Return the current offset of the specified machine instruction
663 /// from the start of the function.  This offset changes as stuff is moved
664 /// around inside the function.
665 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
666   MachineBasicBlock *MBB = MI->getParent();
667
668   // The offset is composed of two things: the sum of the sizes of all MBB's
669   // before this instruction's block, and the offset from the start of the block
670   // it is in.
671   unsigned Offset = BBInfo[MBB->getNumber()].Offset;
672
673   // Sum instructions before MI in MBB.
674   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
675     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
676     Offset += TII->GetInstSizeInBytes(I);
677   }
678   return Offset;
679 }
680
681 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
682 /// ID.
683 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
684                               const MachineBasicBlock *RHS) {
685   return LHS->getNumber() < RHS->getNumber();
686 }
687
688 /// updateForInsertedWaterBlock - When a block is newly inserted into the
689 /// machine function, it upsets all of the block numbers.  Renumber the blocks
690 /// and update the arrays that parallel this numbering.
691 void MipsConstantIslands::updateForInsertedWaterBlock
692   (MachineBasicBlock *NewBB) {
693   // Renumber the MBB's to keep them consecutive.
694   NewBB->getParent()->RenumberBlocks(NewBB);
695
696   // Insert an entry into BBInfo to align it properly with the (newly
697   // renumbered) block numbers.
698   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
699
700   // Next, update WaterList.  Specifically, we need to add NewMBB as having
701   // available water after it.
702   water_iterator IP =
703     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
704                      CompareMBBNumbers);
705   WaterList.insert(IP, NewBB);
706 }
707
708 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
709   return getOffsetOf(U.MI);
710 }
711
712 /// Split the basic block containing MI into two blocks, which are joined by
713 /// an unconditional branch.  Update data structures and renumber blocks to
714 /// account for this change and returns the newly created block.
715 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
716   (MachineInstr *MI) {
717   MachineBasicBlock *OrigBB = MI->getParent();
718
719   // Create a new MBB for the code after the OrigBB.
720   MachineBasicBlock *NewBB =
721     MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
722   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
723   MF->insert(MBBI, NewBB);
724
725   // Splice the instructions starting with MI over to NewBB.
726   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
727
728   // Add an unconditional branch from OrigBB to NewBB.
729   // Note the new unconditional branch is not being recorded.
730   // There doesn't seem to be meaningful DebugInfo available; this doesn't
731   // correspond to anything in the source.
732   BuildMI(OrigBB, DebugLoc(), TII->get(Mips::BimmX16)).addMBB(NewBB);
733   ++NumSplit;
734
735   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
736   NewBB->transferSuccessors(OrigBB);
737
738   // OrigBB branches to NewBB.
739   OrigBB->addSuccessor(NewBB);
740
741   // Update internal data structures to account for the newly inserted MBB.
742   // This is almost the same as updateForInsertedWaterBlock, except that
743   // the Water goes after OrigBB, not NewBB.
744   MF->RenumberBlocks(NewBB);
745
746   // Insert an entry into BBInfo to align it properly with the (newly
747   // renumbered) block numbers.
748   BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
749
750   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
751   // available water after it (but not if it's already there, which happens
752   // when splitting before a conditional branch that is followed by an
753   // unconditional branch - in that case we want to insert NewBB).
754   water_iterator IP =
755     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
756                      CompareMBBNumbers);
757   MachineBasicBlock* WaterBB = *IP;
758   if (WaterBB == OrigBB)
759     WaterList.insert(llvm::next(IP), NewBB);
760   else
761     WaterList.insert(IP, OrigBB);
762   NewWaterList.insert(OrigBB);
763
764   // Figure out how large the OrigBB is.  As the first half of the original
765   // block, it cannot contain a tablejump.  The size includes
766   // the new jump we added.  (It should be possible to do this without
767   // recounting everything, but it's very confusing, and this is rarely
768   // executed.)
769   computeBlockSize(OrigBB);
770
771   // Figure out how large the NewMBB is.  As the second half of the original
772   // block, it may contain a tablejump.
773   computeBlockSize(NewBB);
774
775   // All BBOffsets following these blocks must be modified.
776   adjustBBOffsetsAfter(OrigBB);
777
778   return NewBB;
779 }
780
781
782
783 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
784 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
785 /// constant pool entry).
786 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
787                                          unsigned TrialOffset, unsigned MaxDisp,
788                                          bool NegativeOK) {
789   if (UserOffset <= TrialOffset) {
790     // User before the Trial.
791     if (TrialOffset - UserOffset <= MaxDisp)
792       return true;
793   } else if (NegativeOK) {
794     if (UserOffset - TrialOffset <= MaxDisp)
795       return true;
796   }
797   return false;
798 }
799
800 /// isWaterInRange - Returns true if a CPE placed after the specified
801 /// Water (a basic block) will be in range for the specific MI.
802 ///
803 /// Compute how much the function will grow by inserting a CPE after Water.
804 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
805                                         MachineBasicBlock* Water, CPUser &U,
806                                         unsigned &Growth) {
807   unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
808   unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
809   unsigned NextBlockOffset, NextBlockAlignment;
810   MachineFunction::const_iterator NextBlock = Water;
811   if (++NextBlock == MF->end()) {
812     NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
813     NextBlockAlignment = 0;
814   } else {
815     NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
816     NextBlockAlignment = NextBlock->getAlignment();
817   }
818   unsigned Size = U.CPEMI->getOperand(2).getImm();
819   unsigned CPEEnd = CPEOffset + Size;
820
821   // The CPE may be able to hide in the alignment padding before the next
822   // block. It may also cause more padding to be required if it is more aligned
823   // that the next block.
824   if (CPEEnd > NextBlockOffset) {
825     Growth = CPEEnd - NextBlockOffset;
826     // Compute the padding that would go at the end of the CPE to align the next
827     // block.
828     Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
829
830     // If the CPE is to be inserted before the instruction, that will raise
831     // the offset of the instruction. Also account for unknown alignment padding
832     // in blocks between CPE and the user.
833     if (CPEOffset < UserOffset)
834       UserOffset += Growth;
835   } else
836     // CPE fits in existing padding.
837     Growth = 0;
838
839   return isOffsetInRange(UserOffset, CPEOffset, U);
840 }
841
842 /// isCPEntryInRange - Returns true if the distance between specific MI and
843 /// specific ConstPool entry instruction can fit in MI's displacement field.
844 bool MipsConstantIslands::isCPEntryInRange
845   (MachineInstr *MI, unsigned UserOffset,
846    MachineInstr *CPEMI, unsigned MaxDisp,
847    bool NegOk, bool DoDump) {
848   unsigned CPEOffset  = getOffsetOf(CPEMI);
849
850   if (DoDump) {
851     DEBUG({
852       unsigned Block = MI->getParent()->getNumber();
853       const BasicBlockInfo &BBI = BBInfo[Block];
854       dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
855              << " max delta=" << MaxDisp
856              << format(" insn address=%#x", UserOffset)
857              << " in BB#" << Block << ": "
858              << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
859              << format("CPE address=%#x offset=%+d: ", CPEOffset,
860                        int(CPEOffset-UserOffset));
861     });
862   }
863
864   return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
865 }
866
867 #ifndef NDEBUG
868 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
869 /// unconditionally branches to its only successor.
870 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
871   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
872     return false;
873   MachineBasicBlock *Succ = *MBB->succ_begin();
874   MachineBasicBlock *Pred = *MBB->pred_begin();
875   MachineInstr *PredMI = &Pred->back();
876   if (PredMI->getOpcode() == Mips::BimmX16)
877     return PredMI->getOperand(0).getMBB() == Succ;
878   return false;
879 }
880 #endif
881
882 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
883   unsigned BBNum = BB->getNumber();
884   for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
885     // Get the offset and known bits at the end of the layout predecessor.
886     // Include the alignment of the current block.
887     unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
888     BBInfo[i].Offset = Offset;
889   }
890 }
891
892 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
893 /// and instruction CPEMI, and decrement its refcount.  If the refcount
894 /// becomes 0 remove the entry and instruction.  Returns true if we removed
895 /// the entry, false if we didn't.
896
897 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
898                                                     MachineInstr *CPEMI) {
899   // Find the old entry. Eliminate it if it is no longer used.
900   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
901   assert(CPE && "Unexpected!");
902   if (--CPE->RefCount == 0) {
903     removeDeadCPEMI(CPEMI);
904     CPE->CPEMI = NULL;
905     --NumCPEs;
906     return true;
907   }
908   return false;
909 }
910
911 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
912 /// if not, see if an in-range clone of the CPE is in range, and if so,
913 /// change the data structures so the user references the clone.  Returns:
914 /// 0 = no existing entry found
915 /// 1 = entry found, and there were no code insertions or deletions
916 /// 2 = entry found, and there were code insertions or deletions
917 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
918 {
919   MachineInstr *UserMI = U.MI;
920   MachineInstr *CPEMI  = U.CPEMI;
921
922   // Check to see if the CPE is already in-range.
923   if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
924                        true)) {
925     DEBUG(dbgs() << "In range\n");
926     return 1;
927   }
928
929   // No.  Look for previously created clones of the CPE that are in range.
930   unsigned CPI = CPEMI->getOperand(1).getIndex();
931   std::vector<CPEntry> &CPEs = CPEntries[CPI];
932   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
933     // We already tried this one
934     if (CPEs[i].CPEMI == CPEMI)
935       continue;
936     // Removing CPEs can leave empty entries, skip
937     if (CPEs[i].CPEMI == NULL)
938       continue;
939     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
940                      U.NegOk)) {
941       DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
942                    << CPEs[i].CPI << "\n");
943       // Point the CPUser node to the replacement
944       U.CPEMI = CPEs[i].CPEMI;
945       // Change the CPI in the instruction operand to refer to the clone.
946       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
947         if (UserMI->getOperand(j).isCPI()) {
948           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
949           break;
950         }
951       // Adjust the refcount of the clone...
952       CPEs[i].RefCount++;
953       // ...and the original.  If we didn't remove the old entry, none of the
954       // addresses changed, so we don't need another pass.
955       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
956     }
957   }
958   return 0;
959 }
960
961 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
962 /// This version checks if the longer form of the instruction can be used to
963 /// to satisfy things.
964 /// if not, see if an in-range clone of the CPE is in range, and if so,
965 /// change the data structures so the user references the clone.  Returns:
966 /// 0 = no existing entry found
967 /// 1 = entry found, and there were no code insertions or deletions
968 /// 2 = entry found, and there were code insertions or deletions
969 int MipsConstantIslands::findLongFormInRangeCPEntry
970   (CPUser& U, unsigned UserOffset)
971 {
972   MachineInstr *UserMI = U.MI;
973   MachineInstr *CPEMI  = U.CPEMI;
974
975   // Check to see if the CPE is already in-range.
976   if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
977                        U.getLongFormMaxDisp(), U.NegOk,
978                        true)) {
979     DEBUG(dbgs() << "In range\n");
980     UserMI->setDesc(TII->get(U.getLongFormOpcode()));
981     return 2;  // instruction is longer length now
982   }
983
984   // No.  Look for previously created clones of the CPE that are in range.
985   unsigned CPI = CPEMI->getOperand(1).getIndex();
986   std::vector<CPEntry> &CPEs = CPEntries[CPI];
987   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
988     // We already tried this one
989     if (CPEs[i].CPEMI == CPEMI)
990       continue;
991     // Removing CPEs can leave empty entries, skip
992     if (CPEs[i].CPEMI == NULL)
993       continue;
994     if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
995                          U.getLongFormMaxDisp(), U.NegOk)) {
996       DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
997                    << CPEs[i].CPI << "\n");
998       // Point the CPUser node to the replacement
999       U.CPEMI = CPEs[i].CPEMI;
1000       // Change the CPI in the instruction operand to refer to the clone.
1001       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1002         if (UserMI->getOperand(j).isCPI()) {
1003           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1004           break;
1005         }
1006       // Adjust the refcount of the clone...
1007       CPEs[i].RefCount++;
1008       // ...and the original.  If we didn't remove the old entry, none of the
1009       // addresses changed, so we don't need another pass.
1010       return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1011     }
1012   }
1013   return 0;
1014 }
1015
1016 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1017 /// the specific unconditional branch instruction.
1018 static inline unsigned getUnconditionalBrDisp(int Opc) {
1019   switch (Opc) {
1020   case Mips::BimmX16:
1021     return ((1<<16)-1)*2;
1022   default:
1023     break;
1024   }
1025   return ((1<<16)-1)*2;
1026 }
1027
1028 /// findAvailableWater - Look for an existing entry in the WaterList in which
1029 /// we can place the CPE referenced from U so it's within range of U's MI.
1030 /// Returns true if found, false if not.  If it returns true, WaterIter
1031 /// is set to the WaterList entry.  
1032 /// To ensure that this pass
1033 /// terminates, the CPE location for a particular CPUser is only allowed to
1034 /// move to a lower address, so search backward from the end of the list and
1035 /// prefer the first water that is in range.
1036 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1037                                       water_iterator &WaterIter) {
1038   if (WaterList.empty())
1039     return false;
1040
1041   unsigned BestGrowth = ~0u;
1042   for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1043        --IP) {
1044     MachineBasicBlock* WaterBB = *IP;
1045     // Check if water is in range and is either at a lower address than the
1046     // current "high water mark" or a new water block that was created since
1047     // the previous iteration by inserting an unconditional branch.  In the
1048     // latter case, we want to allow resetting the high water mark back to
1049     // this new water since we haven't seen it before.  Inserting branches
1050     // should be relatively uncommon and when it does happen, we want to be
1051     // sure to take advantage of it for all the CPEs near that block, so that
1052     // we don't insert more branches than necessary.
1053     unsigned Growth;
1054     if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1055         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1056          NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1057       // This is the least amount of required padding seen so far.
1058       BestGrowth = Growth;
1059       WaterIter = IP;
1060       DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1061                    << " Growth=" << Growth << '\n');
1062
1063       // Keep looking unless it is perfect.
1064       if (BestGrowth == 0)
1065         return true;
1066     }
1067     if (IP == B)
1068       break;
1069   }
1070   return BestGrowth != ~0u;
1071 }
1072
1073 /// createNewWater - No existing WaterList entry will work for
1074 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1075 /// block is used if in range, and the conditional branch munged so control
1076 /// flow is correct.  Otherwise the block is split to create a hole with an
1077 /// unconditional branch around it.  In either case NewMBB is set to a
1078 /// block following which the new island can be inserted (the WaterList
1079 /// is not adjusted).
1080 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1081                                         unsigned UserOffset,
1082                                         MachineBasicBlock *&NewMBB) {
1083   CPUser &U = CPUsers[CPUserIndex];
1084   MachineInstr *UserMI = U.MI;
1085   MachineInstr *CPEMI  = U.CPEMI;
1086   unsigned CPELogAlign = getCPELogAlign(CPEMI);
1087   MachineBasicBlock *UserMBB = UserMI->getParent();
1088   const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1089
1090   // If the block does not end in an unconditional branch already, and if the
1091   // end of the block is within range, make new water there.  
1092   if (BBHasFallthrough(UserMBB)) {
1093     // Size of branch to insert.
1094     unsigned Delta = 2;
1095     // Compute the offset where the CPE will begin.
1096     unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1097
1098     if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1099       DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1100             << format(", expected CPE offset %#x\n", CPEOffset));
1101       NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1102       // Add an unconditional branch from UserMBB to fallthrough block.  Record
1103       // it for branch lengthening; this new branch will not get out of range,
1104       // but if the preceding conditional branch is out of range, the targets
1105       // will be exchanged, and the altered branch may be out of range, so the
1106       // machinery has to know about it.
1107       int UncondBr = Mips::BimmX16;
1108       BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1109       unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1110       ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1111                                       MaxDisp, false, UncondBr));
1112       BBInfo[UserMBB->getNumber()].Size += Delta;
1113       adjustBBOffsetsAfter(UserMBB);
1114       return;
1115     }
1116   }
1117
1118   // What a big block.  Find a place within the block to split it.  
1119
1120   // Try to split the block so it's fully aligned.  Compute the latest split
1121   // point where we can add a 4-byte branch instruction, and then align to
1122   // LogAlign which is the largest possible alignment in the function.
1123   unsigned LogAlign = MF->getAlignment();
1124   assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1125   unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1126   DEBUG(dbgs() << format("Split in middle of big block before %#x",
1127                          BaseInsertOffset));
1128
1129   // The 4 in the following is for the unconditional branch we'll be inserting
1130   // Alignment of the island is handled
1131   // inside isOffsetInRange.
1132   BaseInsertOffset -= 4;
1133
1134   DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1135                << " la=" << LogAlign << '\n');
1136
1137   // This could point off the end of the block if we've already got constant
1138   // pool entries following this block; only the last one is in the water list.
1139   // Back past any possible branches (allow for a conditional and a maximally
1140   // long unconditional).
1141   if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1142     BaseInsertOffset = UserBBI.postOffset() - 8;
1143     DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1144   }
1145   unsigned EndInsertOffset = BaseInsertOffset + 4 +
1146     CPEMI->getOperand(2).getImm();
1147   MachineBasicBlock::iterator MI = UserMI;
1148   ++MI;
1149   unsigned CPUIndex = CPUserIndex+1;
1150   unsigned NumCPUsers = CPUsers.size();
1151   //MachineInstr *LastIT = 0;
1152   for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1153        Offset < BaseInsertOffset;
1154        Offset += TII->GetInstSizeInBytes(MI),
1155        MI = llvm::next(MI)) {
1156     assert(MI != UserMBB->end() && "Fell off end of block");
1157     if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1158       CPUser &U = CPUsers[CPUIndex];
1159       if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1160         // Shift intertion point by one unit of alignment so it is within reach.
1161         BaseInsertOffset -= 1u << LogAlign;
1162         EndInsertOffset  -= 1u << LogAlign;
1163       }
1164       // This is overly conservative, as we don't account for CPEMIs being
1165       // reused within the block, but it doesn't matter much.  Also assume CPEs
1166       // are added in order with alignment padding.  We may eventually be able
1167       // to pack the aligned CPEs better.
1168       EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1169       CPUIndex++;
1170     }
1171   }
1172
1173   --MI;
1174   NewMBB = splitBlockBeforeInstr(MI);
1175 }
1176
1177 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1178 /// is out-of-range.  If so, pick up the constant pool value and move it some
1179 /// place in-range.  Return true if we changed any addresses (thus must run
1180 /// another pass of branch lengthening), false otherwise.
1181 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1182   CPUser &U = CPUsers[CPUserIndex];
1183   MachineInstr *UserMI = U.MI;
1184   MachineInstr *CPEMI  = U.CPEMI;
1185   unsigned CPI = CPEMI->getOperand(1).getIndex();
1186   unsigned Size = CPEMI->getOperand(2).getImm();
1187   // Compute this only once, it's expensive.
1188   unsigned UserOffset = getUserOffset(U);
1189
1190   // See if the current entry is within range, or there is a clone of it
1191   // in range.
1192   int result = findInRangeCPEntry(U, UserOffset);
1193   if (result==1) return false;
1194   else if (result==2) return true;
1195
1196
1197   // Look for water where we can place this CPE.
1198   MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1199   MachineBasicBlock *NewMBB;
1200   water_iterator IP;
1201   if (findAvailableWater(U, UserOffset, IP)) {
1202     DEBUG(dbgs() << "Found water in range\n");
1203     MachineBasicBlock *WaterBB = *IP;
1204
1205     // If the original WaterList entry was "new water" on this iteration,
1206     // propagate that to the new island.  This is just keeping NewWaterList
1207     // updated to match the WaterList, which will be updated below.
1208     if (NewWaterList.erase(WaterBB))
1209       NewWaterList.insert(NewIsland);
1210
1211     // The new CPE goes before the following block (NewMBB).
1212     NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1213
1214   } else {
1215     // No water found.
1216     // we first see if a longer form of the instrucion could have reached
1217     // the constant. in that case we won't bother to split
1218 #ifdef IN_PROGRESS
1219     result = findLongFormInRangeCPEntry(U, UserOffset);
1220 #endif
1221     DEBUG(dbgs() << "No water found\n");
1222     createNewWater(CPUserIndex, UserOffset, NewMBB);
1223
1224     // splitBlockBeforeInstr adds to WaterList, which is important when it is
1225     // called while handling branches so that the water will be seen on the
1226     // next iteration for constant pools, but in this context, we don't want
1227     // it.  Check for this so it will be removed from the WaterList.
1228     // Also remove any entry from NewWaterList.
1229     MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1230     IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1231     if (IP != WaterList.end())
1232       NewWaterList.erase(WaterBB);
1233
1234     // We are adding new water.  Update NewWaterList.
1235     NewWaterList.insert(NewIsland);
1236   }
1237
1238   // Remove the original WaterList entry; we want subsequent insertions in
1239   // this vicinity to go after the one we're about to insert.  This
1240   // considerably reduces the number of times we have to move the same CPE
1241   // more than once and is also important to ensure the algorithm terminates.
1242   if (IP != WaterList.end())
1243     WaterList.erase(IP);
1244
1245   // Okay, we know we can put an island before NewMBB now, do it!
1246   MF->insert(NewMBB, NewIsland);
1247
1248   // Update internal data structures to account for the newly inserted MBB.
1249   updateForInsertedWaterBlock(NewIsland);
1250
1251   // Decrement the old entry, and remove it if refcount becomes 0.
1252   decrementCPEReferenceCount(CPI, CPEMI);
1253
1254   // Now that we have an island to add the CPE to, clone the original CPE and
1255   // add it to the island.
1256   U.HighWaterMark = NewIsland;
1257   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1258                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1259   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1260   ++NumCPEs;
1261
1262   // Mark the basic block as aligned as required by the const-pool entry.
1263   NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1264
1265   // Increase the size of the island block to account for the new entry.
1266   BBInfo[NewIsland->getNumber()].Size += Size;
1267   adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1268
1269   // No existing clone of this CPE is within range.
1270   // We will be generating a new clone.  Get a UID for it.
1271   unsigned ID = createPICLabelUId();
1272
1273   // Finally, change the CPI in the instruction operand to be ID.
1274   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1275     if (UserMI->getOperand(i).isCPI()) {
1276       UserMI->getOperand(i).setIndex(ID);
1277       break;
1278     }
1279
1280   DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1281         << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1282
1283   return true;
1284 }
1285
1286 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1287 /// sizes and offsets of impacted basic blocks.
1288 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1289   MachineBasicBlock *CPEBB = CPEMI->getParent();
1290   unsigned Size = CPEMI->getOperand(2).getImm();
1291   CPEMI->eraseFromParent();
1292   BBInfo[CPEBB->getNumber()].Size -= Size;
1293   // All succeeding offsets have the current size value added in, fix this.
1294   if (CPEBB->empty()) {
1295     BBInfo[CPEBB->getNumber()].Size = 0;
1296
1297     // This block no longer needs to be aligned.
1298     CPEBB->setAlignment(0);
1299   } else
1300     // Entries are sorted by descending alignment, so realign from the front.
1301     CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1302
1303   adjustBBOffsetsAfter(CPEBB);
1304   // An island has only one predecessor BB and one successor BB. Check if
1305   // this BB's predecessor jumps directly to this BB's successor. This
1306   // shouldn't happen currently.
1307   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1308   // FIXME: remove the empty blocks after all the work is done?
1309 }
1310
1311 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1312 /// are zero.
1313 bool MipsConstantIslands::removeUnusedCPEntries() {
1314   unsigned MadeChange = false;
1315   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1316       std::vector<CPEntry> &CPEs = CPEntries[i];
1317       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1318         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1319           removeDeadCPEMI(CPEs[j].CPEMI);
1320           CPEs[j].CPEMI = NULL;
1321           MadeChange = true;
1322         }
1323       }
1324   }
1325   return MadeChange;
1326 }
1327
1328 /// isBBInRange - Returns true if the distance between specific MI and
1329 /// specific BB can fit in MI's displacement field.
1330 bool MipsConstantIslands::isBBInRange
1331   (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1332
1333 unsigned PCAdj = 4;
1334
1335   unsigned BrOffset   = getOffsetOf(MI) + PCAdj;
1336   unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1337
1338   DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1339                << " from BB#" << MI->getParent()->getNumber()
1340                << " max delta=" << MaxDisp
1341                << " from " << getOffsetOf(MI) << " to " << DestOffset
1342                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1343
1344   if (BrOffset <= DestOffset) {
1345     // Branch before the Dest.
1346     if (DestOffset-BrOffset <= MaxDisp)
1347       return true;
1348   } else {
1349     if (BrOffset-DestOffset <= MaxDisp)
1350       return true;
1351   }
1352   return false;
1353 }
1354
1355 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1356 /// away to fit in its displacement field.
1357 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1358   MachineInstr *MI = Br.MI;
1359   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1360
1361   // Check to see if the DestBB is already in-range.
1362   if (isBBInRange(MI, DestBB, Br.MaxDisp))
1363     return false;
1364
1365   if (!Br.isCond)
1366     return fixupUnconditionalBr(Br);
1367   return fixupConditionalBr(Br);
1368 }
1369
1370 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1371 /// too far away to fit in its displacement field. If the LR register has been
1372 /// spilled in the epilogue, then we can use BL to implement a far jump.
1373 /// Otherwise, add an intermediate branch instruction to a branch.
1374 bool
1375 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1376   MachineInstr *MI = Br.MI;
1377   MachineBasicBlock *MBB = MI->getParent();
1378   // Use BL to implement far jump.
1379   Br.MaxDisp = ((1 << 16)-1) * 2;
1380   MI->setDesc(TII->get(Mips::BimmX16));
1381   BBInfo[MBB->getNumber()].Size += 2;
1382   adjustBBOffsetsAfter(MBB);
1383   HasFarJump = true;
1384   ++NumUBrFixed;
1385
1386   DEBUG(dbgs() << "  Changed B to long jump " << *MI);
1387
1388   return true;
1389 }
1390
1391 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1392 /// far away to fit in its displacement field. It is converted to an inverse
1393 /// conditional branch + an unconditional branch to the destination.
1394 bool
1395 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1396   MachineInstr *MI = Br.MI;
1397   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1398
1399   // Add an unconditional branch to the destination and invert the branch
1400   // condition to jump over it:
1401   // blt L1
1402   // =>
1403   // bge L2
1404   // b   L1
1405   // L2:
1406   unsigned CCReg = 0;  // FIXME
1407   unsigned CC=0; //FIXME
1408
1409   // If the branch is at the end of its MBB and that has a fall-through block,
1410   // direct the updated conditional branch to the fall-through block. Otherwise,
1411   // split the MBB before the next instruction.
1412   MachineBasicBlock *MBB = MI->getParent();
1413   MachineInstr *BMI = &MBB->back();
1414   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1415
1416   ++NumCBrFixed;
1417   if (BMI != MI) {
1418     if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1419         BMI->getOpcode() == Br.UncondBr) {
1420       // Last MI in the BB is an unconditional branch. Can we simply invert the
1421       // condition and swap destinations:
1422       // beq L1
1423       // b   L2
1424       // =>
1425       // bne L2
1426       // b   L1
1427       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1428       if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1429         DEBUG(dbgs() << "  Invert Bcc condition and swap its destination with "
1430                      << *BMI);
1431         BMI->getOperand(0).setMBB(DestBB);
1432         MI->getOperand(0).setMBB(NewDest);
1433         return true;
1434       }
1435     }
1436   }
1437
1438   if (NeedSplit) {
1439     splitBlockBeforeInstr(MI);
1440     // No need for the branch to the next block. We're adding an unconditional
1441     // branch to the destination.
1442     int delta = TII->GetInstSizeInBytes(&MBB->back());
1443     BBInfo[MBB->getNumber()].Size -= delta;
1444     MBB->back().eraseFromParent();
1445     // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1446   }
1447   MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1448
1449   DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
1450                << " also invert condition and change dest. to BB#"
1451                << NextBB->getNumber() << "\n");
1452
1453   // Insert a new conditional branch and a new unconditional branch.
1454   // Also update the ImmBranch as well as adding a new entry for the new branch.
1455   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1456     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1457   Br.MI = &MBB->back();
1458   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1459   BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1460   BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1461   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1462   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1463
1464   // Remove the old conditional branch.  It may or may not still be in MBB.
1465   BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1466   MI->eraseFromParent();
1467   adjustBBOffsetsAfter(MBB);
1468   return true;
1469 }
1470
1471
1472 void MipsConstantIslands::prescanForConstants() {
1473   unsigned J = 0;
1474   (void)J;
1475   PrescannedForConstants = true;
1476   for (MachineFunction::iterator B =
1477          MF->begin(), E = MF->end(); B != E; ++B) {
1478     for (MachineBasicBlock::instr_iterator I =
1479         B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1480       switch(I->getDesc().getOpcode()) {
1481         case Mips::LwConstant32: {
1482           DEBUG(dbgs() << "constant island constant " << *I << "\n");
1483           J = I->getNumOperands();
1484           DEBUG(dbgs() << "num operands " << J  << "\n");
1485           MachineOperand& Literal = I->getOperand(1);
1486           if (Literal.isImm()) {
1487             int64_t V = Literal.getImm();
1488             DEBUG(dbgs() << "literal " << V  << "\n");
1489             Type *Int32Ty =
1490               Type::getInt32Ty(MF->getFunction()->getContext());
1491             const Constant *C = ConstantInt::get(Int32Ty, V);
1492             unsigned index = MCP->getConstantPoolIndex(C, 4);
1493             I->getOperand(2).ChangeToImmediate(index);
1494             DEBUG(dbgs() << "constant island constant " << *I << "\n");
1495             I->setDesc(TII->get(Mips::LwRxPcTcp16));
1496             I->RemoveOperand(1);
1497             I->RemoveOperand(1);
1498             I->addOperand(MachineOperand::CreateCPI(index, 0));
1499             I->addOperand(MachineOperand::CreateImm(4));
1500           }
1501           break;
1502         }
1503         default:
1504           break;
1505       }
1506     }
1507   }
1508 }
1509