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