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