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