1 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "arm-cp-islands"
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"
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");
51 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
52 cl::desc("Adjust basic block layout to better use TB[BH]"));
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.
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 /// BasicBlockInfo - Information about the offset and size of a single
69 struct BasicBlockInfo {
70 /// Offset - Distance from the beginning of the function to the beginning
71 /// of this basic block.
73 /// The two-byte pads required for Thumb alignment are counted as part of
74 /// the following block.
77 /// Size - Size of the basic block in bytes. If the block contains
78 /// inline assembly, this is a worst case estimate.
80 /// The two-byte pads required for Thumb alignment are counted as part of
81 /// the following block (i.e., the offset and size for a padded block
82 /// will both be ==2 mod 4).
85 BasicBlockInfo() : Offset(0), Size(0) {}
86 BasicBlockInfo(unsigned o, unsigned s) : Offset(o), Size(s) {}
89 std::vector<BasicBlockInfo> BBInfo;
91 /// WaterList - A sorted list of basic blocks where islands could be placed
92 /// (i.e. blocks that don't fall through to the following block, due
93 /// to a return, unreachable, or unconditional branch).
94 std::vector<MachineBasicBlock*> WaterList;
96 /// NewWaterList - The subset of WaterList that was created since the
97 /// previous iteration by inserting unconditional branches.
98 SmallSet<MachineBasicBlock*, 4> NewWaterList;
100 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
102 /// CPUser - One user of a constant pool, keeping the machine instruction
103 /// pointer, the constant pool being referenced, and the max displacement
104 /// allowed from the instruction to the CP. The HighWaterMark records the
105 /// highest basic block where a new CPEntry can be placed. To ensure this
106 /// pass terminates, the CP entries are initially placed at the end of the
107 /// function and then move monotonically to lower addresses. The
108 /// exception to this rule is when the current CP entry for a particular
109 /// CPUser is out of range, but there is another CP entry for the same
110 /// constant value in range. We want to use the existing in-range CP
111 /// entry, but if it later moves out of range, the search for new water
112 /// should resume where it left off. The HighWaterMark is used to record
117 MachineBasicBlock *HighWaterMark;
121 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
122 bool neg, bool soimm)
123 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
124 HighWaterMark = CPEMI->getParent();
128 /// CPUsers - Keep track of all of the machine instructions that use various
129 /// constant pools and their max displacement.
130 std::vector<CPUser> CPUsers;
132 /// CPEntry - One per constant pool entry, keeping the machine instruction
133 /// pointer, the constpool index, and the number of CPUser's which
134 /// reference this entry.
139 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
140 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
143 /// CPEntries - Keep track of all of the constant pool entry machine
144 /// instructions. For each original constpool index (i.e. those that
145 /// existed upon entry to this pass), it keeps a vector of entries.
146 /// Original elements are cloned as we go along; the clones are
147 /// put in the vector of the original element, but have distinct CPIs.
148 std::vector<std::vector<CPEntry> > CPEntries;
150 /// ImmBranch - One per immediate branch, keeping the machine instruction
151 /// pointer, conditional or unconditional, the max displacement,
152 /// and (if isCond is true) the corresponding unconditional branch
156 unsigned MaxDisp : 31;
159 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
160 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
163 /// ImmBranches - Keep track of all the immediate branch instructions.
165 std::vector<ImmBranch> ImmBranches;
167 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
169 SmallVector<MachineInstr*, 4> PushPopMIs;
171 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
172 SmallVector<MachineInstr*, 4> T2JumpTables;
174 /// HasFarJump - True if any far jump instruction has been emitted during
175 /// the branch fix up pass.
178 /// HasInlineAsm - True if the function contains inline assembly.
181 const ARMInstrInfo *TII;
182 const ARMSubtarget *STI;
183 ARMFunctionInfo *AFI;
189 ARMConstantIslands() : MachineFunctionPass(ID) {}
191 virtual bool runOnMachineFunction(MachineFunction &MF);
193 virtual const char *getPassName() const {
194 return "ARM constant island placement and branch shortening pass";
198 void DoInitialPlacement(MachineFunction &MF,
199 std::vector<MachineInstr*> &CPEMIs);
200 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
201 void JumpTableFunctionScan(MachineFunction &MF);
202 void InitialFunctionScan(MachineFunction &MF,
203 const std::vector<MachineInstr*> &CPEMIs);
204 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
205 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
206 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
207 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
208 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
209 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
210 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
211 MachineBasicBlock *&NewMBB);
212 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
213 void RemoveDeadCPEMI(MachineInstr *CPEMI);
214 bool RemoveUnusedCPEntries();
215 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
216 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
217 bool DoDump = false);
218 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
220 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
221 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
222 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
223 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
224 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
225 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
226 bool UndoLRSpillRestore();
227 bool OptimizeThumb2Instructions(MachineFunction &MF);
228 bool OptimizeThumb2Branches(MachineFunction &MF);
229 bool ReorderThumb2JumpTables(MachineFunction &MF);
230 bool OptimizeThumb2JumpTables(MachineFunction &MF);
231 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
232 MachineBasicBlock *JTBB);
234 unsigned GetOffsetOf(MachineInstr *MI) const;
236 void verify(MachineFunction &MF);
238 char ARMConstantIslands::ID = 0;
241 /// verify - check BBOffsets, BBSizes, alignment of islands
242 void ARMConstantIslands::verify(MachineFunction &MF) {
243 for (unsigned i = 1, e = BBInfo.size(); i != e; ++i)
244 assert(BBInfo[i-1].Offset + BBInfo[i-1].Size == BBInfo[i].Offset);
248 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
250 MachineBasicBlock *MBB = MBBI;
252 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
253 unsigned MBBId = MBB->getNumber();
254 assert(HasInlineAsm ||
255 (BBInfo[MBBId].Offset%4 == 0 && BBInfo[MBBId].Size%4 == 0) ||
256 (BBInfo[MBBId].Offset%4 != 0 && BBInfo[MBBId].Size%4 != 0));
259 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
260 CPUser &U = CPUsers[i];
261 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
262 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
263 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
264 UserOffset - CPEOffset;
265 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
270 /// print block size and offset information - debugging
271 void ARMConstantIslands::dumpBBs() {
272 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
273 DEBUG(errs() << "block " << J << " offset " << BBInfo[J].Offset
274 << " size " << BBInfo[J].Size << "\n");
278 /// createARMConstantIslandPass - returns an instance of the constpool
280 FunctionPass *llvm::createARMConstantIslandPass() {
281 return new ARMConstantIslands();
284 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
285 MachineConstantPool &MCP = *MF.getConstantPool();
287 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
288 AFI = MF.getInfo<ARMFunctionInfo>();
289 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
291 isThumb = AFI->isThumbFunction();
292 isThumb1 = AFI->isThumb1OnlyFunction();
293 isThumb2 = AFI->isThumb2Function();
296 HasInlineAsm = false;
298 // Renumber all of the machine basic blocks in the function, guaranteeing that
299 // the numbers agree with the position of the block in the function.
302 // Try to reorder and otherwise adjust the block layout to make good use
303 // of the TB[BH] instructions.
304 bool MadeChange = false;
305 if (isThumb2 && AdjustJumpTableBlocks) {
306 JumpTableFunctionScan(MF);
307 MadeChange |= ReorderThumb2JumpTables(MF);
308 // Data is out of date, so clear it. It'll be re-computed later.
309 T2JumpTables.clear();
310 // Blocks may have shifted around. Keep the numbering up to date.
314 // Thumb1 functions containing constant pools get 4-byte alignment.
315 // This is so we can keep exact track of where the alignment padding goes.
317 // ARM and Thumb2 functions need to be 4-byte aligned.
319 MF.EnsureAlignment(2); // 2 = log2(4)
321 // Perform the initial placement of the constant pool entries. To start with,
322 // we put them all at the end of the function.
323 std::vector<MachineInstr*> CPEMIs;
324 if (!MCP.isEmpty()) {
325 DoInitialPlacement(MF, CPEMIs);
327 MF.EnsureAlignment(2); // 2 = log2(4)
330 /// The next UID to take is the first unused one.
331 AFI->initPICLabelUId(CPEMIs.size());
333 // Do the initial scan of the function, building up information about the
334 // sizes of each block, the location of all the water, and finding all of the
335 // constant pool users.
336 InitialFunctionScan(MF, CPEMIs);
341 /// Remove dead constant pool entries.
342 MadeChange |= RemoveUnusedCPEntries();
344 // Iteratively place constant pool entries and fix up branches until there
346 unsigned NoCPIters = 0, NoBRIters = 0;
348 bool CPChange = false;
349 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
350 CPChange |= HandleConstantPoolUser(MF, i);
351 if (CPChange && ++NoCPIters > 30)
352 llvm_unreachable("Constant Island pass failed to converge!");
355 // Clear NewWaterList now. If we split a block for branches, it should
356 // appear as "new water" for the next iteration of constant pool placement.
357 NewWaterList.clear();
359 bool BRChange = false;
360 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
361 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
362 if (BRChange && ++NoBRIters > 30)
363 llvm_unreachable("Branch Fix Up pass failed to converge!");
366 if (!CPChange && !BRChange)
371 // Shrink 32-bit Thumb2 branch, load, and store instructions.
372 if (isThumb2 && !STI->prefers32BitThumb())
373 MadeChange |= OptimizeThumb2Instructions(MF);
375 // After a while, this might be made debug-only, but it is not expensive.
378 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
379 // undo the spill / restore of LR if possible.
380 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
381 MadeChange |= UndoLRSpillRestore();
383 // Save the mapping between original and cloned constpool entries.
384 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
385 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
386 const CPEntry & CPE = CPEntries[i][j];
387 AFI->recordCPEClone(i, CPE.CPI);
391 DEBUG(errs() << '\n'; dumpBBs());
399 T2JumpTables.clear();
404 /// DoInitialPlacement - Perform the initial placement of the constant pool
405 /// entries. To start with, we put them all at the end of the function.
406 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
407 std::vector<MachineInstr*> &CPEMIs) {
408 // Create the basic block to hold the CPE's.
409 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
412 // Mark the basic block as 4-byte aligned as required by the const-pool.
415 // Add all of the constants from the constant pool to the end block, use an
416 // identity mapping of CPI's to CPE's.
417 const std::vector<MachineConstantPoolEntry> &CPs =
418 MF.getConstantPool()->getConstants();
420 const TargetData &TD = *MF.getTarget().getTargetData();
421 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
422 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
423 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
424 // we would have to pad them out or something so that instructions stay
426 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
427 MachineInstr *CPEMI =
428 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
429 .addImm(i).addConstantPoolIndex(i).addImm(Size);
430 CPEMIs.push_back(CPEMI);
432 // Add a new CPEntry, but no corresponding CPUser yet.
433 std::vector<CPEntry> CPEs;
434 CPEs.push_back(CPEntry(CPEMI, i));
435 CPEntries.push_back(CPEs);
437 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
442 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
443 /// into the block immediately after it.
444 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
445 // Get the next machine basic block in the function.
446 MachineFunction::iterator MBBI = MBB;
447 // Can't fall off end of function.
448 if (llvm::next(MBBI) == MBB->getParent()->end())
451 MachineBasicBlock *NextBB = llvm::next(MBBI);
452 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
453 E = MBB->succ_end(); I != E; ++I)
460 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
461 /// look up the corresponding CPEntry.
462 ARMConstantIslands::CPEntry
463 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
464 const MachineInstr *CPEMI) {
465 std::vector<CPEntry> &CPEs = CPEntries[CPI];
466 // Number of entries per constpool index should be small, just do a
468 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
469 if (CPEs[i].CPEMI == CPEMI)
475 /// JumpTableFunctionScan - Do a scan of the function, building up
476 /// information about the sizes of each block and the locations of all
478 void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
479 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
481 MachineBasicBlock &MBB = *MBBI;
483 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
485 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
486 T2JumpTables.push_back(I);
490 /// InitialFunctionScan - Do the initial scan of the function, building up
491 /// information about the sizes of each block, the location of all the water,
492 /// and finding all of the constant pool users.
493 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
494 const std::vector<MachineInstr*> &CPEMIs) {
495 // First thing, see if the function has any inline assembly in it. If so,
496 // we have to be conservative about alignment assumptions, as we don't
497 // know for sure the size of any instructions in the inline assembly.
498 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
500 MachineBasicBlock &MBB = *MBBI;
501 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
503 if (I->getOpcode() == ARM::INLINEASM)
507 // Now go back through the instructions and build up our data structures.
509 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
511 MachineBasicBlock &MBB = *MBBI;
513 // If this block doesn't fall through into the next MBB, then this is
514 // 'water' that a constant pool island could be placed.
515 if (!BBHasFallthrough(&MBB))
516 WaterList.push_back(&MBB);
518 unsigned MBBSize = 0;
519 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
521 if (I->isDebugValue())
523 // Add instruction size to MBBSize.
524 MBBSize += TII->GetInstSizeInBytes(I);
526 int Opc = I->getOpcode();
527 if (I->getDesc().isBranch()) {
534 continue; // Ignore other JT branches
536 // A Thumb1 table jump may involve padding; for the offsets to
537 // be right, functions containing these must be 4-byte aligned.
538 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
539 // table entries. So this code checks whether offset of tBR_JTr + 2
540 // is aligned. That is held in Offset+MBBSize, which already has
541 // 2 added in for the size of the mov pc instruction.
542 MF.EnsureAlignment(2U);
543 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
544 // FIXME: Add a pseudo ALIGN instruction instead.
545 MBBSize += 2; // padding
546 continue; // Does not get an entry in ImmBranches
548 T2JumpTables.push_back(I);
549 continue; // Does not get an entry in ImmBranches
580 // Record this immediate branch.
581 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
582 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
585 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
586 PushPopMIs.push_back(I);
588 if (Opc == ARM::CONSTPOOL_ENTRY)
591 // Scan the instructions for constant pool operands.
592 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
593 if (I->getOperand(op).isCPI()) {
594 // We found one. The addressing mode tells us the max displacement
595 // from the PC that this instruction permits.
597 // Basic size info comes from the TSFlags field.
601 bool IsSoImm = false;
605 llvm_unreachable("Unknown addressing mode for CP reference!");
608 // Taking the address of a CP entry.
610 // This takes a SoImm, which is 8 bit immediate rotated. We'll
611 // pretend the maximum offset is 255 * 4. Since each instruction
612 // 4 byte wide, this is always correct. We'll check for other
613 // displacements that fits in a SoImm as well.
619 case ARM::t2LEApcrel:
631 Bits = 12; // +-offset_12
637 Scale = 4; // +(offset_8*4)
643 Scale = 4; // +-(offset_8*4)
648 // Remember that this is a user of a CP entry.
649 unsigned CPI = I->getOperand(op).getIndex();
650 MachineInstr *CPEMI = CPEMIs[CPI];
651 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
652 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
654 // Increment corresponding CPEntry reference count.
655 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
656 assert(CPE && "Cannot find a corresponding CPEntry!");
659 // Instructions can only use one CP entry, don't bother scanning the
660 // rest of the operands.
665 // In thumb mode, if this block is a constpool island, we may need padding
666 // so it's aligned on 4 byte boundary.
669 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
670 ((Offset%4) != 0 || HasInlineAsm))
673 BBInfo.push_back(BasicBlockInfo(Offset, MBBSize));
678 /// GetOffsetOf - Return the current offset of the specified machine instruction
679 /// from the start of the function. This offset changes as stuff is moved
680 /// around inside the function.
681 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
682 MachineBasicBlock *MBB = MI->getParent();
684 // The offset is composed of two things: the sum of the sizes of all MBB's
685 // before this instruction's block, and the offset from the start of the block
687 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
689 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
690 // alignment padding, and compensate if so.
692 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
693 (Offset%4 != 0 || HasInlineAsm))
696 // Sum instructions before MI in MBB.
697 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
698 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
699 if (&*I == MI) return Offset;
700 Offset += TII->GetInstSizeInBytes(I);
704 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
706 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
707 const MachineBasicBlock *RHS) {
708 return LHS->getNumber() < RHS->getNumber();
711 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
712 /// machine function, it upsets all of the block numbers. Renumber the blocks
713 /// and update the arrays that parallel this numbering.
714 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
715 // Renumber the MBB's to keep them consecutive.
716 NewBB->getParent()->RenumberBlocks(NewBB);
718 // Insert an entry into BBInfo to align it properly with the (newly
719 // renumbered) block numbers.
720 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
722 // Next, update WaterList. Specifically, we need to add NewMBB as having
723 // available water after it.
725 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
727 WaterList.insert(IP, NewBB);
731 /// Split the basic block containing MI into two blocks, which are joined by
732 /// an unconditional branch. Update data structures and renumber blocks to
733 /// account for this change and returns the newly created block.
734 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
735 MachineBasicBlock *OrigBB = MI->getParent();
736 MachineFunction &MF = *OrigBB->getParent();
738 // Create a new MBB for the code after the OrigBB.
739 MachineBasicBlock *NewBB =
740 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
741 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
742 MF.insert(MBBI, NewBB);
744 // Splice the instructions starting with MI over to NewBB.
745 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
747 // Add an unconditional branch from OrigBB to NewBB.
748 // Note the new unconditional branch is not being recorded.
749 // There doesn't seem to be meaningful DebugInfo available; this doesn't
750 // correspond to anything in the source.
751 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
753 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
755 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
756 .addImm(ARMCC::AL).addReg(0);
759 // Update the CFG. All succs of OrigBB are now succs of NewBB.
760 NewBB->transferSuccessors(OrigBB);
762 // OrigBB branches to NewBB.
763 OrigBB->addSuccessor(NewBB);
765 // Update internal data structures to account for the newly inserted MBB.
766 // This is almost the same as UpdateForInsertedWaterBlock, except that
767 // the Water goes after OrigBB, not NewBB.
768 MF.RenumberBlocks(NewBB);
770 // Insert an entry into BBInfo to align it properly with the (newly
771 // renumbered) block numbers.
772 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
774 // Next, update WaterList. Specifically, we need to add OrigMBB as having
775 // available water after it (but not if it's already there, which happens
776 // when splitting before a conditional branch that is followed by an
777 // unconditional branch - in that case we want to insert NewBB).
779 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
781 MachineBasicBlock* WaterBB = *IP;
782 if (WaterBB == OrigBB)
783 WaterList.insert(llvm::next(IP), NewBB);
785 WaterList.insert(IP, OrigBB);
786 NewWaterList.insert(OrigBB);
788 unsigned OrigBBI = OrigBB->getNumber();
789 unsigned NewBBI = NewBB->getNumber();
791 int delta = isThumb1 ? 2 : 4;
793 // Figure out how large the OrigBB is. As the first half of the original
794 // block, it cannot contain a tablejump. The size includes
795 // the new jump we added. (It should be possible to do this without
796 // recounting everything, but it's very confusing, and this is rarely
798 unsigned OrigBBSize = 0;
799 for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
801 OrigBBSize += TII->GetInstSizeInBytes(I);
802 BBInfo[OrigBBI].Size = OrigBBSize;
804 // ...and adjust BBOffsets for NewBB accordingly.
805 BBInfo[NewBBI].Offset = BBInfo[OrigBBI].Offset + BBInfo[OrigBBI].Size;
807 // Figure out how large the NewMBB is. As the second half of the original
808 // block, it may contain a tablejump.
809 unsigned NewBBSize = 0;
810 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
812 NewBBSize += TII->GetInstSizeInBytes(I);
813 // Set the size of NewBB in BBSizes. It does not include any padding now.
814 BBInfo[NewBBI].Size = NewBBSize;
816 MachineInstr* ThumbJTMI = prior(NewBB->end());
817 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
818 // We've added another 2-byte instruction before this tablejump, which
819 // means we will always need padding if we didn't before, and vice versa.
821 // The original offset of the jump instruction was:
822 unsigned OrigOffset = BBInfo[OrigBBI].Offset + BBInfo[OrigBBI].Size - delta;
823 if (OrigOffset%4 == 0) {
824 // We had padding before and now we don't. No net change in code size.
827 // We didn't have padding before and now we do.
828 BBInfo[NewBBI].Size += 2;
833 // All BBOffsets following these blocks must be modified.
835 AdjustBBOffsetsAfter(NewBB, delta);
840 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
841 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
842 /// constant pool entry).
843 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
844 unsigned TrialOffset, unsigned MaxDisp,
845 bool NegativeOK, bool IsSoImm) {
846 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
847 // purposes of the displacement computation; compensate for that here.
848 // Effectively, the valid range of displacements is 2 bytes smaller for such
850 unsigned TotalAdj = 0;
851 if (isThumb && UserOffset%4 !=0) {
855 // CPEs will be rounded up to a multiple of 4.
856 if (isThumb && TrialOffset%4 != 0) {
861 // In Thumb2 mode, later branch adjustments can shift instructions up and
862 // cause alignment change. In the worst case scenario this can cause the
863 // user's effective address to be subtracted by 2 and the CPE's address to
865 if (isThumb2 && TotalAdj != 4)
866 MaxDisp -= (4 - TotalAdj);
868 if (UserOffset <= TrialOffset) {
869 // User before the Trial.
870 if (TrialOffset - UserOffset <= MaxDisp)
872 // FIXME: Make use full range of soimm values.
873 } else if (NegativeOK) {
874 if (UserOffset - TrialOffset <= MaxDisp)
876 // FIXME: Make use full range of soimm values.
881 /// WaterIsInRange - Returns true if a CPE placed after the specified
882 /// Water (a basic block) will be in range for the specific MI.
884 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
885 MachineBasicBlock* Water, CPUser &U) {
886 unsigned MaxDisp = U.MaxDisp;
887 unsigned CPEOffset = BBInfo[Water->getNumber()].Offset +
888 BBInfo[Water->getNumber()].Size;
890 // If the CPE is to be inserted before the instruction, that will raise
891 // the offset of the instruction.
892 if (CPEOffset < UserOffset)
893 UserOffset += U.CPEMI->getOperand(2).getImm();
895 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
898 /// CPEIsInRange - Returns true if the distance between specific MI and
899 /// specific ConstPool entry instruction can fit in MI's displacement field.
900 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
901 MachineInstr *CPEMI, unsigned MaxDisp,
902 bool NegOk, bool DoDump) {
903 unsigned CPEOffset = GetOffsetOf(CPEMI);
904 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
907 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
908 << " max delta=" << MaxDisp
909 << " insn address=" << UserOffset
910 << " CPE address=" << CPEOffset
911 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
914 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
918 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
919 /// unconditionally branches to its only successor.
920 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
921 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
924 MachineBasicBlock *Succ = *MBB->succ_begin();
925 MachineBasicBlock *Pred = *MBB->pred_begin();
926 MachineInstr *PredMI = &Pred->back();
927 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
928 || PredMI->getOpcode() == ARM::t2B)
929 return PredMI->getOperand(0).getMBB() == Succ;
934 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
936 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
937 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
939 BBInfo[i].Offset += delta;
940 // If some existing blocks have padding, adjust the padding as needed, a
941 // bit tricky. delta can be negative so don't use % on that.
944 MachineBasicBlock *MBB = MBBI;
945 if (!MBB->empty() && !HasInlineAsm) {
946 // Constant pool entries require padding.
947 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
948 unsigned OldOffset = BBInfo[i].Offset - delta;
949 if ((OldOffset%4) == 0 && (BBInfo[i].Offset%4) != 0) {
953 } else if ((OldOffset%4) != 0 && (BBInfo[i].Offset%4) == 0) {
954 // remove existing padding
959 // Thumb1 jump tables require padding. They should be at the end;
960 // following unconditional branches are removed by AnalyzeBranch.
961 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
962 // table entries. So this code checks whether offset of tBR_JTr
963 // is aligned; if it is, the offset of the jump table following the
964 // instruction will not be aligned, and we need padding.
965 MachineInstr *ThumbJTMI = prior(MBB->end());
966 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
967 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
968 unsigned OldMIOffset = NewMIOffset - delta;
969 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
970 // remove existing padding
973 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
982 MBBI = llvm::next(MBBI);
986 /// DecrementOldEntry - find the constant pool entry with index CPI
987 /// and instruction CPEMI, and decrement its refcount. If the refcount
988 /// becomes 0 remove the entry and instruction. Returns true if we removed
989 /// the entry, false if we didn't.
991 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
992 // Find the old entry. Eliminate it if it is no longer used.
993 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
994 assert(CPE && "Unexpected!");
995 if (--CPE->RefCount == 0) {
996 RemoveDeadCPEMI(CPEMI);
1004 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1005 /// if not, see if an in-range clone of the CPE is in range, and if so,
1006 /// change the data structures so the user references the clone. Returns:
1007 /// 0 = no existing entry found
1008 /// 1 = entry found, and there were no code insertions or deletions
1009 /// 2 = entry found, and there were code insertions or deletions
1010 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1012 MachineInstr *UserMI = U.MI;
1013 MachineInstr *CPEMI = U.CPEMI;
1015 // Check to see if the CPE is already in-range.
1016 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
1017 DEBUG(errs() << "In range\n");
1021 // No. Look for previously created clones of the CPE that are in range.
1022 unsigned CPI = CPEMI->getOperand(1).getIndex();
1023 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1024 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1025 // We already tried this one
1026 if (CPEs[i].CPEMI == CPEMI)
1028 // Removing CPEs can leave empty entries, skip
1029 if (CPEs[i].CPEMI == NULL)
1031 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1032 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1033 << CPEs[i].CPI << "\n");
1034 // Point the CPUser node to the replacement
1035 U.CPEMI = CPEs[i].CPEMI;
1036 // Change the CPI in the instruction operand to refer to the clone.
1037 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1038 if (UserMI->getOperand(j).isCPI()) {
1039 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1042 // Adjust the refcount of the clone...
1044 // ...and the original. If we didn't remove the old entry, none of the
1045 // addresses changed, so we don't need another pass.
1046 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1052 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1053 /// the specific unconditional branch instruction.
1054 static inline unsigned getUnconditionalBrDisp(int Opc) {
1057 return ((1<<10)-1)*2;
1059 return ((1<<23)-1)*2;
1064 return ((1<<23)-1)*4;
1067 /// LookForWater - Look for an existing entry in the WaterList in which
1068 /// we can place the CPE referenced from U so it's within range of U's MI.
1069 /// Returns true if found, false if not. If it returns true, WaterIter
1070 /// is set to the WaterList entry. For Thumb, prefer water that will not
1071 /// introduce padding to water that will. To ensure that this pass
1072 /// terminates, the CPE location for a particular CPUser is only allowed to
1073 /// move to a lower address, so search backward from the end of the list and
1074 /// prefer the first water that is in range.
1075 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1076 water_iterator &WaterIter) {
1077 if (WaterList.empty())
1080 bool FoundWaterThatWouldPad = false;
1081 water_iterator IPThatWouldPad;
1082 for (water_iterator IP = prior(WaterList.end()),
1083 B = WaterList.begin();; --IP) {
1084 MachineBasicBlock* WaterBB = *IP;
1085 // Check if water is in range and is either at a lower address than the
1086 // current "high water mark" or a new water block that was created since
1087 // the previous iteration by inserting an unconditional branch. In the
1088 // latter case, we want to allow resetting the high water mark back to
1089 // this new water since we haven't seen it before. Inserting branches
1090 // should be relatively uncommon and when it does happen, we want to be
1091 // sure to take advantage of it for all the CPEs near that block, so that
1092 // we don't insert more branches than necessary.
1093 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1094 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1095 NewWaterList.count(WaterBB))) {
1096 unsigned WBBId = WaterBB->getNumber();
1098 (BBInfo[WBBId].Offset + BBInfo[WBBId].Size)%4 != 0) {
1099 // This is valid Water, but would introduce padding. Remember
1100 // it in case we don't find any Water that doesn't do this.
1101 if (!FoundWaterThatWouldPad) {
1102 FoundWaterThatWouldPad = true;
1103 IPThatWouldPad = IP;
1113 if (FoundWaterThatWouldPad) {
1114 WaterIter = IPThatWouldPad;
1120 /// CreateNewWater - No existing WaterList entry will work for
1121 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1122 /// block is used if in range, and the conditional branch munged so control
1123 /// flow is correct. Otherwise the block is split to create a hole with an
1124 /// unconditional branch around it. In either case NewMBB is set to a
1125 /// block following which the new island can be inserted (the WaterList
1126 /// is not adjusted).
1127 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1128 unsigned UserOffset,
1129 MachineBasicBlock *&NewMBB) {
1130 CPUser &U = CPUsers[CPUserIndex];
1131 MachineInstr *UserMI = U.MI;
1132 MachineInstr *CPEMI = U.CPEMI;
1133 MachineBasicBlock *UserMBB = UserMI->getParent();
1134 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].Offset +
1135 BBInfo[UserMBB->getNumber()].Size;
1136 assert(OffsetOfNextBlock== BBInfo[UserMBB->getNumber()+1].Offset);
1138 // If the block does not end in an unconditional branch already, and if the
1139 // end of the block is within range, make new water there. (The addition
1140 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1141 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1142 // inside OffsetIsInRange.
1143 if (BBHasFallthrough(UserMBB) &&
1144 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1145 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1146 DEBUG(errs() << "Split at end of block\n");
1147 if (&UserMBB->back() == UserMI)
1148 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1149 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1150 // Add an unconditional branch from UserMBB to fallthrough block.
1151 // Record it for branch lengthening; this new branch will not get out of
1152 // range, but if the preceding conditional branch is out of range, the
1153 // targets will be exchanged, and the altered branch may be out of
1154 // range, so the machinery has to know about it.
1155 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1157 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1159 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1160 .addImm(ARMCC::AL).addReg(0);
1161 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1162 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1163 MaxDisp, false, UncondBr));
1164 int delta = isThumb1 ? 2 : 4;
1165 BBInfo[UserMBB->getNumber()].Size += delta;
1166 AdjustBBOffsetsAfter(UserMBB, delta);
1168 // What a big block. Find a place within the block to split it.
1169 // This is a little tricky on Thumb1 since instructions are 2 bytes
1170 // and constant pool entries are 4 bytes: if instruction I references
1171 // island CPE, and instruction I+1 references CPE', it will
1172 // not work well to put CPE as far forward as possible, since then
1173 // CPE' cannot immediately follow it (that location is 2 bytes
1174 // farther away from I+1 than CPE was from I) and we'd need to create
1175 // a new island. So, we make a first guess, then walk through the
1176 // instructions between the one currently being looked at and the
1177 // possible insertion point, and make sure any other instructions
1178 // that reference CPEs will be able to use the same island area;
1179 // if not, we back up the insertion point.
1181 // The 4 in the following is for the unconditional branch we'll be
1182 // inserting (allows for long branch on Thumb1). Alignment of the
1183 // island is handled inside OffsetIsInRange.
1184 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1185 // This could point off the end of the block if we've already got
1186 // constant pool entries following this block; only the last one is
1187 // in the water list. Back past any possible branches (allow for a
1188 // conditional and a maximally long unconditional).
1189 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1190 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1192 unsigned EndInsertOffset = BaseInsertOffset +
1193 CPEMI->getOperand(2).getImm();
1194 MachineBasicBlock::iterator MI = UserMI;
1196 unsigned CPUIndex = CPUserIndex+1;
1197 unsigned NumCPUsers = CPUsers.size();
1198 MachineInstr *LastIT = 0;
1199 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1200 Offset < BaseInsertOffset;
1201 Offset += TII->GetInstSizeInBytes(MI),
1202 MI = llvm::next(MI)) {
1203 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1204 CPUser &U = CPUsers[CPUIndex];
1205 if (!OffsetIsInRange(Offset, EndInsertOffset,
1206 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1207 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1208 EndInsertOffset -= (isThumb1 ? 2 : 4);
1210 // This is overly conservative, as we don't account for CPEMIs
1211 // being reused within the block, but it doesn't matter much.
1212 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1216 // Remember the last IT instruction.
1217 if (MI->getOpcode() == ARM::t2IT)
1221 DEBUG(errs() << "Split in middle of big block\n");
1224 // Avoid splitting an IT block.
1226 unsigned PredReg = 0;
1227 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1228 if (CC != ARMCC::AL)
1231 NewMBB = SplitBlockBeforeInstr(MI);
1235 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1236 /// is out-of-range. If so, pick up the constant pool value and move it some
1237 /// place in-range. Return true if we changed any addresses (thus must run
1238 /// another pass of branch lengthening), false otherwise.
1239 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1240 unsigned CPUserIndex) {
1241 CPUser &U = CPUsers[CPUserIndex];
1242 MachineInstr *UserMI = U.MI;
1243 MachineInstr *CPEMI = U.CPEMI;
1244 unsigned CPI = CPEMI->getOperand(1).getIndex();
1245 unsigned Size = CPEMI->getOperand(2).getImm();
1246 // Compute this only once, it's expensive. The 4 or 8 is the value the
1247 // hardware keeps in the PC.
1248 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1250 // See if the current entry is within range, or there is a clone of it
1252 int result = LookForExistingCPEntry(U, UserOffset);
1253 if (result==1) return false;
1254 else if (result==2) return true;
1256 // No existing clone of this CPE is within range.
1257 // We will be generating a new clone. Get a UID for it.
1258 unsigned ID = AFI->createPICLabelUId();
1260 // Look for water where we can place this CPE.
1261 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1262 MachineBasicBlock *NewMBB;
1264 if (LookForWater(U, UserOffset, IP)) {
1265 DEBUG(errs() << "found water in range\n");
1266 MachineBasicBlock *WaterBB = *IP;
1268 // If the original WaterList entry was "new water" on this iteration,
1269 // propagate that to the new island. This is just keeping NewWaterList
1270 // updated to match the WaterList, which will be updated below.
1271 if (NewWaterList.count(WaterBB)) {
1272 NewWaterList.erase(WaterBB);
1273 NewWaterList.insert(NewIsland);
1275 // The new CPE goes before the following block (NewMBB).
1276 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1280 DEBUG(errs() << "No water found\n");
1281 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1283 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1284 // called while handling branches so that the water will be seen on the
1285 // next iteration for constant pools, but in this context, we don't want
1286 // it. Check for this so it will be removed from the WaterList.
1287 // Also remove any entry from NewWaterList.
1288 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1289 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1290 if (IP != WaterList.end())
1291 NewWaterList.erase(WaterBB);
1293 // We are adding new water. Update NewWaterList.
1294 NewWaterList.insert(NewIsland);
1297 // Remove the original WaterList entry; we want subsequent insertions in
1298 // this vicinity to go after the one we're about to insert. This
1299 // considerably reduces the number of times we have to move the same CPE
1300 // more than once and is also important to ensure the algorithm terminates.
1301 if (IP != WaterList.end())
1302 WaterList.erase(IP);
1304 // Okay, we know we can put an island before NewMBB now, do it!
1305 MF.insert(NewMBB, NewIsland);
1307 // Update internal data structures to account for the newly inserted MBB.
1308 UpdateForInsertedWaterBlock(NewIsland);
1310 // Decrement the old entry, and remove it if refcount becomes 0.
1311 DecrementOldEntry(CPI, CPEMI);
1313 // Now that we have an island to add the CPE to, clone the original CPE and
1314 // add it to the island.
1315 U.HighWaterMark = NewIsland;
1316 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1317 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1318 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1321 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1322 NewIsland->setAlignment(2);
1324 BBInfo[NewIsland->getNumber()].Offset = BBInfo[NewMBB->getNumber()].Offset;
1325 // Compensate for .align 2 in thumb mode.
1326 if (isThumb && (BBInfo[NewIsland->getNumber()].Offset%4 != 0 || HasInlineAsm))
1328 // Increase the size of the island block to account for the new entry.
1329 BBInfo[NewIsland->getNumber()].Size += Size;
1330 AdjustBBOffsetsAfter(NewIsland, Size);
1332 // Finally, change the CPI in the instruction operand to be ID.
1333 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1334 if (UserMI->getOperand(i).isCPI()) {
1335 UserMI->getOperand(i).setIndex(ID);
1339 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1340 << '\t' << *UserMI);
1345 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1346 /// sizes and offsets of impacted basic blocks.
1347 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1348 MachineBasicBlock *CPEBB = CPEMI->getParent();
1349 unsigned Size = CPEMI->getOperand(2).getImm();
1350 CPEMI->eraseFromParent();
1351 BBInfo[CPEBB->getNumber()].Size -= Size;
1352 // All succeeding offsets have the current size value added in, fix this.
1353 if (CPEBB->empty()) {
1354 // In thumb1 mode, the size of island may be padded by two to compensate for
1355 // the alignment requirement. Then it will now be 2 when the block is
1356 // empty, so fix this.
1357 // All succeeding offsets have the current size value added in, fix this.
1358 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1359 Size += BBInfo[CPEBB->getNumber()].Size;
1360 BBInfo[CPEBB->getNumber()].Size = 0;
1363 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1364 CPEBB->setAlignment(0);
1366 AdjustBBOffsetsAfter(CPEBB, -Size);
1367 // An island has only one predecessor BB and one successor BB. Check if
1368 // this BB's predecessor jumps directly to this BB's successor. This
1369 // shouldn't happen currently.
1370 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1371 // FIXME: remove the empty blocks after all the work is done?
1374 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1376 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1377 unsigned MadeChange = false;
1378 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1379 std::vector<CPEntry> &CPEs = CPEntries[i];
1380 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1381 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1382 RemoveDeadCPEMI(CPEs[j].CPEMI);
1383 CPEs[j].CPEMI = NULL;
1391 /// BBIsInRange - Returns true if the distance between specific MI and
1392 /// specific BB can fit in MI's displacement field.
1393 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1395 unsigned PCAdj = isThumb ? 4 : 8;
1396 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1397 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1399 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1400 << " from BB#" << MI->getParent()->getNumber()
1401 << " max delta=" << MaxDisp
1402 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1403 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1405 if (BrOffset <= DestOffset) {
1406 // Branch before the Dest.
1407 if (DestOffset-BrOffset <= MaxDisp)
1410 if (BrOffset-DestOffset <= MaxDisp)
1416 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1417 /// away to fit in its displacement field.
1418 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1419 MachineInstr *MI = Br.MI;
1420 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1422 // Check to see if the DestBB is already in-range.
1423 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1427 return FixUpUnconditionalBr(MF, Br);
1428 return FixUpConditionalBr(MF, Br);
1431 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1432 /// too far away to fit in its displacement field. If the LR register has been
1433 /// spilled in the epilogue, then we can use BL to implement a far jump.
1434 /// Otherwise, add an intermediate branch instruction to a branch.
1436 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1437 MachineInstr *MI = Br.MI;
1438 MachineBasicBlock *MBB = MI->getParent();
1440 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1442 // Use BL to implement far jump.
1443 Br.MaxDisp = (1 << 21) * 2;
1444 MI->setDesc(TII->get(ARM::tBfar));
1445 BBInfo[MBB->getNumber()].Size += 2;
1446 AdjustBBOffsetsAfter(MBB, 2);
1450 DEBUG(errs() << " Changed B to long jump " << *MI);
1455 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1456 /// far away to fit in its displacement field. It is converted to an inverse
1457 /// conditional branch + an unconditional branch to the destination.
1459 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1460 MachineInstr *MI = Br.MI;
1461 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1463 // Add an unconditional branch to the destination and invert the branch
1464 // condition to jump over it:
1470 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1471 CC = ARMCC::getOppositeCondition(CC);
1472 unsigned CCReg = MI->getOperand(2).getReg();
1474 // If the branch is at the end of its MBB and that has a fall-through block,
1475 // direct the updated conditional branch to the fall-through block. Otherwise,
1476 // split the MBB before the next instruction.
1477 MachineBasicBlock *MBB = MI->getParent();
1478 MachineInstr *BMI = &MBB->back();
1479 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1483 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1484 BMI->getOpcode() == Br.UncondBr) {
1485 // Last MI in the BB is an unconditional branch. Can we simply invert the
1486 // condition and swap destinations:
1492 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1493 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1494 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1496 BMI->getOperand(0).setMBB(DestBB);
1497 MI->getOperand(0).setMBB(NewDest);
1498 MI->getOperand(1).setImm(CC);
1505 SplitBlockBeforeInstr(MI);
1506 // No need for the branch to the next block. We're adding an unconditional
1507 // branch to the destination.
1508 int delta = TII->GetInstSizeInBytes(&MBB->back());
1509 BBInfo[MBB->getNumber()].Size -= delta;
1510 MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
1511 AdjustBBOffsetsAfter(SplitBB, -delta);
1512 MBB->back().eraseFromParent();
1513 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1515 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1517 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1518 << " also invert condition and change dest. to BB#"
1519 << NextBB->getNumber() << "\n");
1521 // Insert a new conditional branch and a new unconditional branch.
1522 // Also update the ImmBranch as well as adding a new entry for the new branch.
1523 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1524 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1525 Br.MI = &MBB->back();
1526 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1528 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1529 .addImm(ARMCC::AL).addReg(0);
1531 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1532 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1533 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1534 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1536 // Remove the old conditional branch. It may or may not still be in MBB.
1537 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1538 MI->eraseFromParent();
1540 // The net size change is an addition of one unconditional branch.
1541 int delta = TII->GetInstSizeInBytes(&MBB->back());
1542 AdjustBBOffsetsAfter(MBB, delta);
1546 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1547 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1548 /// to do this if tBfar is not used.
1549 bool ARMConstantIslands::UndoLRSpillRestore() {
1550 bool MadeChange = false;
1551 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1552 MachineInstr *MI = PushPopMIs[i];
1553 // First two operands are predicates.
1554 if (MI->getOpcode() == ARM::tPOP_RET &&
1555 MI->getOperand(2).getReg() == ARM::PC &&
1556 MI->getNumExplicitOperands() == 3) {
1557 // Create the new insn and copy the predicate from the old.
1558 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1559 .addOperand(MI->getOperand(0))
1560 .addOperand(MI->getOperand(1));
1561 MI->eraseFromParent();
1568 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1569 bool MadeChange = false;
1571 // Shrink ADR and LDR from constantpool.
1572 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1573 CPUser &U = CPUsers[i];
1574 unsigned Opcode = U.MI->getOpcode();
1575 unsigned NewOpc = 0;
1580 case ARM::t2LEApcrel:
1581 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1582 NewOpc = ARM::tLEApcrel;
1588 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1589 NewOpc = ARM::tLDRpci;
1599 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1600 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1601 // FIXME: Check if offset is multiple of scale if scale is not 4.
1602 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1603 U.MI->setDesc(TII->get(NewOpc));
1604 MachineBasicBlock *MBB = U.MI->getParent();
1605 BBInfo[MBB->getNumber()].Size -= 2;
1606 AdjustBBOffsetsAfter(MBB, -2);
1612 MadeChange |= OptimizeThumb2Branches(MF);
1613 MadeChange |= OptimizeThumb2JumpTables(MF);
1617 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1618 bool MadeChange = false;
1620 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1621 ImmBranch &Br = ImmBranches[i];
1622 unsigned Opcode = Br.MI->getOpcode();
1623 unsigned NewOpc = 0;
1641 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1642 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1643 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1644 Br.MI->setDesc(TII->get(NewOpc));
1645 MachineBasicBlock *MBB = Br.MI->getParent();
1646 BBInfo[MBB->getNumber()].Size -= 2;
1647 AdjustBBOffsetsAfter(MBB, -2);
1653 Opcode = Br.MI->getOpcode();
1654 if (Opcode != ARM::tBcc)
1658 unsigned PredReg = 0;
1659 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1660 if (Pred == ARMCC::EQ)
1662 else if (Pred == ARMCC::NE)
1663 NewOpc = ARM::tCBNZ;
1666 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1667 // Check if the distance is within 126. Subtract starting offset by 2
1668 // because the cmp will be eliminated.
1669 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1670 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1671 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1672 MachineBasicBlock::iterator CmpMI = Br.MI;
1673 if (CmpMI != Br.MI->getParent()->begin()) {
1675 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1676 unsigned Reg = CmpMI->getOperand(0).getReg();
1677 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1678 if (Pred == ARMCC::AL &&
1679 CmpMI->getOperand(1).getImm() == 0 &&
1680 isARMLowRegister(Reg)) {
1681 MachineBasicBlock *MBB = Br.MI->getParent();
1682 MachineInstr *NewBR =
1683 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1684 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1685 CmpMI->eraseFromParent();
1686 Br.MI->eraseFromParent();
1688 BBInfo[MBB->getNumber()].Size -= 2;
1689 AdjustBBOffsetsAfter(MBB, -2);
1701 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1702 /// jumptables when it's possible.
1703 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1704 bool MadeChange = false;
1706 // FIXME: After the tables are shrunk, can we get rid some of the
1707 // constantpool tables?
1708 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1709 if (MJTI == 0) return false;
1711 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1712 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1713 MachineInstr *MI = T2JumpTables[i];
1714 const MCInstrDesc &MCID = MI->getDesc();
1715 unsigned NumOps = MCID.getNumOperands();
1716 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
1717 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1718 unsigned JTI = JTOP.getIndex();
1719 assert(JTI < JT.size());
1722 bool HalfWordOk = true;
1723 unsigned JTOffset = GetOffsetOf(MI) + 4;
1724 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1725 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1726 MachineBasicBlock *MBB = JTBBs[j];
1727 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1728 // Negative offset is not ok. FIXME: We should change BB layout to make
1729 // sure all the branches are forward.
1730 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1732 unsigned TBHLimit = ((1<<16)-1)*2;
1733 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1735 if (!ByteOk && !HalfWordOk)
1739 if (ByteOk || HalfWordOk) {
1740 MachineBasicBlock *MBB = MI->getParent();
1741 unsigned BaseReg = MI->getOperand(0).getReg();
1742 bool BaseRegKill = MI->getOperand(0).isKill();
1745 unsigned IdxReg = MI->getOperand(1).getReg();
1746 bool IdxRegKill = MI->getOperand(1).isKill();
1748 // Scan backwards to find the instruction that defines the base
1749 // register. Due to post-RA scheduling, we can't count on it
1750 // immediately preceding the branch instruction.
1751 MachineBasicBlock::iterator PrevI = MI;
1752 MachineBasicBlock::iterator B = MBB->begin();
1753 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1756 // If for some reason we didn't find it, we can't do anything, so
1757 // just skip this one.
1758 if (!PrevI->definesRegister(BaseReg))
1761 MachineInstr *AddrMI = PrevI;
1763 // Examine the instruction that calculates the jumptable entry address.
1764 // Make sure it only defines the base register and kills any uses
1765 // other than the index register.
1766 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1767 const MachineOperand &MO = AddrMI->getOperand(k);
1768 if (!MO.isReg() || !MO.getReg())
1770 if (MO.isDef() && MO.getReg() != BaseReg) {
1774 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1782 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1783 // that gave us the initial base register definition.
1784 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1787 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1788 // to delete it as well.
1789 MachineInstr *LeaMI = PrevI;
1790 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1791 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1792 LeaMI->getOperand(0).getReg() != BaseReg)
1798 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1799 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1800 .addReg(IdxReg, getKillRegState(IdxRegKill))
1801 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1802 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1803 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1804 // is 2-byte aligned. For now, asm printer will fix it up.
1805 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1806 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1807 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1808 OrigSize += TII->GetInstSizeInBytes(MI);
1810 AddrMI->eraseFromParent();
1811 LeaMI->eraseFromParent();
1812 MI->eraseFromParent();
1814 int delta = OrigSize - NewSize;
1815 BBInfo[MBB->getNumber()].Size -= delta;
1816 AdjustBBOffsetsAfter(MBB, -delta);
1826 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1827 /// jump tables always branch forwards, since that's what tbb and tbh need.
1828 bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1829 bool MadeChange = false;
1831 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1832 if (MJTI == 0) return false;
1834 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1835 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1836 MachineInstr *MI = T2JumpTables[i];
1837 const MCInstrDesc &MCID = MI->getDesc();
1838 unsigned NumOps = MCID.getNumOperands();
1839 unsigned JTOpIdx = NumOps - (MCID.isPredicable() ? 3 : 2);
1840 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1841 unsigned JTI = JTOP.getIndex();
1842 assert(JTI < JT.size());
1844 // We prefer if target blocks for the jump table come after the jump
1845 // instruction so we can use TB[BH]. Loop through the target blocks
1846 // and try to adjust them such that that's true.
1847 int JTNumber = MI->getParent()->getNumber();
1848 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1849 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1850 MachineBasicBlock *MBB = JTBBs[j];
1851 int DTNumber = MBB->getNumber();
1853 if (DTNumber < JTNumber) {
1854 // The destination precedes the switch. Try to move the block forward
1855 // so we have a positive offset.
1856 MachineBasicBlock *NewBB =
1857 AdjustJTTargetBlockForward(MBB, MI->getParent());
1859 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1868 MachineBasicBlock *ARMConstantIslands::
1869 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1871 MachineFunction &MF = *BB->getParent();
1873 // If the destination block is terminated by an unconditional branch,
1874 // try to move it; otherwise, create a new block following the jump
1875 // table that branches back to the actual target. This is a very simple
1876 // heuristic. FIXME: We can definitely improve it.
1877 MachineBasicBlock *TBB = 0, *FBB = 0;
1878 SmallVector<MachineOperand, 4> Cond;
1879 SmallVector<MachineOperand, 4> CondPrior;
1880 MachineFunction::iterator BBi = BB;
1881 MachineFunction::iterator OldPrior = prior(BBi);
1883 // If the block terminator isn't analyzable, don't try to move the block
1884 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1886 // If the block ends in an unconditional branch, move it. The prior block
1887 // has to have an analyzable terminator for us to move this one. Be paranoid
1888 // and make sure we're not trying to move the entry block of the function.
1889 if (!B && Cond.empty() && BB != MF.begin() &&
1890 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1891 BB->moveAfter(JTBB);
1892 OldPrior->updateTerminator();
1893 BB->updateTerminator();
1894 // Update numbering to account for the block being moved.
1895 MF.RenumberBlocks();
1900 // Create a new MBB for the code after the jump BB.
1901 MachineBasicBlock *NewBB =
1902 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1903 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1904 MF.insert(MBBI, NewBB);
1906 // Add an unconditional branch from NewBB to BB.
1907 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1908 // correspond directly to anything in the source.
1909 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1910 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1911 .addImm(ARMCC::AL).addReg(0);
1913 // Update internal data structures to account for the newly inserted MBB.
1914 MF.RenumberBlocks(NewBB);
1917 NewBB->addSuccessor(BB);
1918 JTBB->removeSuccessor(BB);
1919 JTBB->addSuccessor(NewBB);