3be6d1c821a4a06cdfd25253ef9c34479c5d20ff
[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       // Add instruction size to MBBSize.
496       MBBSize += TII->GetInstSizeInBytes(I);
497
498       int Opc = I->getOpcode();
499       if (I->getDesc().isBranch()) {
500         bool isCond = false;
501         unsigned Bits = 0;
502         unsigned Scale = 1;
503         int UOpc = Opc;
504         switch (Opc) {
505         default:
506           continue;  // Ignore other JT branches
507         case ARM::tBR_JTr:
508           // A Thumb1 table jump may involve padding; for the offsets to
509           // be right, functions containing these must be 4-byte aligned.
510           MF.EnsureAlignment(2U);
511           if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
512             // FIXME: Add a pseudo ALIGN instruction instead.
513             MBBSize += 2;           // padding
514           continue;   // Does not get an entry in ImmBranches
515         case ARM::t2BR_JT:
516           T2JumpTables.push_back(I);
517           continue;   // Does not get an entry in ImmBranches
518         case ARM::Bcc:
519           isCond = true;
520           UOpc = ARM::B;
521           // Fallthrough
522         case ARM::B:
523           Bits = 24;
524           Scale = 4;
525           break;
526         case ARM::tBcc:
527           isCond = true;
528           UOpc = ARM::tB;
529           Bits = 8;
530           Scale = 2;
531           break;
532         case ARM::tB:
533           Bits = 11;
534           Scale = 2;
535           break;
536         case ARM::t2Bcc:
537           isCond = true;
538           UOpc = ARM::t2B;
539           Bits = 20;
540           Scale = 2;
541           break;
542         case ARM::t2B:
543           Bits = 24;
544           Scale = 2;
545           break;
546         }
547
548         // Record this immediate branch.
549         unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
550         ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
551       }
552
553       if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
554         PushPopMIs.push_back(I);
555
556       if (Opc == ARM::CONSTPOOL_ENTRY)
557         continue;
558
559       // Scan the instructions for constant pool operands.
560       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
561         if (I->getOperand(op).isCPI()) {
562           // We found one.  The addressing mode tells us the max displacement
563           // from the PC that this instruction permits.
564
565           // Basic size info comes from the TSFlags field.
566           unsigned Bits = 0;
567           unsigned Scale = 1;
568           bool NegOk = false;
569           bool IsSoImm = false;
570
571           switch (Opc) {
572           default:
573             llvm_unreachable("Unknown addressing mode for CP reference!");
574             break;
575
576           // Taking the address of a CP entry.
577           case ARM::LEApcrel:
578             // This takes a SoImm, which is 8 bit immediate rotated. We'll
579             // pretend the maximum offset is 255 * 4. Since each instruction
580             // 4 byte wide, this is always correct. We'll check for other
581             // displacements that fits in a SoImm as well.
582             Bits = 8;
583             Scale = 4;
584             NegOk = true;
585             IsSoImm = true;
586             break;
587           case ARM::t2LEApcrel:
588             Bits = 12;
589             NegOk = true;
590             break;
591           case ARM::tLEApcrel:
592             Bits = 8;
593             Scale = 4;
594             break;
595
596           case ARM::LDR:
597           case ARM::LDRcp:
598           case ARM::t2LDRpci:
599             Bits = 12;  // +-offset_12
600             NegOk = true;
601             break;
602
603           case ARM::tLDRpci:
604           case ARM::tLDRcp:
605             Bits = 8;
606             Scale = 4;  // +(offset_8*4)
607             break;
608
609           case ARM::VLDRD:
610           case ARM::VLDRS:
611             Bits = 8;
612             Scale = 4;  // +-(offset_8*4)
613             NegOk = true;
614             break;
615           }
616
617           // Remember that this is a user of a CP entry.
618           unsigned CPI = I->getOperand(op).getIndex();
619           MachineInstr *CPEMI = CPEMIs[CPI];
620           unsigned MaxOffs = ((1 << Bits)-1) * Scale;
621           CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
622
623           // Increment corresponding CPEntry reference count.
624           CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
625           assert(CPE && "Cannot find a corresponding CPEntry!");
626           CPE->RefCount++;
627
628           // Instructions can only use one CP entry, don't bother scanning the
629           // rest of the operands.
630           break;
631         }
632     }
633
634     // In thumb mode, if this block is a constpool island, we may need padding
635     // so it's aligned on 4 byte boundary.
636     if (isThumb &&
637         !MBB.empty() &&
638         MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
639         ((Offset%4) != 0 || HasInlineAsm))
640       MBBSize += 2;
641
642     BBSizes.push_back(MBBSize);
643     BBOffsets.push_back(Offset);
644     Offset += MBBSize;
645   }
646 }
647
648 /// GetOffsetOf - Return the current offset of the specified machine instruction
649 /// from the start of the function.  This offset changes as stuff is moved
650 /// around inside the function.
651 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
652   MachineBasicBlock *MBB = MI->getParent();
653
654   // The offset is composed of two things: the sum of the sizes of all MBB's
655   // before this instruction's block, and the offset from the start of the block
656   // it is in.
657   unsigned Offset = BBOffsets[MBB->getNumber()];
658
659   // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
660   // alignment padding, and compensate if so.
661   if (isThumb &&
662       MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
663       (Offset%4 != 0 || HasInlineAsm))
664     Offset += 2;
665
666   // Sum instructions before MI in MBB.
667   for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
668     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
669     if (&*I == MI) return Offset;
670     Offset += TII->GetInstSizeInBytes(I);
671   }
672 }
673
674 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
675 /// ID.
676 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
677                               const MachineBasicBlock *RHS) {
678   return LHS->getNumber() < RHS->getNumber();
679 }
680
681 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
682 /// machine function, it upsets all of the block numbers.  Renumber the blocks
683 /// and update the arrays that parallel this numbering.
684 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
685   // Renumber the MBB's to keep them consequtive.
686   NewBB->getParent()->RenumberBlocks(NewBB);
687
688   // Insert a size into BBSizes to align it properly with the (newly
689   // renumbered) block numbers.
690   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
691
692   // Likewise for BBOffsets.
693   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
694
695   // Next, update WaterList.  Specifically, we need to add NewMBB as having
696   // available water after it.
697   water_iterator IP =
698     std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
699                      CompareMBBNumbers);
700   WaterList.insert(IP, NewBB);
701 }
702
703
704 /// Split the basic block containing MI into two blocks, which are joined by
705 /// an unconditional branch.  Update data structures and renumber blocks to
706 /// account for this change and returns the newly created block.
707 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
708   MachineBasicBlock *OrigBB = MI->getParent();
709   MachineFunction &MF = *OrigBB->getParent();
710
711   // Create a new MBB for the code after the OrigBB.
712   MachineBasicBlock *NewBB =
713     MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
714   MachineFunction::iterator MBBI = OrigBB; ++MBBI;
715   MF.insert(MBBI, NewBB);
716
717   // Splice the instructions starting with MI over to NewBB.
718   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
719
720   // Add an unconditional branch from OrigBB to NewBB.
721   // Note the new unconditional branch is not being recorded.
722   // There doesn't seem to be meaningful DebugInfo available; this doesn't
723   // correspond to anything in the source.
724   unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
725   BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
726   NumSplit++;
727
728   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
729   while (!OrigBB->succ_empty()) {
730     MachineBasicBlock *Succ = *OrigBB->succ_begin();
731     OrigBB->removeSuccessor(Succ);
732     NewBB->addSuccessor(Succ);
733
734     // This pass should be run after register allocation, so there should be no
735     // PHI nodes to update.
736     assert((Succ->empty() || !Succ->begin()->isPHI())
737            && "PHI nodes should be eliminated by now!");
738   }
739
740   // OrigBB branches to NewBB.
741   OrigBB->addSuccessor(NewBB);
742
743   // Update internal data structures to account for the newly inserted MBB.
744   // This is almost the same as UpdateForInsertedWaterBlock, except that
745   // the Water goes after OrigBB, not NewBB.
746   MF.RenumberBlocks(NewBB);
747
748   // Insert a size into BBSizes to align it properly with the (newly
749   // renumbered) block numbers.
750   BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
751
752   // Likewise for BBOffsets.
753   BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
754
755   // Next, update WaterList.  Specifically, we need to add OrigMBB as having
756   // available water after it (but not if it's already there, which happens
757   // when splitting before a conditional branch that is followed by an
758   // unconditional branch - in that case we want to insert NewBB).
759   water_iterator IP =
760     std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
761                      CompareMBBNumbers);
762   MachineBasicBlock* WaterBB = *IP;
763   if (WaterBB == OrigBB)
764     WaterList.insert(llvm::next(IP), NewBB);
765   else
766     WaterList.insert(IP, OrigBB);
767   NewWaterList.insert(OrigBB);
768
769   // Figure out how large the first NewMBB is.  (It cannot
770   // contain a constpool_entry or tablejump.)
771   unsigned NewBBSize = 0;
772   for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
773        I != E; ++I)
774     NewBBSize += TII->GetInstSizeInBytes(I);
775
776   unsigned OrigBBI = OrigBB->getNumber();
777   unsigned NewBBI = NewBB->getNumber();
778   // Set the size of NewBB in BBSizes.
779   BBSizes[NewBBI] = NewBBSize;
780
781   // We removed instructions from UserMBB, subtract that off from its size.
782   // Add 2 or 4 to the block to count the unconditional branch we added to it.
783   int delta = isThumb1 ? 2 : 4;
784   BBSizes[OrigBBI] -= NewBBSize - delta;
785
786   // ...and adjust BBOffsets for NewBB accordingly.
787   BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
788
789   // All BBOffsets following these blocks must be modified.
790   AdjustBBOffsetsAfter(NewBB, delta);
791
792   return NewBB;
793 }
794
795 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
796 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
797 /// constant pool entry).
798 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
799                                          unsigned TrialOffset, unsigned MaxDisp,
800                                          bool NegativeOK, bool IsSoImm) {
801   // On Thumb offsets==2 mod 4 are rounded down by the hardware for
802   // purposes of the displacement computation; compensate for that here.
803   // Effectively, the valid range of displacements is 2 bytes smaller for such
804   // references.
805   unsigned TotalAdj = 0;
806   if (isThumb && UserOffset%4 !=0) {
807     UserOffset -= 2;
808     TotalAdj = 2;
809   }
810   // CPEs will be rounded up to a multiple of 4.
811   if (isThumb && TrialOffset%4 != 0) {
812     TrialOffset += 2;
813     TotalAdj += 2;
814   }
815
816   // In Thumb2 mode, later branch adjustments can shift instructions up and
817   // cause alignment change. In the worst case scenario this can cause the
818   // user's effective address to be subtracted by 2 and the CPE's address to
819   // be plus 2.
820   if (isThumb2 && TotalAdj != 4)
821     MaxDisp -= (4 - TotalAdj);
822
823   if (UserOffset <= TrialOffset) {
824     // User before the Trial.
825     if (TrialOffset - UserOffset <= MaxDisp)
826       return true;
827     // FIXME: Make use full range of soimm values.
828   } else if (NegativeOK) {
829     if (UserOffset - TrialOffset <= MaxDisp)
830       return true;
831     // FIXME: Make use full range of soimm values.
832   }
833   return false;
834 }
835
836 /// WaterIsInRange - Returns true if a CPE placed after the specified
837 /// Water (a basic block) will be in range for the specific MI.
838
839 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
840                                         MachineBasicBlock* Water, CPUser &U) {
841   unsigned MaxDisp = U.MaxDisp;
842   unsigned CPEOffset = BBOffsets[Water->getNumber()] +
843                        BBSizes[Water->getNumber()];
844
845   // If the CPE is to be inserted before the instruction, that will raise
846   // the offset of the instruction.
847   if (CPEOffset < UserOffset)
848     UserOffset += U.CPEMI->getOperand(2).getImm();
849
850   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
851 }
852
853 /// CPEIsInRange - Returns true if the distance between specific MI and
854 /// specific ConstPool entry instruction can fit in MI's displacement field.
855 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
856                                       MachineInstr *CPEMI, unsigned MaxDisp,
857                                       bool NegOk, bool DoDump) {
858   unsigned CPEOffset  = GetOffsetOf(CPEMI);
859   assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
860
861   if (DoDump) {
862     DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
863                  << " max delta=" << MaxDisp
864                  << " insn address=" << UserOffset
865                  << " CPE address=" << CPEOffset
866                  << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
867   }
868
869   return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
870 }
871
872 #ifndef NDEBUG
873 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
874 /// unconditionally branches to its only successor.
875 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
876   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
877     return false;
878
879   MachineBasicBlock *Succ = *MBB->succ_begin();
880   MachineBasicBlock *Pred = *MBB->pred_begin();
881   MachineInstr *PredMI = &Pred->back();
882   if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
883       || PredMI->getOpcode() == ARM::t2B)
884     return PredMI->getOperand(0).getMBB() == Succ;
885   return false;
886 }
887 #endif // NDEBUG
888
889 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
890                                               int delta) {
891   MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
892   for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
893       i < e; ++i) {
894     BBOffsets[i] += delta;
895     // If some existing blocks have padding, adjust the padding as needed, a
896     // bit tricky.  delta can be negative so don't use % on that.
897     if (!isThumb)
898       continue;
899     MachineBasicBlock *MBB = MBBI;
900     if (!MBB->empty() && !HasInlineAsm) {
901       // Constant pool entries require padding.
902       if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
903         unsigned OldOffset = BBOffsets[i] - delta;
904         if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
905           // add new padding
906           BBSizes[i] += 2;
907           delta += 2;
908         } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
909           // remove existing padding
910           BBSizes[i] -= 2;
911           delta -= 2;
912         }
913       }
914       // Thumb1 jump tables require padding.  They should be at the end;
915       // following unconditional branches are removed by AnalyzeBranch.
916       MachineInstr *ThumbJTMI = prior(MBB->end());
917       if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
918         unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
919         unsigned OldMIOffset = NewMIOffset - delta;
920         if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
921           // remove existing padding
922           BBSizes[i] -= 2;
923           delta -= 2;
924         } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
925           // add new padding
926           BBSizes[i] += 2;
927           delta += 2;
928         }
929       }
930       if (delta==0)
931         return;
932     }
933     MBBI = llvm::next(MBBI);
934   }
935 }
936
937 /// DecrementOldEntry - find the constant pool entry with index CPI
938 /// and instruction CPEMI, and decrement its refcount.  If the refcount
939 /// becomes 0 remove the entry and instruction.  Returns true if we removed
940 /// the entry, false if we didn't.
941
942 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
943   // Find the old entry. Eliminate it if it is no longer used.
944   CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
945   assert(CPE && "Unexpected!");
946   if (--CPE->RefCount == 0) {
947     RemoveDeadCPEMI(CPEMI);
948     CPE->CPEMI = NULL;
949     NumCPEs--;
950     return true;
951   }
952   return false;
953 }
954
955 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
956 /// if not, see if an in-range clone of the CPE is in range, and if so,
957 /// change the data structures so the user references the clone.  Returns:
958 /// 0 = no existing entry found
959 /// 1 = entry found, and there were no code insertions or deletions
960 /// 2 = entry found, and there were code insertions or deletions
961 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
962 {
963   MachineInstr *UserMI = U.MI;
964   MachineInstr *CPEMI  = U.CPEMI;
965
966   // Check to see if the CPE is already in-range.
967   if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
968     DEBUG(errs() << "In range\n");
969     return 1;
970   }
971
972   // No.  Look for previously created clones of the CPE that are in range.
973   unsigned CPI = CPEMI->getOperand(1).getIndex();
974   std::vector<CPEntry> &CPEs = CPEntries[CPI];
975   for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
976     // We already tried this one
977     if (CPEs[i].CPEMI == CPEMI)
978       continue;
979     // Removing CPEs can leave empty entries, skip
980     if (CPEs[i].CPEMI == NULL)
981       continue;
982     if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
983       DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
984                    << CPEs[i].CPI << "\n");
985       // Point the CPUser node to the replacement
986       U.CPEMI = CPEs[i].CPEMI;
987       // Change the CPI in the instruction operand to refer to the clone.
988       for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
989         if (UserMI->getOperand(j).isCPI()) {
990           UserMI->getOperand(j).setIndex(CPEs[i].CPI);
991           break;
992         }
993       // Adjust the refcount of the clone...
994       CPEs[i].RefCount++;
995       // ...and the original.  If we didn't remove the old entry, none of the
996       // addresses changed, so we don't need another pass.
997       return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
998     }
999   }
1000   return 0;
1001 }
1002
1003 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1004 /// the specific unconditional branch instruction.
1005 static inline unsigned getUnconditionalBrDisp(int Opc) {
1006   switch (Opc) {
1007   case ARM::tB:
1008     return ((1<<10)-1)*2;
1009   case ARM::t2B:
1010     return ((1<<23)-1)*2;
1011   default:
1012     break;
1013   }
1014
1015   return ((1<<23)-1)*4;
1016 }
1017
1018 /// LookForWater - Look for an existing entry in the WaterList in which
1019 /// we can place the CPE referenced from U so it's within range of U's MI.
1020 /// Returns true if found, false if not.  If it returns true, WaterIter
1021 /// is set to the WaterList entry.  For Thumb, prefer water that will not
1022 /// introduce padding to water that will.  To ensure that this pass
1023 /// terminates, the CPE location for a particular CPUser is only allowed to
1024 /// move to a lower address, so search backward from the end of the list and
1025 /// prefer the first water that is in range.
1026 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1027                                       water_iterator &WaterIter) {
1028   if (WaterList.empty())
1029     return false;
1030
1031   bool FoundWaterThatWouldPad = false;
1032   water_iterator IPThatWouldPad;
1033   for (water_iterator IP = prior(WaterList.end()),
1034          B = WaterList.begin();; --IP) {
1035     MachineBasicBlock* WaterBB = *IP;
1036     // Check if water is in range and is either at a lower address than the
1037     // current "high water mark" or a new water block that was created since
1038     // the previous iteration by inserting an unconditional branch.  In the
1039     // latter case, we want to allow resetting the high water mark back to
1040     // this new water since we haven't seen it before.  Inserting branches
1041     // should be relatively uncommon and when it does happen, we want to be
1042     // sure to take advantage of it for all the CPEs near that block, so that
1043     // we don't insert more branches than necessary.
1044     if (WaterIsInRange(UserOffset, WaterBB, U) &&
1045         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1046          NewWaterList.count(WaterBB))) {
1047       unsigned WBBId = WaterBB->getNumber();
1048       if (isThumb &&
1049           (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1050         // This is valid Water, but would introduce padding.  Remember
1051         // it in case we don't find any Water that doesn't do this.
1052         if (!FoundWaterThatWouldPad) {
1053           FoundWaterThatWouldPad = true;
1054           IPThatWouldPad = IP;
1055         }
1056       } else {
1057         WaterIter = IP;
1058         return true;
1059       }
1060     }
1061     if (IP == B)
1062       break;
1063   }
1064   if (FoundWaterThatWouldPad) {
1065     WaterIter = IPThatWouldPad;
1066     return true;
1067   }
1068   return false;
1069 }
1070
1071 /// CreateNewWater - No existing WaterList entry will work for
1072 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
1073 /// block is used if in range, and the conditional branch munged so control
1074 /// flow is correct.  Otherwise the block is split to create a hole with an
1075 /// unconditional branch around it.  In either case NewMBB is set to a
1076 /// block following which the new island can be inserted (the WaterList
1077 /// is not adjusted).
1078 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1079                                         unsigned UserOffset,
1080                                         MachineBasicBlock *&NewMBB) {
1081   CPUser &U = CPUsers[CPUserIndex];
1082   MachineInstr *UserMI = U.MI;
1083   MachineInstr *CPEMI  = U.CPEMI;
1084   MachineBasicBlock *UserMBB = UserMI->getParent();
1085   unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
1086                                BBSizes[UserMBB->getNumber()];
1087   assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1088
1089   // If the block does not end in an unconditional branch already, and if the
1090   // end of the block is within range, make new water there.  (The addition
1091   // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1092   // Thumb2, 2 on Thumb1.  Possible Thumb1 alignment padding is allowed for
1093   // inside OffsetIsInRange.
1094   if (BBHasFallthrough(UserMBB) &&
1095       OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1096                       U.MaxDisp, U.NegOk, U.IsSoImm)) {
1097     DEBUG(errs() << "Split at end of block\n");
1098     if (&UserMBB->back() == UserMI)
1099       assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1100     NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1101     // Add an unconditional branch from UserMBB to fallthrough block.
1102     // Record it for branch lengthening; this new branch will not get out of
1103     // range, but if the preceding conditional branch is out of range, the
1104     // targets will be exchanged, and the altered branch may be out of
1105     // range, so the machinery has to know about it.
1106     int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1107     BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1108     unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1109     ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1110                           MaxDisp, false, UncondBr));
1111     int delta = isThumb1 ? 2 : 4;
1112     BBSizes[UserMBB->getNumber()] += delta;
1113     AdjustBBOffsetsAfter(UserMBB, delta);
1114   } else {
1115     // What a big block.  Find a place within the block to split it.
1116     // This is a little tricky on Thumb1 since instructions are 2 bytes
1117     // and constant pool entries are 4 bytes: if instruction I references
1118     // island CPE, and instruction I+1 references CPE', it will
1119     // not work well to put CPE as far forward as possible, since then
1120     // CPE' cannot immediately follow it (that location is 2 bytes
1121     // farther away from I+1 than CPE was from I) and we'd need to create
1122     // a new island.  So, we make a first guess, then walk through the
1123     // instructions between the one currently being looked at and the
1124     // possible insertion point, and make sure any other instructions
1125     // that reference CPEs will be able to use the same island area;
1126     // if not, we back up the insertion point.
1127
1128     // The 4 in the following is for the unconditional branch we'll be
1129     // inserting (allows for long branch on Thumb1).  Alignment of the
1130     // island is handled inside OffsetIsInRange.
1131     unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1132     // This could point off the end of the block if we've already got
1133     // constant pool entries following this block; only the last one is
1134     // in the water list.  Back past any possible branches (allow for a
1135     // conditional and a maximally long unconditional).
1136     if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1137       BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1138                               (isThumb1 ? 6 : 8);
1139     unsigned EndInsertOffset = BaseInsertOffset +
1140            CPEMI->getOperand(2).getImm();
1141     MachineBasicBlock::iterator MI = UserMI;
1142     ++MI;
1143     unsigned CPUIndex = CPUserIndex+1;
1144     for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1145          Offset < BaseInsertOffset;
1146          Offset += TII->GetInstSizeInBytes(MI),
1147             MI = llvm::next(MI)) {
1148       if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1149         CPUser &U = CPUsers[CPUIndex];
1150         if (!OffsetIsInRange(Offset, EndInsertOffset,
1151                              U.MaxDisp, U.NegOk, U.IsSoImm)) {
1152           BaseInsertOffset -= (isThumb1 ? 2 : 4);
1153           EndInsertOffset  -= (isThumb1 ? 2 : 4);
1154         }
1155         // This is overly conservative, as we don't account for CPEMIs
1156         // being reused within the block, but it doesn't matter much.
1157         EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1158         CPUIndex++;
1159       }
1160     }
1161     DEBUG(errs() << "Split in middle of big block\n");
1162     NewMBB = SplitBlockBeforeInstr(prior(MI));
1163   }
1164 }
1165
1166 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1167 /// is out-of-range.  If so, pick up the constant pool value and move it some
1168 /// place in-range.  Return true if we changed any addresses (thus must run
1169 /// another pass of branch lengthening), false otherwise.
1170 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1171                                                 unsigned CPUserIndex) {
1172   CPUser &U = CPUsers[CPUserIndex];
1173   MachineInstr *UserMI = U.MI;
1174   MachineInstr *CPEMI  = U.CPEMI;
1175   unsigned CPI = CPEMI->getOperand(1).getIndex();
1176   unsigned Size = CPEMI->getOperand(2).getImm();
1177   // Compute this only once, it's expensive.  The 4 or 8 is the value the
1178   // hardware keeps in the PC.
1179   unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1180
1181   // See if the current entry is within range, or there is a clone of it
1182   // in range.
1183   int result = LookForExistingCPEntry(U, UserOffset);
1184   if (result==1) return false;
1185   else if (result==2) return true;
1186
1187   // No existing clone of this CPE is within range.
1188   // We will be generating a new clone.  Get a UID for it.
1189   unsigned ID = AFI->createConstPoolEntryUId();
1190
1191   // Look for water where we can place this CPE.
1192   MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1193   MachineBasicBlock *NewMBB;
1194   water_iterator IP;
1195   if (LookForWater(U, UserOffset, IP)) {
1196     DEBUG(errs() << "found water in range\n");
1197     MachineBasicBlock *WaterBB = *IP;
1198
1199     // If the original WaterList entry was "new water" on this iteration,
1200     // propagate that to the new island.  This is just keeping NewWaterList
1201     // updated to match the WaterList, which will be updated below.
1202     if (NewWaterList.count(WaterBB)) {
1203       NewWaterList.erase(WaterBB);
1204       NewWaterList.insert(NewIsland);
1205     }
1206     // The new CPE goes before the following block (NewMBB).
1207     NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1208
1209   } else {
1210     // No water found.
1211     DEBUG(errs() << "No water found\n");
1212     CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1213
1214     // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1215     // called while handling branches so that the water will be seen on the
1216     // next iteration for constant pools, but in this context, we don't want
1217     // it.  Check for this so it will be removed from the WaterList.
1218     // Also remove any entry from NewWaterList.
1219     MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1220     IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1221     if (IP != WaterList.end())
1222       NewWaterList.erase(WaterBB);
1223
1224     // We are adding new water.  Update NewWaterList.
1225     NewWaterList.insert(NewIsland);
1226   }
1227
1228   // Remove the original WaterList entry; we want subsequent insertions in
1229   // this vicinity to go after the one we're about to insert.  This
1230   // considerably reduces the number of times we have to move the same CPE
1231   // more than once and is also important to ensure the algorithm terminates.
1232   if (IP != WaterList.end())
1233     WaterList.erase(IP);
1234
1235   // Okay, we know we can put an island before NewMBB now, do it!
1236   MF.insert(NewMBB, NewIsland);
1237
1238   // Update internal data structures to account for the newly inserted MBB.
1239   UpdateForInsertedWaterBlock(NewIsland);
1240
1241   // Decrement the old entry, and remove it if refcount becomes 0.
1242   DecrementOldEntry(CPI, CPEMI);
1243
1244   // Now that we have an island to add the CPE to, clone the original CPE and
1245   // add it to the island.
1246   U.HighWaterMark = NewIsland;
1247   U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1248                 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1249   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1250   NumCPEs++;
1251
1252   BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1253   // Compensate for .align 2 in thumb mode.
1254   if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
1255     Size += 2;
1256   // Increase the size of the island block to account for the new entry.
1257   BBSizes[NewIsland->getNumber()] += Size;
1258   AdjustBBOffsetsAfter(NewIsland, Size);
1259
1260   // Finally, change the CPI in the instruction operand to be ID.
1261   for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1262     if (UserMI->getOperand(i).isCPI()) {
1263       UserMI->getOperand(i).setIndex(ID);
1264       break;
1265     }
1266
1267   DEBUG(errs() << "  Moved CPE to #" << ID << " CPI=" << CPI
1268            << '\t' << *UserMI);
1269
1270   return true;
1271 }
1272
1273 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1274 /// sizes and offsets of impacted basic blocks.
1275 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1276   MachineBasicBlock *CPEBB = CPEMI->getParent();
1277   unsigned Size = CPEMI->getOperand(2).getImm();
1278   CPEMI->eraseFromParent();
1279   BBSizes[CPEBB->getNumber()] -= Size;
1280   // All succeeding offsets have the current size value added in, fix this.
1281   if (CPEBB->empty()) {
1282     // In thumb1 mode, the size of island may be padded by two to compensate for
1283     // the alignment requirement.  Then it will now be 2 when the block is
1284     // empty, so fix this.
1285     // All succeeding offsets have the current size value added in, fix this.
1286     if (BBSizes[CPEBB->getNumber()] != 0) {
1287       Size += BBSizes[CPEBB->getNumber()];
1288       BBSizes[CPEBB->getNumber()] = 0;
1289     }
1290   }
1291   AdjustBBOffsetsAfter(CPEBB, -Size);
1292   // An island has only one predecessor BB and one successor BB. Check if
1293   // this BB's predecessor jumps directly to this BB's successor. This
1294   // shouldn't happen currently.
1295   assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1296   // FIXME: remove the empty blocks after all the work is done?
1297 }
1298
1299 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1300 /// are zero.
1301 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1302   unsigned MadeChange = false;
1303   for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1304       std::vector<CPEntry> &CPEs = CPEntries[i];
1305       for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1306         if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1307           RemoveDeadCPEMI(CPEs[j].CPEMI);
1308           CPEs[j].CPEMI = NULL;
1309           MadeChange = true;
1310         }
1311       }
1312   }
1313   return MadeChange;
1314 }
1315
1316 /// BBIsInRange - Returns true if the distance between specific MI and
1317 /// specific BB can fit in MI's displacement field.
1318 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1319                                      unsigned MaxDisp) {
1320   unsigned PCAdj      = isThumb ? 4 : 8;
1321   unsigned BrOffset   = GetOffsetOf(MI) + PCAdj;
1322   unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1323
1324   DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1325                << " from BB#" << MI->getParent()->getNumber()
1326                << " max delta=" << MaxDisp
1327                << " from " << GetOffsetOf(MI) << " to " << DestOffset
1328                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1329
1330   if (BrOffset <= DestOffset) {
1331     // Branch before the Dest.
1332     if (DestOffset-BrOffset <= MaxDisp)
1333       return true;
1334   } else {
1335     if (BrOffset-DestOffset <= MaxDisp)
1336       return true;
1337   }
1338   return false;
1339 }
1340
1341 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1342 /// away to fit in its displacement field.
1343 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1344   MachineInstr *MI = Br.MI;
1345   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1346
1347   // Check to see if the DestBB is already in-range.
1348   if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1349     return false;
1350
1351   if (!Br.isCond)
1352     return FixUpUnconditionalBr(MF, Br);
1353   return FixUpConditionalBr(MF, Br);
1354 }
1355
1356 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1357 /// too far away to fit in its displacement field. If the LR register has been
1358 /// spilled in the epilogue, then we can use BL to implement a far jump.
1359 /// Otherwise, add an intermediate branch instruction to a branch.
1360 bool
1361 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1362   MachineInstr *MI = Br.MI;
1363   MachineBasicBlock *MBB = MI->getParent();
1364   if (!isThumb1)
1365     llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1366
1367   // Use BL to implement far jump.
1368   Br.MaxDisp = (1 << 21) * 2;
1369   MI->setDesc(TII->get(ARM::tBfar));
1370   BBSizes[MBB->getNumber()] += 2;
1371   AdjustBBOffsetsAfter(MBB, 2);
1372   HasFarJump = true;
1373   NumUBrFixed++;
1374
1375   DEBUG(errs() << "  Changed B to long jump " << *MI);
1376
1377   return true;
1378 }
1379
1380 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1381 /// far away to fit in its displacement field. It is converted to an inverse
1382 /// conditional branch + an unconditional branch to the destination.
1383 bool
1384 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1385   MachineInstr *MI = Br.MI;
1386   MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1387
1388   // Add an unconditional branch to the destination and invert the branch
1389   // condition to jump over it:
1390   // blt L1
1391   // =>
1392   // bge L2
1393   // b   L1
1394   // L2:
1395   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1396   CC = ARMCC::getOppositeCondition(CC);
1397   unsigned CCReg = MI->getOperand(2).getReg();
1398
1399   // If the branch is at the end of its MBB and that has a fall-through block,
1400   // direct the updated conditional branch to the fall-through block. Otherwise,
1401   // split the MBB before the next instruction.
1402   MachineBasicBlock *MBB = MI->getParent();
1403   MachineInstr *BMI = &MBB->back();
1404   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1405
1406   NumCBrFixed++;
1407   if (BMI != MI) {
1408     if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1409         BMI->getOpcode() == Br.UncondBr) {
1410       // Last MI in the BB is an unconditional branch. Can we simply invert the
1411       // condition and swap destinations:
1412       // beq L1
1413       // b   L2
1414       // =>
1415       // bne L2
1416       // b   L1
1417       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1418       if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1419         DEBUG(errs() << "  Invert Bcc condition and swap its destination with "
1420                      << *BMI);
1421         BMI->getOperand(0).setMBB(DestBB);
1422         MI->getOperand(0).setMBB(NewDest);
1423         MI->getOperand(1).setImm(CC);
1424         return true;
1425       }
1426     }
1427   }
1428
1429   if (NeedSplit) {
1430     SplitBlockBeforeInstr(MI);
1431     // No need for the branch to the next block. We're adding an unconditional
1432     // branch to the destination.
1433     int delta = TII->GetInstSizeInBytes(&MBB->back());
1434     BBSizes[MBB->getNumber()] -= delta;
1435     MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
1436     AdjustBBOffsetsAfter(SplitBB, -delta);
1437     MBB->back().eraseFromParent();
1438     // BBOffsets[SplitBB] is wrong temporarily, fixed below
1439   }
1440   MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1441
1442   DEBUG(errs() << "  Insert B to BB#" << DestBB->getNumber()
1443                << " also invert condition and change dest. to BB#"
1444                << NextBB->getNumber() << "\n");
1445
1446   // Insert a new conditional branch and a new unconditional branch.
1447   // Also update the ImmBranch as well as adding a new entry for the new branch.
1448   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1449     .addMBB(NextBB).addImm(CC).addReg(CCReg);
1450   Br.MI = &MBB->back();
1451   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1452   BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1453   BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1454   unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1455   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1456
1457   // Remove the old conditional branch.  It may or may not still be in MBB.
1458   BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1459   MI->eraseFromParent();
1460
1461   // The net size change is an addition of one unconditional branch.
1462   int delta = TII->GetInstSizeInBytes(&MBB->back());
1463   AdjustBBOffsetsAfter(MBB, delta);
1464   return true;
1465 }
1466
1467 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1468 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1469 /// to do this if tBfar is not used.
1470 bool ARMConstantIslands::UndoLRSpillRestore() {
1471   bool MadeChange = false;
1472   for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1473     MachineInstr *MI = PushPopMIs[i];
1474     // First two operands are predicates.
1475     if (MI->getOpcode() == ARM::tPOP_RET &&
1476         MI->getOperand(2).getReg() == ARM::PC &&
1477         MI->getNumExplicitOperands() == 3) {
1478       BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1479       MI->eraseFromParent();
1480       MadeChange = true;
1481     }
1482   }
1483   return MadeChange;
1484 }
1485
1486 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1487   bool MadeChange = false;
1488
1489   // Shrink ADR and LDR from constantpool.
1490   for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1491     CPUser &U = CPUsers[i];
1492     unsigned Opcode = U.MI->getOpcode();
1493     unsigned NewOpc = 0;
1494     unsigned Scale = 1;
1495     unsigned Bits = 0;
1496     switch (Opcode) {
1497     default: break;
1498     case ARM::t2LEApcrel:
1499       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1500         NewOpc = ARM::tLEApcrel;
1501         Bits = 8;
1502         Scale = 4;
1503       }
1504       break;
1505     case ARM::t2LDRpci:
1506       if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1507         NewOpc = ARM::tLDRpci;
1508         Bits = 8;
1509         Scale = 4;
1510       }
1511       break;
1512     }
1513
1514     if (!NewOpc)
1515       continue;
1516
1517     unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1518     unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1519     // FIXME: Check if offset is multiple of scale if scale is not 4.
1520     if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1521       U.MI->setDesc(TII->get(NewOpc));
1522       MachineBasicBlock *MBB = U.MI->getParent();
1523       BBSizes[MBB->getNumber()] -= 2;
1524       AdjustBBOffsetsAfter(MBB, -2);
1525       ++NumT2CPShrunk;
1526       MadeChange = true;
1527     }
1528   }
1529
1530   MadeChange |= OptimizeThumb2Branches(MF);
1531   MadeChange |= OptimizeThumb2JumpTables(MF);
1532   return MadeChange;
1533 }
1534
1535 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1536   bool MadeChange = false;
1537
1538   for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1539     ImmBranch &Br = ImmBranches[i];
1540     unsigned Opcode = Br.MI->getOpcode();
1541     unsigned NewOpc = 0;
1542     unsigned Scale = 1;
1543     unsigned Bits = 0;
1544     switch (Opcode) {
1545     default: break;
1546     case ARM::t2B:
1547       NewOpc = ARM::tB;
1548       Bits = 11;
1549       Scale = 2;
1550       break;
1551     case ARM::t2Bcc: {
1552       NewOpc = ARM::tBcc;
1553       Bits = 8;
1554       Scale = 2;
1555       break;
1556     }
1557     }
1558     if (NewOpc) {
1559       unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1560       MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1561       if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1562         Br.MI->setDesc(TII->get(NewOpc));
1563         MachineBasicBlock *MBB = Br.MI->getParent();
1564         BBSizes[MBB->getNumber()] -= 2;
1565         AdjustBBOffsetsAfter(MBB, -2);
1566         ++NumT2BrShrunk;
1567         MadeChange = true;
1568       }
1569     }
1570
1571     Opcode = Br.MI->getOpcode();
1572     if (Opcode != ARM::tBcc)
1573       continue;
1574
1575     NewOpc = 0;
1576     unsigned PredReg = 0;
1577     ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1578     if (Pred == ARMCC::EQ)
1579       NewOpc = ARM::tCBZ;
1580     else if (Pred == ARMCC::NE)
1581       NewOpc = ARM::tCBNZ;
1582     if (!NewOpc)
1583       continue;
1584     MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1585     // Check if the distance is within 126. Subtract starting offset by 2
1586     // because the cmp will be eliminated.
1587     unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1588     unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1589     if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1590       MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1591       if (CmpMI->getOpcode() == ARM::tCMPzi8) {
1592         unsigned Reg = CmpMI->getOperand(0).getReg();
1593         Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1594         if (Pred == ARMCC::AL &&
1595             CmpMI->getOperand(1).getImm() == 0 &&
1596             isARMLowRegister(Reg)) {
1597           MachineBasicBlock *MBB = Br.MI->getParent();
1598           MachineInstr *NewBR =
1599             BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1600             .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1601           CmpMI->eraseFromParent();
1602           Br.MI->eraseFromParent();
1603           Br.MI = NewBR;
1604           BBSizes[MBB->getNumber()] -= 2;
1605           AdjustBBOffsetsAfter(MBB, -2);
1606           ++NumCBZ;
1607           MadeChange = true;
1608         }
1609       }
1610     }
1611   }
1612
1613   return MadeChange;
1614 }
1615
1616 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1617 /// jumptables when it's possible.
1618 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1619   bool MadeChange = false;
1620
1621   // FIXME: After the tables are shrunk, can we get rid some of the
1622   // constantpool tables?
1623   MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1624   if (MJTI == 0) return false;
1625   
1626   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1627   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1628     MachineInstr *MI = T2JumpTables[i];
1629     const TargetInstrDesc &TID = MI->getDesc();
1630     unsigned NumOps = TID.getNumOperands();
1631     unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1632     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1633     unsigned JTI = JTOP.getIndex();
1634     assert(JTI < JT.size());
1635
1636     bool ByteOk = true;
1637     bool HalfWordOk = true;
1638     unsigned JTOffset = GetOffsetOf(MI) + 4;
1639     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1640     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1641       MachineBasicBlock *MBB = JTBBs[j];
1642       unsigned DstOffset = BBOffsets[MBB->getNumber()];
1643       // Negative offset is not ok. FIXME: We should change BB layout to make
1644       // sure all the branches are forward.
1645       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1646         ByteOk = false;
1647       unsigned TBHLimit = ((1<<16)-1)*2;
1648       if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1649         HalfWordOk = false;
1650       if (!ByteOk && !HalfWordOk)
1651         break;
1652     }
1653
1654     if (ByteOk || HalfWordOk) {
1655       MachineBasicBlock *MBB = MI->getParent();
1656       unsigned BaseReg = MI->getOperand(0).getReg();
1657       bool BaseRegKill = MI->getOperand(0).isKill();
1658       if (!BaseRegKill)
1659         continue;
1660       unsigned IdxReg = MI->getOperand(1).getReg();
1661       bool IdxRegKill = MI->getOperand(1).isKill();
1662       MachineBasicBlock::iterator PrevI = MI;
1663       if (PrevI == MBB->begin())
1664         continue;
1665
1666       MachineInstr *AddrMI = --PrevI;
1667       bool OptOk = true;
1668       // Examine the instruction that calculate the jumptable entry address.
1669       // If it's not the one just before the t2BR_JT, we won't delete it, then
1670       // it's not worth doing the optimization.
1671       for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1672         const MachineOperand &MO = AddrMI->getOperand(k);
1673         if (!MO.isReg() || !MO.getReg())
1674           continue;
1675         if (MO.isDef() && MO.getReg() != BaseReg) {
1676           OptOk = false;
1677           break;
1678         }
1679         if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1680           OptOk = false;
1681           break;
1682         }
1683       }
1684       if (!OptOk)
1685         continue;
1686
1687       // The previous instruction should be a tLEApcrel or t2LEApcrelJT, we want
1688       // to delete it as well.
1689       MachineInstr *LeaMI = --PrevI;
1690       if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1691            LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1692           LeaMI->getOperand(0).getReg() != BaseReg)
1693         OptOk = false;
1694
1695       if (!OptOk)
1696         continue;
1697
1698       unsigned Opc = ByteOk ? ARM::t2TBB : ARM::t2TBH;
1699       MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1700         .addReg(IdxReg, getKillRegState(IdxRegKill))
1701         .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1702         .addImm(MI->getOperand(JTOpIdx+1).getImm());
1703       // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1704       // is 2-byte aligned. For now, asm printer will fix it up.
1705       unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1706       unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1707       OrigSize += TII->GetInstSizeInBytes(LeaMI);
1708       OrigSize += TII->GetInstSizeInBytes(MI);
1709
1710       AddrMI->eraseFromParent();
1711       LeaMI->eraseFromParent();
1712       MI->eraseFromParent();
1713
1714       int delta = OrigSize - NewSize;
1715       BBSizes[MBB->getNumber()] -= delta;
1716       AdjustBBOffsetsAfter(MBB, -delta);
1717
1718       ++NumTBs;
1719       MadeChange = true;
1720     }
1721   }
1722
1723   return MadeChange;
1724 }
1725
1726 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1727 /// jump tables always branch forwards, since that's what tbb and tbh need.
1728 bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1729   bool MadeChange = false;
1730
1731   MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1732   if (MJTI == 0) return false;
1733   
1734   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1735   for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1736     MachineInstr *MI = T2JumpTables[i];
1737     const TargetInstrDesc &TID = MI->getDesc();
1738     unsigned NumOps = TID.getNumOperands();
1739     unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1740     MachineOperand JTOP = MI->getOperand(JTOpIdx);
1741     unsigned JTI = JTOP.getIndex();
1742     assert(JTI < JT.size());
1743
1744     // We prefer if target blocks for the jump table come after the jump
1745     // instruction so we can use TB[BH]. Loop through the target blocks
1746     // and try to adjust them such that that's true.
1747     int JTNumber = MI->getParent()->getNumber();
1748     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1749     for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1750       MachineBasicBlock *MBB = JTBBs[j];
1751       int DTNumber = MBB->getNumber();
1752
1753       if (DTNumber < JTNumber) {
1754         // The destination precedes the switch. Try to move the block forward
1755         // so we have a positive offset.
1756         MachineBasicBlock *NewBB =
1757           AdjustJTTargetBlockForward(MBB, MI->getParent());
1758         if (NewBB)
1759           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1760         MadeChange = true;
1761       }
1762     }
1763   }
1764
1765   return MadeChange;
1766 }
1767
1768 MachineBasicBlock *ARMConstantIslands::
1769 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1770 {
1771   MachineFunction &MF = *BB->getParent();
1772
1773   // If it's the destination block is terminated by an unconditional branch,
1774   // try to move it; otherwise, create a new block following the jump
1775   // table that branches back to the actual target. This is a very simple
1776   // heuristic. FIXME: We can definitely improve it.
1777   MachineBasicBlock *TBB = 0, *FBB = 0;
1778   SmallVector<MachineOperand, 4> Cond;
1779   SmallVector<MachineOperand, 4> CondPrior;
1780   MachineFunction::iterator BBi = BB;
1781   MachineFunction::iterator OldPrior = prior(BBi);
1782
1783   // If the block terminator isn't analyzable, don't try to move the block
1784   bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1785
1786   // If the block ends in an unconditional branch, move it. The prior block
1787   // has to have an analyzable terminator for us to move this one. Be paranoid
1788   // and make sure we're not trying to move the entry block of the function.
1789   if (!B && Cond.empty() && BB != MF.begin() &&
1790       !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1791     BB->moveAfter(JTBB);
1792     OldPrior->updateTerminator();
1793     BB->updateTerminator();
1794     // Update numbering to account for the block being moved.
1795     MF.RenumberBlocks();
1796     ++NumJTMoved;
1797     return NULL;
1798   }
1799
1800   // Create a new MBB for the code after the jump BB.
1801   MachineBasicBlock *NewBB =
1802     MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1803   MachineFunction::iterator MBBI = JTBB; ++MBBI;
1804   MF.insert(MBBI, NewBB);
1805
1806   // Add an unconditional branch from NewBB to BB.
1807   // There doesn't seem to be meaningful DebugInfo available; this doesn't
1808   // correspond directly to anything in the source.
1809   assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1810   BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB);
1811
1812   // Update internal data structures to account for the newly inserted MBB.
1813   MF.RenumberBlocks(NewBB);
1814
1815   // Update the CFG.
1816   NewBB->addSuccessor(BB);
1817   JTBB->removeSuccessor(BB);
1818   JTBB->addSuccessor(NewBB);
1819
1820   ++NumJTInserted;
1821   return NewBB;
1822 }