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