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