remove various std::ostream version of printing methods from
[oota-llvm.git] / lib / Target / ARM / ARMConstantIslandPass.cpp
1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
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 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function.  This is required due to the
12 // limited pc-relative displacements that ARM has.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "arm-cp-islands"
17 #include "ARM.h"
18 #include "ARMAddressingModes.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMInstrInfo.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 using namespace llvm;
35
36 STATISTIC(NumCPEs,       "Number of constpool entries");
37 STATISTIC(NumSplit,      "Number of uncond branches inserted");
38 STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
39 STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
40 STATISTIC(NumTBs,        "Number of table branches generated");
41 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
42 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
43
44 namespace {
45   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
46   /// requires constant pool entries to be scattered among the instructions
47   /// inside a function.  To do this, it completely ignores the normal LLVM
48   /// constant pool; instead, it places constants wherever it feels like with
49   /// special instructions.
50   ///
51   /// The terminology used in this pass includes:
52   ///   Islands - Clumps of constants placed in the function.
53   ///   Water   - Potential places where an island could be formed.
54   ///   CPE     - A constant pool entry that has been placed somewhere, which
55   ///             tracks a list of users.
56   class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
57     /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
58     /// by MBB Number.  The two-byte pads required for Thumb alignment are
59     /// counted as part of the following block (i.e., the offset and size for
60     /// a padded block will both be ==2 mod 4).
61     std::vector<unsigned> BBSizes;
62
63     /// BBOffsets - the offset of each MBB in bytes, starting from 0.
64     /// The two-byte pads required for Thumb alignment are counted as part of
65     /// the following block.
66     std::vector<unsigned> BBOffsets;
67
68     /// WaterList - A sorted list of basic blocks where islands could be placed
69     /// (i.e. blocks that don't fall through to the following block, due
70     /// to a return, unreachable, or unconditional branch).
71     std::vector<MachineBasicBlock*> WaterList;
72
73     /// CPUser - One user of a constant pool, keeping the machine instruction
74     /// pointer, the constant pool being referenced, and the max displacement
75     /// allowed from the instruction to the CP.
76     struct CPUser {
77       MachineInstr *MI;
78       MachineInstr *CPEMI;
79       unsigned MaxDisp;
80       bool NegOk;
81       bool IsSoImm;
82       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
83              bool neg, bool soimm)
84         : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {}
85     };
86
87     /// CPUsers - Keep track of all of the machine instructions that use various
88     /// constant pools and their max displacement.
89     std::vector<CPUser> CPUsers;
90
91     /// CPEntry - One per constant pool entry, keeping the machine instruction
92     /// pointer, the constpool index, and the number of CPUser's which
93     /// reference this entry.
94     struct CPEntry {
95       MachineInstr *CPEMI;
96       unsigned CPI;
97       unsigned RefCount;
98       CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
99         : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
100     };
101
102     /// CPEntries - Keep track of all of the constant pool entry machine
103     /// instructions. For each original constpool index (i.e. those that
104     /// existed upon entry to this pass), it keeps a vector of entries.
105     /// Original elements are cloned as we go along; the clones are
106     /// put in the vector of the original element, but have distinct CPIs.
107     std::vector<std::vector<CPEntry> > CPEntries;
108
109     /// ImmBranch - One per immediate branch, keeping the machine instruction
110     /// pointer, conditional or unconditional, the max displacement,
111     /// and (if isCond is true) the corresponding unconditional branch
112     /// opcode.
113     struct ImmBranch {
114       MachineInstr *MI;
115       unsigned MaxDisp : 31;
116       bool isCond : 1;
117       int UncondBr;
118       ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
119         : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
120     };
121
122     /// ImmBranches - Keep track of all the immediate branch instructions.
123     ///
124     std::vector<ImmBranch> ImmBranches;
125
126     /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
127     ///
128     SmallVector<MachineInstr*, 4> PushPopMIs;
129
130     /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
131     SmallVector<MachineInstr*, 4> T2JumpTables;
132
133     /// HasFarJump - True if any far jump instruction has been emitted during
134     /// the branch fix up pass.
135     bool HasFarJump;
136
137     const TargetInstrInfo *TII;
138     const ARMSubtarget *STI;
139     ARMFunctionInfo *AFI;
140     bool isThumb;
141     bool isThumb1;
142     bool isThumb2;
143   public:
144     static char ID;
145     ARMConstantIslands() : MachineFunctionPass(&ID) {}
146
147     virtual bool runOnMachineFunction(MachineFunction &MF);
148
149     virtual const char *getPassName() const {
150       return "ARM constant island placement and branch shortening pass";
151     }
152
153   private:
154     void DoInitialPlacement(MachineFunction &MF,
155                             std::vector<MachineInstr*> &CPEMIs);
156     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
157     void InitialFunctionScan(MachineFunction &MF,
158                              const std::vector<MachineInstr*> &CPEMIs);
159     MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
160     void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
161     void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
162     bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
163     int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
164     bool LookForWater(CPUser&U, unsigned UserOffset,
165                       MachineBasicBlock** NewMBB);
166     MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
167                         std::vector<MachineBasicBlock*>::iterator IP);
168     void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
169                       MachineBasicBlock** NewMBB);
170     bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
171     void RemoveDeadCPEMI(MachineInstr *CPEMI);
172     bool RemoveUnusedCPEntries();
173     bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
174                       MachineInstr *CPEMI, unsigned Disp, bool NegOk,
175                       bool DoDump = false);
176     bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
177                         CPUser &U);
178     bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
179                          unsigned Disp, bool NegativeOK, bool IsSoImm = false);
180     bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
181     bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
182     bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
183     bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
184     bool UndoLRSpillRestore();
185     bool OptimizeThumb2Instructions(MachineFunction &MF);
186     bool OptimizeThumb2Branches(MachineFunction &MF);
187     bool OptimizeThumb2JumpTables(MachineFunction &MF);
188
189     unsigned GetOffsetOf(MachineInstr *MI) const;
190     void dumpBBs();
191     void verify(MachineFunction &MF);
192   };
193   char ARMConstantIslands::ID = 0;
194 }
195
196 /// verify - check BBOffsets, BBSizes, alignment of islands
197 void ARMConstantIslands::verify(MachineFunction &MF) {
198   assert(BBOffsets.size() == BBSizes.size());
199   for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
200     assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
201   if (!isThumb)
202     return;
203 #ifndef NDEBUG
204   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
205        MBBI != E; ++MBBI) {
206     MachineBasicBlock *MBB = MBBI;
207     if (!MBB->empty() &&
208         MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
209       unsigned MBBId = MBB->getNumber();
210       assert((BBOffsets[MBBId]%4 == 0 && BBSizes[MBBId]%4 == 0) ||
211              (BBOffsets[MBBId]%4 != 0 && BBSizes[MBBId]%4 != 0));
212     }
213   }
214 #endif
215 }
216
217 /// print block size and offset information - debugging
218 void ARMConstantIslands::dumpBBs() {
219   for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
220     DOUT << "block " << J << " offset " << BBOffsets[J] <<
221                             " size " << BBSizes[J] << "\n";
222   }
223 }
224
225 /// createARMConstantIslandPass - returns an instance of the constpool
226 /// island pass.
227 FunctionPass *llvm::createARMConstantIslandPass() {
228   return new ARMConstantIslands();
229 }
230
231 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
232   MachineConstantPool &MCP = *MF.getConstantPool();
233
234   TII = MF.getTarget().getInstrInfo();
235   AFI = MF.getInfo<ARMFunctionInfo>();
236   STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
237
238   isThumb = AFI->isThumbFunction();
239   isThumb1 = AFI->isThumb1OnlyFunction();
240   isThumb2 = AFI->isThumb2Function();
241
242   HasFarJump = false;
243
244   // Renumber all of the machine basic blocks in the function, guaranteeing that
245   // the numbers agree with the position of the block in the function.
246   MF.RenumberBlocks();
247
248   // Thumb1 functions containing constant pools get 4-byte alignment.
249   // This is so we can keep exact track of where the alignment padding goes.
250
251   // Set default. Thumb1 function is 2-byte aligned, ARM and Thumb2 are 4-byte
252   // aligned.
253   AFI->setAlign(isThumb1 ? 1U : 2U);
254
255   // Perform the initial placement of the constant pool entries.  To start with,
256   // we put them all at the end of the function.
257   std::vector<MachineInstr*> CPEMIs;
258   if (!MCP.isEmpty()) {
259     DoInitialPlacement(MF, CPEMIs);
260     if (isThumb1)
261       AFI->setAlign(2U);
262   }
263
264   /// The next UID to take is the first unused one.
265   AFI->initConstPoolEntryUId(CPEMIs.size());
266
267   // Do the initial scan of the function, building up information about the
268   // sizes of each block, the location of all the water, and finding all of the
269   // constant pool users.
270   InitialFunctionScan(MF, CPEMIs);
271   CPEMIs.clear();
272
273   /// Remove dead constant pool entries.
274   RemoveUnusedCPEntries();
275
276   // Iteratively place constant pool entries and fix up branches until there
277   // is no change.
278   bool MadeChange = false;
279   unsigned NoCPIters = 0, NoBRIters = 0;
280   while (true) {
281     bool CPChange = false;
282     for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
283       CPChange |= HandleConstantPoolUser(MF, i);
284     if (CPChange && ++NoCPIters > 30)
285       llvm_unreachable("Constant Island pass failed to converge!");
286     DEBUG(dumpBBs());
287
288     bool BRChange = false;
289     for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
290       BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
291     if (BRChange && ++NoBRIters > 30)
292       llvm_unreachable("Branch Fix Up pass failed to converge!");
293     DEBUG(dumpBBs());
294
295     if (!CPChange && !BRChange)
296       break;
297     MadeChange = true;
298   }
299
300   // Shrink 32-bit Thumb2 branch, load, and store instructions.
301   if (isThumb2)
302     MadeChange |= OptimizeThumb2Instructions(MF);
303
304   // After a while, this might be made debug-only, but it is not expensive.
305   verify(MF);
306
307   // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
308   // Undo the spill / restore of LR if possible.
309   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
310     MadeChange |= UndoLRSpillRestore();
311
312   BBSizes.clear();
313   BBOffsets.clear();
314   WaterList.clear();
315   CPUsers.clear();
316   CPEntries.clear();
317   ImmBranches.clear();
318   PushPopMIs.clear();
319   T2JumpTables.clear();
320
321   return MadeChange;
322 }
323
324 /// DoInitialPlacement - Perform the initial placement of the constant pool
325 /// entries.  To start with, we put them all at the end of the function.
326 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
327                                         std::vector<MachineInstr*> &CPEMIs) {
328   // Create the basic block to hold the CPE's.
329   MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
330   MF.push_back(BB);
331
332   // Add all of the constants from the constant pool to the end block, use an
333   // identity mapping of CPI's to CPE's.
334   const std::vector<MachineConstantPoolEntry> &CPs =
335     MF.getConstantPool()->getConstants();
336
337   const TargetData &TD = *MF.getTarget().getTargetData();
338   for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
339     unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
340     // Verify that all constant pool entries are a multiple of 4 bytes.  If not,
341     // we would have to pad them out or something so that instructions stay
342     // aligned.
343     assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
344     MachineInstr *CPEMI =
345       BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
346                            .addImm(i).addConstantPoolIndex(i).addImm(Size);
347     CPEMIs.push_back(CPEMI);
348
349     // Add a new CPEntry, but no corresponding CPUser yet.
350     std::vector<CPEntry> CPEs;
351     CPEs.push_back(CPEntry(CPEMI, i));
352     CPEntries.push_back(CPEs);
353     NumCPEs++;
354     DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
355   }
356 }
357
358 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
359 /// into the block immediately after it.
360 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
361   // Get the next machine basic block in the function.
362   MachineFunction::iterator MBBI = MBB;
363   if (next(MBBI) == MBB->getParent()->end())  // Can't fall off end of function.
364     return false;
365
366   MachineBasicBlock *NextBB = next(MBBI);
367   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
368        E = MBB->succ_end(); I != E; ++I)
369     if (*I == NextBB)
370       return true;
371
372   return false;
373 }
374
375 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
376 /// look up the corresponding CPEntry.
377 ARMConstantIslands::CPEntry
378 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
379                                         const MachineInstr *CPEMI) {
380   std::vector<CPEntry> &CPEs = CPEntries[CPI];
381   // Number of entries per constpool index should be small, just do a
382   // linear search.
383   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
384     if (CPEs[i].CPEMI == CPEMI)
385       return &CPEs[i];
386   }
387   return NULL;
388 }
389
390 /// InitialFunctionScan - Do the initial scan of the function, building up
391 /// information about the sizes of each block, the location of all the water,
392 /// and finding all of the constant pool users.
393 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
394                                  const std::vector<MachineInstr*> &CPEMIs) {
395   unsigned Offset = 0;
396   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
397        MBBI != E; ++MBBI) {
398     MachineBasicBlock &MBB = *MBBI;
399
400     // If this block doesn't fall through into the next MBB, then this is
401     // 'water' that a constant pool island could be placed.
402     if (!BBHasFallthrough(&MBB))
403       WaterList.push_back(&MBB);
404
405     unsigned MBBSize = 0;
406     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
407          I != E; ++I) {
408       // Add instruction size to MBBSize.
409       MBBSize += TII->GetInstSizeInBytes(I);
410
411       int Opc = I->getOpcode();
412       if (I->getDesc().isBranch()) {
413         bool isCond = false;
414         unsigned Bits = 0;
415         unsigned Scale = 1;
416         int UOpc = Opc;
417         switch (Opc) {
418         default:
419           continue;  // Ignore other JT branches
420         case ARM::tBR_JTr:
421           // A Thumb1 table jump may involve padding; for the offsets to
422           // be right, functions containing these must be 4-byte aligned.
423           AFI->setAlign(2U);
424           if ((Offset+MBBSize)%4 != 0)
425             // FIXME: Add a pseudo ALIGN instruction instead.
426             MBBSize += 2;           // padding
427           continue;   // Does not get an entry in ImmBranches
428         case ARM::t2BR_JT:
429           T2JumpTables.push_back(I);
430           continue;   // Does not get an entry in ImmBranches
431         case ARM::Bcc:
432           isCond = true;
433           UOpc = ARM::B;
434           // Fallthrough
435         case ARM::B:
436           Bits = 24;
437           Scale = 4;
438           break;
439         case ARM::tBcc:
440           isCond = true;
441           UOpc = ARM::tB;
442           Bits = 8;
443           Scale = 2;
444           break;
445         case ARM::tB:
446           Bits = 11;
447           Scale = 2;
448           break;
449         case ARM::t2Bcc:
450           isCond = true;
451           UOpc = ARM::t2B;
452           Bits = 20;
453           Scale = 2;
454           break;
455         case ARM::t2B:
456           Bits = 24;
457           Scale = 2;
458           break;
459         }
460
461         // Record this immediate branch.
462         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
463         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
464       }
465
466       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
467         PushPopMIs.push_back(I);
468
469       if (Opc == ARM::CONSTPOOL_ENTRY)
470         continue;
471
472       // Scan the instructions for constant pool operands.
473       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
474         if (I->getOperand(op).isCPI()) {
475           // We found one.  The addressing mode tells us the max displacement
476           // from the PC that this instruction permits.
477
478           // Basic size info comes from the TSFlags field.
479           unsigned Bits = 0;
480           unsigned Scale = 1;
481           bool NegOk = false;
482           bool IsSoImm = false;
483
484           switch (Opc) {
485           default:
486             llvm_unreachable("Unknown addressing mode for CP reference!");
487             break;
488
489           // Taking the address of a CP entry.
490           case ARM::LEApcrel:
491             // This takes a SoImm, which is 8 bit immediate rotated. We'll
492             // pretend the maximum offset is 255 * 4. Since each instruction
493             // 4 byte wide, this is always correct. We'llc heck for other
494             // displacements that fits in a SoImm as well.
495             Bits = 8;
496             Scale = 4;
497             NegOk = true;
498             IsSoImm = true;
499             break;
500           case ARM::t2LEApcrel:
501             Bits = 12;
502             NegOk = true;
503             break;
504           case ARM::tLEApcrel:
505             Bits = 8;
506             Scale = 4;
507             break;
508
509           case ARM::LDR:
510           case ARM::LDRcp:
511           case ARM::t2LDRpci:
512             Bits = 12;  // +-offset_12
513             NegOk = true;
514             break;
515
516           case ARM::tLDRpci:
517           case ARM::tLDRcp:
518             Bits = 8;
519             Scale = 4;  // +(offset_8*4)
520             break;
521
522           case ARM::FLDD:
523           case ARM::FLDS:
524             Bits = 8;
525             Scale = 4;  // +-(offset_8*4)
526             NegOk = true;
527             break;
528           }
529
530           // Remember that this is a user of a CP entry.
531           unsigned CPI = I->getOperand(op).getIndex();
532           MachineInstr *CPEMI = CPEMIs[CPI];
533           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
534           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
535
536           // Increment corresponding CPEntry reference count.
537           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
538           assert(CPE && "Cannot find a corresponding CPEntry!");
539           CPE->RefCount++;
540
541           // Instructions can only use one CP entry, don't bother scanning the
542           // rest of the operands.
543           break;
544         }
545     }
546
547     // In thumb mode, if this block is a constpool island, we may need padding
548     // so it's aligned on 4 byte boundary.
549     if (isThumb &&
550         !MBB.empty() &&
551         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
552         (Offset%4) != 0)
553       MBBSize += 2;
554
555     BBSizes.push_back(MBBSize);
556     BBOffsets.push_back(Offset);
557     Offset += MBBSize;
558   }
559 }
560
561 /// GetOffsetOf - Return the current offset of the specified machine instruction
562 /// from the start of the function.  This offset changes as stuff is moved
563 /// around inside the function.
564 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
565   MachineBasicBlock *MBB = MI->getParent();
566
567   // The offset is composed of two things: the sum of the sizes of all MBB's
568   // before this instruction's block, and the offset from the start of the block
569   // it is in.
570   unsigned Offset = BBOffsets[MBB->getNumber()];
571
572   // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
573   // alignment padding, and compensate if so.
574   if (isThumb &&
575       MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
576       Offset%4 != 0)
577     Offset += 2;
578
579   // Sum instructions before MI in MBB.
580   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
581     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
582     if (&*I == MI) return Offset;
583     Offset += TII->GetInstSizeInBytes(I);
584   }
585 }
586
587 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
588 /// ID.
589 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
590                               const MachineBasicBlock *RHS) {
591   return LHS->getNumber() < RHS->getNumber();
592 }
593
594 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
595 /// machine function, it upsets all of the block numbers.  Renumber the blocks
596 /// and update the arrays that parallel this numbering.
597 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
598   // Renumber the MBB's to keep them consequtive.
599   NewBB->getParent()->RenumberBlocks(NewBB);
600
601   // Insert a size into BBSizes to align it properly with the (newly
602   // renumbered) block numbers.
603   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
604
605   // Likewise for BBOffsets.
606   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
607
608   // Next, update WaterList.  Specifically, we need to add NewMBB as having
609   // available water after it.
610   std::vector<MachineBasicBlock*>::iterator IP =
611     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
612                      CompareMBBNumbers);
613   WaterList.insert(IP, NewBB);
614 }
615
616
617 /// Split the basic block containing MI into two blocks, which are joined by
618 /// an unconditional branch.  Update datastructures and renumber blocks to
619 /// account for this change and returns the newly created block.
620 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
621   MachineBasicBlock *OrigBB = MI->getParent();
622   MachineFunction &MF = *OrigBB->getParent();
623
624   // Create a new MBB for the code after the OrigBB.
625   MachineBasicBlock *NewBB =
626     MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
627   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
628   MF.insert(MBBI, NewBB);
629
630   // Splice the instructions starting with MI over to NewBB.
631   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
632
633   // Add an unconditional branch from OrigBB to NewBB.
634   // Note the new unconditional branch is not being recorded.
635   // There doesn't seem to be meaningful DebugInfo available; this doesn't
636   // correspond to anything in the source.
637   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
638   BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
639   NumSplit++;
640
641   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
642   while (!OrigBB->succ_empty()) {
643     MachineBasicBlock *Succ = *OrigBB->succ_begin();
644     OrigBB->removeSuccessor(Succ);
645     NewBB->addSuccessor(Succ);
646
647     // This pass should be run after register allocation, so there should be no
648     // PHI nodes to update.
649     assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
650            && "PHI nodes should be eliminated by now!");
651   }
652
653   // OrigBB branches to NewBB.
654   OrigBB->addSuccessor(NewBB);
655
656   // Update internal data structures to account for the newly inserted MBB.
657   // This is almost the same as UpdateForInsertedWaterBlock, except that
658   // the Water goes after OrigBB, not NewBB.
659   MF.RenumberBlocks(NewBB);
660
661   // Insert a size into BBSizes to align it properly with the (newly
662   // renumbered) block numbers.
663   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
664
665   // Likewise for BBOffsets.
666   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
667
668   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
669   // available water after it (but not if it's already there, which happens
670   // when splitting before a conditional branch that is followed by an
671   // unconditional branch - in that case we want to insert NewBB).
672   std::vector<MachineBasicBlock*>::iterator IP =
673     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
674                      CompareMBBNumbers);
675   MachineBasicBlock* WaterBB = *IP;
676   if (WaterBB == OrigBB)
677     WaterList.insert(next(IP), NewBB);
678   else
679     WaterList.insert(IP, OrigBB);
680
681   // Figure out how large the first NewMBB is.  (It cannot
682   // contain a constpool_entry or tablejump.)
683   unsigned NewBBSize = 0;
684   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
685        I != E; ++I)
686     NewBBSize += TII->GetInstSizeInBytes(I);
687
688   unsigned OrigBBI = OrigBB->getNumber();
689   unsigned NewBBI = NewBB->getNumber();
690   // Set the size of NewBB in BBSizes.
691   BBSizes[NewBBI] = NewBBSize;
692
693   // We removed instructions from UserMBB, subtract that off from its size.
694   // Add 2 or 4 to the block to count the unconditional branch we added to it.
695   int delta = isThumb1 ? 2 : 4;
696   BBSizes[OrigBBI] -= NewBBSize - delta;
697
698   // ...and adjust BBOffsets for NewBB accordingly.
699   BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
700
701   // All BBOffsets following these blocks must be modified.
702   AdjustBBOffsetsAfter(NewBB, delta);
703
704   return NewBB;
705 }
706
707 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
708 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
709 /// constant pool entry).
710 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
711                                          unsigned TrialOffset, unsigned MaxDisp,
712                                          bool NegativeOK, bool IsSoImm) {
713   // On Thumb offsets==2 mod 4 are rounded down by the hardware for
714   // purposes of the displacement computation; compensate for that here.
715   // Effectively, the valid range of displacements is 2 bytes smaller for such
716   // references.
717   unsigned TotalAdj = 0;
718   if (isThumb && UserOffset%4 !=0) {
719     UserOffset -= 2;
720     TotalAdj = 2;
721   }
722   // CPEs will be rounded up to a multiple of 4.
723   if (isThumb && TrialOffset%4 != 0) {
724     TrialOffset += 2;
725     TotalAdj += 2;
726   }
727
728   // In Thumb2 mode, later branch adjustments can shift instructions up and
729   // cause alignment change. In the worst case scenario this can cause the
730   // user's effective address to be subtracted by 2 and the CPE's address to
731   // be plus 2.
732   if (isThumb2 && TotalAdj != 4)
733     MaxDisp -= (4 - TotalAdj);
734
735   if (UserOffset <= TrialOffset) {
736     // User before the Trial.
737     if (TrialOffset - UserOffset <= MaxDisp)
738       return true;
739     // FIXME: Make use full range of soimm values.
740   } else if (NegativeOK) {
741     if (UserOffset - TrialOffset <= MaxDisp)
742       return true;
743     // FIXME: Make use full range of soimm values.
744   }
745   return false;
746 }
747
748 /// WaterIsInRange - Returns true if a CPE placed after the specified
749 /// Water (a basic block) will be in range for the specific MI.
750
751 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
752                                         MachineBasicBlock* Water, CPUser &U) {
753   unsigned MaxDisp = U.MaxDisp;
754   unsigned CPEOffset = BBOffsets[Water->getNumber()] +
755                        BBSizes[Water->getNumber()];
756
757   // If the CPE is to be inserted before the instruction, that will raise
758   // the offset of the instruction.  (Currently applies only to ARM, so
759   // no alignment compensation attempted here.)
760   if (CPEOffset < UserOffset)
761     UserOffset += U.CPEMI->getOperand(2).getImm();
762
763   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
764 }
765
766 /// CPEIsInRange - Returns true if the distance between specific MI and
767 /// specific ConstPool entry instruction can fit in MI's displacement field.
768 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
769                                       MachineInstr *CPEMI, unsigned MaxDisp,
770                                       bool NegOk, bool DoDump) {
771   unsigned CPEOffset  = GetOffsetOf(CPEMI);
772   assert(CPEOffset%4 == 0 && "Misaligned CPE");
773
774   if (DoDump) {
775     DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
776                  << " max delta=" << MaxDisp
777                  << " insn address=" << UserOffset
778                  << " CPE address=" << CPEOffset
779                  << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
780   }
781
782   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
783 }
784
785 #ifndef NDEBUG
786 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
787 /// unconditionally branches to its only successor.
788 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
789   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
790     return false;
791
792   MachineBasicBlock *Succ = *MBB->succ_begin();
793   MachineBasicBlock *Pred = *MBB->pred_begin();
794   MachineInstr *PredMI = &Pred->back();
795   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
796       || PredMI->getOpcode() == ARM::t2B)
797     return PredMI->getOperand(0).getMBB() == Succ;
798   return false;
799 }
800 #endif // NDEBUG
801
802 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
803                                               int delta) {
804   MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
805   for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
806       i < e; ++i) {
807     BBOffsets[i] += delta;
808     // If some existing blocks have padding, adjust the padding as needed, a
809     // bit tricky.  delta can be negative so don't use % on that.
810     if (!isThumb)
811       continue;
812     MachineBasicBlock *MBB = MBBI;
813     if (!MBB->empty()) {
814       // Constant pool entries require padding.
815       if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
816         unsigned OldOffset = BBOffsets[i] - delta;
817         if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
818           // add new padding
819           BBSizes[i] += 2;
820           delta += 2;
821         } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
822           // remove existing padding
823           BBSizes[i] -= 2;
824           delta -= 2;
825         }
826       }
827       // Thumb1 jump tables require padding.  They should be at the end;
828       // following unconditional branches are removed by AnalyzeBranch.
829       MachineInstr *ThumbJTMI = prior(MBB->end());
830       if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
831         unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
832         unsigned OldMIOffset = NewMIOffset - delta;
833         if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
834           // remove existing padding
835           BBSizes[i] -= 2;
836           delta -= 2;
837         } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
838           // add new padding
839           BBSizes[i] += 2;
840           delta += 2;
841         }
842       }
843       if (delta==0)
844         return;
845     }
846     MBBI = next(MBBI);
847   }
848 }
849
850 /// DecrementOldEntry - find the constant pool entry with index CPI
851 /// and instruction CPEMI, and decrement its refcount.  If the refcount
852 /// becomes 0 remove the entry and instruction.  Returns true if we removed
853 /// the entry, false if we didn't.
854
855 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
856   // Find the old entry. Eliminate it if it is no longer used.
857   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
858   assert(CPE && "Unexpected!");
859   if (--CPE->RefCount == 0) {
860     RemoveDeadCPEMI(CPEMI);
861     CPE->CPEMI = NULL;
862     NumCPEs--;
863     return true;
864   }
865   return false;
866 }
867
868 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
869 /// if not, see if an in-range clone of the CPE is in range, and if so,
870 /// change the data structures so the user references the clone.  Returns:
871 /// 0 = no existing entry found
872 /// 1 = entry found, and there were no code insertions or deletions
873 /// 2 = entry found, and there were code insertions or deletions
874 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
875 {
876   MachineInstr *UserMI = U.MI;
877   MachineInstr *CPEMI  = U.CPEMI;
878
879   // Check to see if the CPE is already in-range.
880   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
881     DOUT << "In range\n";
882     return 1;
883   }
884
885   // No.  Look for previously created clones of the CPE that are in range.
886   unsigned CPI = CPEMI->getOperand(1).getIndex();
887   std::vector<CPEntry> &CPEs = CPEntries[CPI];
888   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
889     // We already tried this one
890     if (CPEs[i].CPEMI == CPEMI)
891       continue;
892     // Removing CPEs can leave empty entries, skip
893     if (CPEs[i].CPEMI == NULL)
894       continue;
895     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
896       DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
897       // Point the CPUser node to the replacement
898       U.CPEMI = CPEs[i].CPEMI;
899       // Change the CPI in the instruction operand to refer to the clone.
900       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
901         if (UserMI->getOperand(j).isCPI()) {
902           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
903           break;
904         }
905       // Adjust the refcount of the clone...
906       CPEs[i].RefCount++;
907       // ...and the original.  If we didn't remove the old entry, none of the
908       // addresses changed, so we don't need another pass.
909       return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
910     }
911   }
912   return 0;
913 }
914
915 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
916 /// the specific unconditional branch instruction.
917 static inline unsigned getUnconditionalBrDisp(int Opc) {
918   switch (Opc) {
919   case ARM::tB:
920     return ((1<<10)-1)*2;
921   case ARM::t2B:
922     return ((1<<23)-1)*2;
923   default:
924     break;
925   }
926
927   return ((1<<23)-1)*4;
928 }
929
930 /// AcceptWater - Small amount of common code factored out of the following.
931
932 MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
933                           std::vector<MachineBasicBlock*>::iterator IP) {
934   DOUT << "found water in range\n";
935   // Remove the original WaterList entry; we want subsequent
936   // insertions in this vicinity to go after the one we're
937   // about to insert.  This considerably reduces the number
938   // of times we have to move the same CPE more than once.
939   WaterList.erase(IP);
940   // CPE goes before following block (NewMBB).
941   return next(MachineFunction::iterator(WaterBB));
942 }
943
944 /// LookForWater - look for an existing entry in the WaterList in which
945 /// we can place the CPE referenced from U so it's within range of U's MI.
946 /// Returns true if found, false if not.  If it returns true, *NewMBB
947 /// is set to the WaterList entry.
948 /// For ARM, we prefer the water that's farthest away. For Thumb, prefer
949 /// water that will not introduce padding to water that will; within each
950 /// group, prefer the water that's farthest away.
951 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
952                                       MachineBasicBlock** NewMBB) {
953   std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
954   MachineBasicBlock* WaterBBThatWouldPad = NULL;
955   if (!WaterList.empty()) {
956     for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
957            B = WaterList.begin();; --IP) {
958       MachineBasicBlock* WaterBB = *IP;
959       if (WaterIsInRange(UserOffset, WaterBB, U)) {
960         unsigned WBBId = WaterBB->getNumber();
961         if (isThumb &&
962             (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
963           // This is valid Water, but would introduce padding.  Remember
964           // it in case we don't find any Water that doesn't do this.
965           if (!WaterBBThatWouldPad) {
966             WaterBBThatWouldPad = WaterBB;
967             IPThatWouldPad = IP;
968           }
969         } else {
970           *NewMBB = AcceptWater(WaterBB, IP);
971           return true;
972         }
973       }
974       if (IP == B)
975         break;
976     }
977   }
978   if (isThumb && WaterBBThatWouldPad) {
979     *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
980     return true;
981   }
982   return false;
983 }
984
985 /// CreateNewWater - No existing WaterList entry will work for
986 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
987 /// block is used if in range, and the conditional branch munged so control
988 /// flow is correct.  Otherwise the block is split to create a hole with an
989 /// unconditional branch around it.  In either case *NewMBB is set to a
990 /// block following which the new island can be inserted (the WaterList
991 /// is not adjusted).
992
993 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
994                         unsigned UserOffset, MachineBasicBlock** NewMBB) {
995   CPUser &U = CPUsers[CPUserIndex];
996   MachineInstr *UserMI = U.MI;
997   MachineInstr *CPEMI  = U.CPEMI;
998   MachineBasicBlock *UserMBB = UserMI->getParent();
999   unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
1000                                BBSizes[UserMBB->getNumber()];
1001   assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1002
1003   // If the use is at the end of the block, or the end of the block
1004   // is within range, make new water there.  (The addition below is
1005   // for the unconditional branch we will be adding:  4 bytes on ARM + Thumb2,
1006   // 2 on Thumb1.  Possible Thumb1 alignment padding is allowed for
1007   // inside OffsetIsInRange.
1008   // If the block ends in an unconditional branch already, it is water,
1009   // and is known to be out of range, so we'll always be adding a branch.)
1010   if (&UserMBB->back() == UserMI ||
1011       OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1012                       U.MaxDisp, U.NegOk, U.IsSoImm)) {
1013     DOUT << "Split at end of block\n";
1014     if (&UserMBB->back() == UserMI)
1015       assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1016     *NewMBB = next(MachineFunction::iterator(UserMBB));
1017     // Add an unconditional branch from UserMBB to fallthrough block.
1018     // Record it for branch lengthening; this new branch will not get out of
1019     // range, but if the preceding conditional branch is out of range, the
1020     // targets will be exchanged, and the altered branch may be out of
1021     // range, so the machinery has to know about it.
1022     int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1023     BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
1024             TII->get(UncondBr)).addMBB(*NewMBB);
1025     unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1026     ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1027                           MaxDisp, false, UncondBr));
1028     int delta = isThumb1 ? 2 : 4;
1029     BBSizes[UserMBB->getNumber()] += delta;
1030     AdjustBBOffsetsAfter(UserMBB, delta);
1031   } else {
1032     // What a big block.  Find a place within the block to split it.
1033     // This is a little tricky on Thumb1 since instructions are 2 bytes
1034     // and constant pool entries are 4 bytes: if instruction I references
1035     // island CPE, and instruction I+1 references CPE', it will
1036     // not work well to put CPE as far forward as possible, since then
1037     // CPE' cannot immediately follow it (that location is 2 bytes
1038     // farther away from I+1 than CPE was from I) and we'd need to create
1039     // a new island.  So, we make a first guess, then walk through the
1040     // instructions between the one currently being looked at and the
1041     // possible insertion point, and make sure any other instructions
1042     // that reference CPEs will be able to use the same island area;
1043     // if not, we back up the insertion point.
1044
1045     // The 4 in the following is for the unconditional branch we'll be
1046     // inserting (allows for long branch on Thumb1).  Alignment of the
1047     // island is handled inside OffsetIsInRange.
1048     unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1049     // This could point off the end of the block if we've already got
1050     // constant pool entries following this block; only the last one is
1051     // in the water list.  Back past any possible branches (allow for a
1052     // conditional and a maximally long unconditional).
1053     if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1054       BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1055                               (isThumb1 ? 6 : 8);
1056     unsigned EndInsertOffset = BaseInsertOffset +
1057            CPEMI->getOperand(2).getImm();
1058     MachineBasicBlock::iterator MI = UserMI;
1059     ++MI;
1060     unsigned CPUIndex = CPUserIndex+1;
1061     for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1062          Offset < BaseInsertOffset;
1063          Offset += TII->GetInstSizeInBytes(MI),
1064             MI = next(MI)) {
1065       if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1066         CPUser &U = CPUsers[CPUIndex];
1067         if (!OffsetIsInRange(Offset, EndInsertOffset,
1068                              U.MaxDisp, U.NegOk, U.IsSoImm)) {
1069           BaseInsertOffset -= (isThumb1 ? 2 : 4);
1070           EndInsertOffset  -= (isThumb1 ? 2 : 4);
1071         }
1072         // This is overly conservative, as we don't account for CPEMIs
1073         // being reused within the block, but it doesn't matter much.
1074         EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1075         CPUIndex++;
1076       }
1077     }
1078     DOUT << "Split in middle of big block\n";
1079     *NewMBB = SplitBlockBeforeInstr(prior(MI));
1080   }
1081 }
1082
1083 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1084 /// is out-of-range.  If so, pick up the constant pool value and move it some
1085 /// place in-range.  Return true if we changed any addresses (thus must run
1086 /// another pass of branch lengthening), false otherwise.
1087 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1088                                                 unsigned CPUserIndex) {
1089   CPUser &U = CPUsers[CPUserIndex];
1090   MachineInstr *UserMI = U.MI;
1091   MachineInstr *CPEMI  = U.CPEMI;
1092   unsigned CPI = CPEMI->getOperand(1).getIndex();
1093   unsigned Size = CPEMI->getOperand(2).getImm();
1094   MachineBasicBlock *NewMBB;
1095   // Compute this only once, it's expensive.  The 4 or 8 is the value the
1096   // hardware keeps in the PC.
1097   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1098
1099   // See if the current entry is within range, or there is a clone of it
1100   // in range.
1101   int result = LookForExistingCPEntry(U, UserOffset);
1102   if (result==1) return false;
1103   else if (result==2) return true;
1104
1105   // No existing clone of this CPE is within range.
1106   // We will be generating a new clone.  Get a UID for it.
1107   unsigned ID = AFI->createConstPoolEntryUId();
1108
1109   // Look for water where we can place this CPE.  We look for the farthest one
1110   // away that will work.  Forward references only for now (although later
1111   // we might find some that are backwards).
1112
1113   if (!LookForWater(U, UserOffset, &NewMBB)) {
1114     // No water found.
1115     DOUT << "No water found\n";
1116     CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1117   }
1118
1119   // Okay, we know we can put an island before NewMBB now, do it!
1120   MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1121   MF.insert(NewMBB, NewIsland);
1122
1123   // Update internal data structures to account for the newly inserted MBB.
1124   UpdateForInsertedWaterBlock(NewIsland);
1125
1126   // Decrement the old entry, and remove it if refcount becomes 0.
1127   DecrementOldEntry(CPI, CPEMI);
1128
1129   // Now that we have an island to add the CPE to, clone the original CPE and
1130   // add it to the island.
1131   U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1132                     TII->get(ARM::CONSTPOOL_ENTRY))
1133                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1134   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1135   NumCPEs++;
1136
1137   BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1138   // Compensate for .align 2 in thumb mode.
1139   if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1140     Size += 2;
1141   // Increase the size of the island block to account for the new entry.
1142   BBSizes[NewIsland->getNumber()] += Size;
1143   AdjustBBOffsetsAfter(NewIsland, Size);
1144
1145   // Finally, change the CPI in the instruction operand to be ID.
1146   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1147     if (UserMI->getOperand(i).isCPI()) {
1148       UserMI->getOperand(i).setIndex(ID);
1149       break;
1150     }
1151
1152   DEBUG(errs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1153            << '\t' << *UserMI);
1154
1155   return true;
1156 }
1157
1158 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1159 /// sizes and offsets of impacted basic blocks.
1160 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1161   MachineBasicBlock *CPEBB = CPEMI->getParent();
1162   unsigned Size = CPEMI->getOperand(2).getImm();
1163   CPEMI->eraseFromParent();
1164   BBSizes[CPEBB->getNumber()] -= Size;
1165   // All succeeding offsets have the current size value added in, fix this.
1166   if (CPEBB->empty()) {
1167     // In thumb1 mode, the size of island may be padded by two to compensate for
1168     // the alignment requirement.  Then it will now be 2 when the block is
1169     // empty, so fix this.
1170     // All succeeding offsets have the current size value added in, fix this.
1171     if (BBSizes[CPEBB->getNumber()] != 0) {
1172       Size += BBSizes[CPEBB->getNumber()];
1173       BBSizes[CPEBB->getNumber()] = 0;
1174     }
1175   }
1176   AdjustBBOffsetsAfter(CPEBB, -Size);
1177   // An island has only one predecessor BB and one successor BB. Check if
1178   // this BB's predecessor jumps directly to this BB's successor. This
1179   // shouldn't happen currently.
1180   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1181   // FIXME: remove the empty blocks after all the work is done?
1182 }
1183
1184 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1185 /// are zero.
1186 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1187   unsigned MadeChange = false;
1188   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1189       std::vector<CPEntry> &CPEs = CPEntries[i];
1190       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1191         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1192           RemoveDeadCPEMI(CPEs[j].CPEMI);
1193           CPEs[j].CPEMI = NULL;
1194           MadeChange = true;
1195         }
1196       }
1197   }
1198   return MadeChange;
1199 }
1200
1201 /// BBIsInRange - Returns true if the distance between specific MI and
1202 /// specific BB can fit in MI's displacement field.
1203 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1204                                      unsigned MaxDisp) {
1205   unsigned PCAdj      = isThumb ? 4 : 8;
1206   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
1207   unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1208
1209   DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1210                << " from BB#" << MI->getParent()->getNumber()
1211                << " max delta=" << MaxDisp
1212                << " from " << GetOffsetOf(MI) << " to " << DestOffset
1213                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1214
1215   if (BrOffset <= DestOffset) {
1216     // Branch before the Dest.
1217     if (DestOffset-BrOffset <= MaxDisp)
1218       return true;
1219   } else {
1220     if (BrOffset-DestOffset <= MaxDisp)
1221       return true;
1222   }
1223   return false;
1224 }
1225
1226 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1227 /// away to fit in its displacement field.
1228 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1229   MachineInstr *MI = Br.MI;
1230   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1231
1232   // Check to see if the DestBB is already in-range.
1233   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1234     return false;
1235
1236   if (!Br.isCond)
1237     return FixUpUnconditionalBr(MF, Br);
1238   return FixUpConditionalBr(MF, Br);
1239 }
1240
1241 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1242 /// too far away to fit in its displacement field. If the LR register has been
1243 /// spilled in the epilogue, then we can use BL to implement a far jump.
1244 /// Otherwise, add an intermediate branch instruction to a branch.
1245 bool
1246 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1247   MachineInstr *MI = Br.MI;
1248   MachineBasicBlock *MBB = MI->getParent();
1249   if (!isThumb1)
1250     llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1251
1252   // Use BL to implement far jump.
1253   Br.MaxDisp = (1 << 21) * 2;
1254   MI->setDesc(TII->get(ARM::tBfar));
1255   BBSizes[MBB->getNumber()] += 2;
1256   AdjustBBOffsetsAfter(MBB, 2);
1257   HasFarJump = true;
1258   NumUBrFixed++;
1259
1260   DEBUG(errs() << "  Changed B to long jump " << *MI);
1261
1262   return true;
1263 }
1264
1265 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1266 /// far away to fit in its displacement field. It is converted to an inverse
1267 /// conditional branch + an unconditional branch to the destination.
1268 bool
1269 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1270   MachineInstr *MI = Br.MI;
1271   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1272
1273   // Add an unconditional branch to the destination and invert the branch
1274   // condition to jump over it:
1275   // blt L1
1276   // =>
1277   // bge L2
1278   // b   L1
1279   // L2:
1280   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1281   CC = ARMCC::getOppositeCondition(CC);
1282   unsigned CCReg = MI->getOperand(2).getReg();
1283
1284   // If the branch is at the end of its MBB and that has a fall-through block,
1285   // direct the updated conditional branch to the fall-through block. Otherwise,
1286   // split the MBB before the next instruction.
1287   MachineBasicBlock *MBB = MI->getParent();
1288   MachineInstr *BMI = &MBB->back();
1289   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1290
1291   NumCBrFixed++;
1292   if (BMI != MI) {
1293     if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1294         BMI->getOpcode() == Br.UncondBr) {
1295       // Last MI in the BB is an unconditional branch. Can we simply invert the
1296       // condition and swap destinations:
1297       // beq L1
1298       // b   L2
1299       // =>
1300       // bne L2
1301       // b   L1
1302       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1303       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1304         DEBUG(errs() << "  Invert Bcc condition and swap its destination with "
1305                      << *BMI);
1306         BMI->getOperand(0).setMBB(DestBB);
1307         MI->getOperand(0).setMBB(NewDest);
1308         MI->getOperand(1).setImm(CC);
1309         return true;
1310       }
1311     }
1312   }
1313
1314   if (NeedSplit) {
1315     SplitBlockBeforeInstr(MI);
1316     // No need for the branch to the next block. We're adding an unconditional
1317     // branch to the destination.
1318     int delta = TII->GetInstSizeInBytes(&MBB->back());
1319     BBSizes[MBB->getNumber()] -= delta;
1320     MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1321     AdjustBBOffsetsAfter(SplitBB, -delta);
1322     MBB->back().eraseFromParent();
1323     // BBOffsets[SplitBB] is wrong temporarily, fixed below
1324   }
1325   MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1326
1327   DOUT << "  Insert B to BB#" << DestBB->getNumber()
1328        << " also invert condition and change dest. to BB#"
1329        << NextBB->getNumber() << "\n";
1330
1331   // Insert a new conditional branch and a new unconditional branch.
1332   // Also update the ImmBranch as well as adding a new entry for the new branch.
1333   BuildMI(MBB, DebugLoc::getUnknownLoc(),
1334           TII->get(MI->getOpcode()))
1335     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1336   Br.MI = &MBB->back();
1337   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1338   BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1339   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1340   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1341   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1342
1343   // Remove the old conditional branch.  It may or may not still be in MBB.
1344   BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1345   MI->eraseFromParent();
1346
1347   // The net size change is an addition of one unconditional branch.
1348   int delta = TII->GetInstSizeInBytes(&MBB->back());
1349   AdjustBBOffsetsAfter(MBB, delta);
1350   return true;
1351 }
1352
1353 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1354 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1355 /// to do this if tBfar is not used.
1356 bool ARMConstantIslands::UndoLRSpillRestore() {
1357   bool MadeChange = false;
1358   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1359     MachineInstr *MI = PushPopMIs[i];
1360     if (MI->getOpcode() == ARM::tPOP_RET &&
1361         MI->getOperand(2).getReg() == ARM::PC &&
1362         MI->getNumExplicitOperands() == 3) {
1363       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1364       MI->eraseFromParent();
1365       MadeChange = true;
1366     }
1367   }
1368   return MadeChange;
1369 }
1370
1371 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1372   bool MadeChange = false;
1373
1374   // Shrink ADR and LDR from constantpool.
1375   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1376     CPUser &U = CPUsers[i];
1377     unsigned Opcode = U.MI->getOpcode();
1378     unsigned NewOpc = 0;
1379     unsigned Scale = 1;
1380     unsigned Bits = 0;
1381     switch (Opcode) {
1382     default: break;
1383     case ARM::t2LEApcrel:
1384       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1385         NewOpc = ARM::tLEApcrel;
1386         Bits = 8;
1387         Scale = 4;
1388       }
1389       break;
1390     case ARM::t2LDRpci:
1391       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1392         NewOpc = ARM::tLDRpci;
1393         Bits = 8;
1394         Scale = 4;
1395       }
1396       break;
1397     }
1398
1399     if (!NewOpc)
1400       continue;
1401
1402     unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1403     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1404     // FIXME: Check if offset is multiple of scale if scale is not 4.
1405     if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1406       U.MI->setDesc(TII->get(NewOpc));
1407       MachineBasicBlock *MBB = U.MI->getParent();
1408       BBSizes[MBB->getNumber()] -= 2;
1409       AdjustBBOffsetsAfter(MBB, -2);
1410       ++NumT2CPShrunk;
1411       MadeChange = true;
1412     }
1413   }
1414
1415   MadeChange |= OptimizeThumb2Branches(MF);
1416   MadeChange |= OptimizeThumb2JumpTables(MF);
1417   return MadeChange;
1418 }
1419
1420 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1421   bool MadeChange = false;
1422
1423   for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1424     ImmBranch &Br = ImmBranches[i];
1425     unsigned Opcode = Br.MI->getOpcode();
1426     unsigned NewOpc = 0;
1427     unsigned Scale = 1;
1428     unsigned Bits = 0;
1429     switch (Opcode) {
1430     default: break;
1431     case ARM::t2B:
1432       NewOpc = ARM::tB;
1433       Bits = 11;
1434       Scale = 2;
1435       break;
1436     case ARM::t2Bcc:
1437       NewOpc = ARM::tBcc;
1438       Bits = 8;
1439       Scale = 2;      
1440       break;
1441     }
1442     if (!NewOpc)
1443       continue;
1444
1445     unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1446     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1447     if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1448       Br.MI->setDesc(TII->get(NewOpc));
1449       MachineBasicBlock *MBB = Br.MI->getParent();
1450       BBSizes[MBB->getNumber()] -= 2;
1451       AdjustBBOffsetsAfter(MBB, -2);
1452       ++NumT2BrShrunk;
1453       MadeChange = true;
1454     }
1455   }
1456
1457   return MadeChange;
1458 }
1459
1460
1461 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1462 /// jumptables when it's possible.
1463 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1464   bool MadeChange = false;
1465
1466   // FIXME: After the tables are shrunk, can we get rid some of the
1467   // constantpool tables?
1468   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1469   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1470   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1471     MachineInstr *MI = T2JumpTables[i];
1472     const TargetInstrDesc &TID = MI->getDesc();
1473     unsigned NumOps = TID.getNumOperands();
1474     unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1475     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1476     unsigned JTI = JTOP.getIndex();
1477     assert(JTI < JT.size());
1478
1479     bool ByteOk = true;
1480     bool HalfWordOk = true;
1481     unsigned JTOffset = GetOffsetOf(MI) + 4;
1482     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1483     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1484       MachineBasicBlock *MBB = JTBBs[j];
1485       unsigned DstOffset = BBOffsets[MBB->getNumber()];
1486       // Negative offset is not ok. FIXME: We should change BB layout to make
1487       // sure all the branches are forward.
1488       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1489         ByteOk = false;
1490       unsigned TBHLimit = ((1<<16)-1)*2;
1491       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1492         HalfWordOk = false;
1493       if (!ByteOk && !HalfWordOk)
1494         break;
1495     }
1496
1497     if (ByteOk || HalfWordOk) {
1498       MachineBasicBlock *MBB = MI->getParent();
1499       unsigned BaseReg = MI->getOperand(0).getReg();
1500       bool BaseRegKill = MI->getOperand(0).isKill();
1501       if (!BaseRegKill)
1502         continue;
1503       unsigned IdxReg = MI->getOperand(1).getReg();
1504       bool IdxRegKill = MI->getOperand(1).isKill();
1505       MachineBasicBlock::iterator PrevI = MI;
1506       if (PrevI == MBB->begin())
1507         continue;
1508
1509       MachineInstr *AddrMI = --PrevI;
1510       bool OptOk = true;
1511       // Examine the instruction that calculate the jumptable entry address.
1512       // If it's not the one just before the t2BR_JT, we won't delete it, then
1513       // it's not worth doing the optimization.
1514       for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1515         const MachineOperand &MO = AddrMI->getOperand(k);
1516         if (!MO.isReg() || !MO.getReg())
1517           continue;
1518         if (MO.isDef() && MO.getReg() != BaseReg) {
1519           OptOk = false;
1520           break;
1521         }
1522         if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1523           OptOk = false;
1524           break;
1525         }
1526       }
1527       if (!OptOk)
1528         continue;
1529
1530       // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1531       // to delete it as well.
1532       MachineInstr *LeaMI = --PrevI;
1533       if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1534            LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1535           LeaMI->getOperand(0).getReg() != BaseReg)
1536         OptOk = false;
1537
1538       if (!OptOk)
1539         continue;
1540
1541       unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1542       MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1543         .addReg(IdxReg, getKillRegState(IdxRegKill))
1544         .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1545         .addImm(MI->getOperand(JTOpIdx+1).getImm());
1546       // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1547       // is 2-byte aligned. For now, asm printer will fix it up.
1548       unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1549       unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1550       OrigSize += TII->GetInstSizeInBytes(LeaMI);
1551       OrigSize += TII->GetInstSizeInBytes(MI);
1552
1553       AddrMI->eraseFromParent();
1554       LeaMI->eraseFromParent();
1555       MI->eraseFromParent();
1556
1557       int delta = OrigSize - NewSize;
1558       BBSizes[MBB->getNumber()] -= delta;
1559       AdjustBBOffsetsAfter(MBB, -delta);
1560
1561       ++NumTBs;
1562       MadeChange = true;
1563     }
1564   }
1565
1566   return MadeChange;
1567 }