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