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