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