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