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