1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
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 "ARMAddressingModes.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMInstrInfo.h"
21 #include "Thumb2InstrInfo.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 /// 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;
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;
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;
83 /// NewWaterList - The subset of WaterList that was created since the
84 /// previous iteration by inserting unconditional branches.
85 SmallSet<MachineBasicBlock*, 4> NewWaterList;
87 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
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
104 MachineBasicBlock *HighWaterMark;
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();
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;
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.
126 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
127 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
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;
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
143 unsigned MaxDisp : 31;
146 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
147 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
150 /// ImmBranches - Keep track of all the immediate branch instructions.
152 std::vector<ImmBranch> ImmBranches;
154 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
156 SmallVector<MachineInstr*, 4> PushPopMIs;
158 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
159 SmallVector<MachineInstr*, 4> T2JumpTables;
161 /// HasFarJump - True if any far jump instruction has been emitted during
162 /// the branch fix up pass.
165 /// HasInlineAsm - True if the function contains inline assembly.
168 const ARMInstrInfo *TII;
169 const ARMSubtarget *STI;
170 ARMFunctionInfo *AFI;
176 ARMConstantIslands() : MachineFunctionPass(ID) {}
178 virtual bool runOnMachineFunction(MachineFunction &MF);
180 virtual const char *getPassName() const {
181 return "ARM constant island placement and branch shortening pass";
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,
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);
221 unsigned GetOffsetOf(MachineInstr *MI) const;
223 void verify(MachineFunction &MF);
225 char ARMConstantIslands::ID = 0;
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]);
236 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
238 MachineBasicBlock *MBB = MBBI;
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));
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!");
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");
266 /// createARMConstantIslandPass - returns an instance of the constpool
268 FunctionPass *llvm::createARMConstantIslandPass() {
269 return new ARMConstantIslands();
272 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
273 MachineConstantPool &MCP = *MF.getConstantPool();
275 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
276 AFI = MF.getInfo<ARMFunctionInfo>();
277 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
279 isThumb = AFI->isThumbFunction();
280 isThumb1 = AFI->isThumb1OnlyFunction();
281 isThumb2 = AFI->isThumb2Function();
284 HasInlineAsm = false;
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.
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.
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.
305 // ARM and Thumb2 functions need to be 4-byte aligned.
307 MF.EnsureAlignment(2); // 2 = log2(4)
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);
315 MF.EnsureAlignment(2); // 2 = log2(4)
318 /// The next UID to take is the first unused one.
319 AFI->initConstPoolEntryUId(CPEMIs.size());
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);
329 /// Remove dead constant pool entries.
330 RemoveUnusedCPEntries();
332 // Iteratively place constant pool entries and fix up branches until there
334 unsigned NoCPIters = 0, NoBRIters = 0;
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!");
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();
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!");
354 if (!CPChange && !BRChange)
359 // Shrink 32-bit Thumb2 branch, load, and store instructions.
360 if (isThumb2 && !STI->prefers32BitThumb())
361 MadeChange |= OptimizeThumb2Instructions(MF);
363 // After a while, this might be made debug-only, but it is not expensive.
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();
371 DEBUG(errs() << '\n'; dumpBBs());
380 T2JumpTables.clear();
385 /// DoInitialPlacement - Perform the initial placement of the constant pool
386 /// entries. To start with, we put them all at the end of the function.
387 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
388 std::vector<MachineInstr*> &CPEMIs) {
389 // Create the basic block to hold the CPE's.
390 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
393 // Add all of the constants from the constant pool to the end block, use an
394 // identity mapping of CPI's to CPE's.
395 const std::vector<MachineConstantPoolEntry> &CPs =
396 MF.getConstantPool()->getConstants();
398 const TargetData &TD = *MF.getTarget().getTargetData();
399 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
400 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
401 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
402 // we would have to pad them out or something so that instructions stay
404 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
405 MachineInstr *CPEMI =
406 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
407 .addImm(i).addConstantPoolIndex(i).addImm(Size);
408 CPEMIs.push_back(CPEMI);
410 // Add a new CPEntry, but no corresponding CPUser yet.
411 std::vector<CPEntry> CPEs;
412 CPEs.push_back(CPEntry(CPEMI, i));
413 CPEntries.push_back(CPEs);
415 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
420 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
421 /// into the block immediately after it.
422 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
423 // Get the next machine basic block in the function.
424 MachineFunction::iterator MBBI = MBB;
425 // Can't fall off end of function.
426 if (llvm::next(MBBI) == MBB->getParent()->end())
429 MachineBasicBlock *NextBB = llvm::next(MBBI);
430 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
431 E = MBB->succ_end(); I != E; ++I)
438 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
439 /// look up the corresponding CPEntry.
440 ARMConstantIslands::CPEntry
441 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
442 const MachineInstr *CPEMI) {
443 std::vector<CPEntry> &CPEs = CPEntries[CPI];
444 // Number of entries per constpool index should be small, just do a
446 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
447 if (CPEs[i].CPEMI == CPEMI)
453 /// JumpTableFunctionScan - Do a scan of the function, building up
454 /// information about the sizes of each block and the locations of all
456 void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
457 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
459 MachineBasicBlock &MBB = *MBBI;
461 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
463 if (I->getDesc().isBranch() && I->getOpcode() == ARM::t2BR_JT)
464 T2JumpTables.push_back(I);
468 /// InitialFunctionScan - Do the initial scan of the function, building up
469 /// information about the sizes of each block, the location of all the water,
470 /// and finding all of the constant pool users.
471 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
472 const std::vector<MachineInstr*> &CPEMIs) {
473 // First thing, see if the function has any inline assembly in it. If so,
474 // we have to be conservative about alignment assumptions, as we don't
475 // know for sure the size of any instructions in the inline assembly.
476 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
478 MachineBasicBlock &MBB = *MBBI;
479 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
481 if (I->getOpcode() == ARM::INLINEASM)
485 // Now go back through the instructions and build up our data structures
487 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
489 MachineBasicBlock &MBB = *MBBI;
491 // If this block doesn't fall through into the next MBB, then this is
492 // 'water' that a constant pool island could be placed.
493 if (!BBHasFallthrough(&MBB))
494 WaterList.push_back(&MBB);
496 unsigned MBBSize = 0;
497 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
499 if (I->isDebugValue())
501 // Add instruction size to MBBSize.
502 MBBSize += TII->GetInstSizeInBytes(I);
504 int Opc = I->getOpcode();
505 if (I->getDesc().isBranch()) {
512 continue; // Ignore other JT branches
514 // A Thumb1 table jump may involve padding; for the offsets to
515 // be right, functions containing these must be 4-byte aligned.
516 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
517 // table entries. So this code checks whether offset of tBR_JTr + 2
518 // is aligned. That is held in Offset+MBBSize, which already has
519 // 2 added in for the size of the mov pc instruction.
520 MF.EnsureAlignment(2U);
521 if ((Offset+MBBSize)%4 != 0 || HasInlineAsm)
522 // FIXME: Add a pseudo ALIGN instruction instead.
523 MBBSize += 2; // padding
524 continue; // Does not get an entry in ImmBranches
526 T2JumpTables.push_back(I);
527 continue; // Does not get an entry in ImmBranches
558 // Record this immediate branch.
559 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
560 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
563 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
564 PushPopMIs.push_back(I);
566 if (Opc == ARM::CONSTPOOL_ENTRY)
569 // Scan the instructions for constant pool operands.
570 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
571 if (I->getOperand(op).isCPI()) {
572 // We found one. The addressing mode tells us the max displacement
573 // from the PC that this instruction permits.
575 // Basic size info comes from the TSFlags field.
579 bool IsSoImm = false;
583 llvm_unreachable("Unknown addressing mode for CP reference!");
586 // Taking the address of a CP entry.
588 // This takes a SoImm, which is 8 bit immediate rotated. We'll
589 // pretend the maximum offset is 255 * 4. Since each instruction
590 // 4 byte wide, this is always correct. We'll check for other
591 // displacements that fits in a SoImm as well.
597 case ARM::t2LEApcrel:
611 case ARM::t2LDRSHi12:
612 case ARM::t2LDRSBi12:
613 Bits = 12; // +-offset_12
620 Scale = 4; // +(offset_8*4)
626 Scale = 4; // +-(offset_8*4)
631 // Remember that this is a user of a CP entry.
632 unsigned CPI = I->getOperand(op).getIndex();
633 MachineInstr *CPEMI = CPEMIs[CPI];
634 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
635 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
637 // Increment corresponding CPEntry reference count.
638 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
639 assert(CPE && "Cannot find a corresponding CPEntry!");
642 // Instructions can only use one CP entry, don't bother scanning the
643 // rest of the operands.
648 // In thumb mode, if this block is a constpool island, we may need padding
649 // so it's aligned on 4 byte boundary.
652 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
653 ((Offset%4) != 0 || HasInlineAsm))
656 BBSizes.push_back(MBBSize);
657 BBOffsets.push_back(Offset);
662 /// GetOffsetOf - Return the current offset of the specified machine instruction
663 /// from the start of the function. This offset changes as stuff is moved
664 /// around inside the function.
665 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
666 MachineBasicBlock *MBB = MI->getParent();
668 // The offset is composed of two things: the sum of the sizes of all MBB's
669 // before this instruction's block, and the offset from the start of the block
671 unsigned Offset = BBOffsets[MBB->getNumber()];
673 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
674 // alignment padding, and compensate if so.
676 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
677 (Offset%4 != 0 || HasInlineAsm))
680 // Sum instructions before MI in MBB.
681 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
682 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
683 if (&*I == MI) return Offset;
684 Offset += TII->GetInstSizeInBytes(I);
688 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
690 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
691 const MachineBasicBlock *RHS) {
692 return LHS->getNumber() < RHS->getNumber();
695 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
696 /// machine function, it upsets all of the block numbers. Renumber the blocks
697 /// and update the arrays that parallel this numbering.
698 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
699 // Renumber the MBB's to keep them consequtive.
700 NewBB->getParent()->RenumberBlocks(NewBB);
702 // Insert a size into BBSizes to align it properly with the (newly
703 // renumbered) block numbers.
704 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
706 // Likewise for BBOffsets.
707 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
709 // Next, update WaterList. Specifically, we need to add NewMBB as having
710 // available water after it.
712 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
714 WaterList.insert(IP, NewBB);
718 /// Split the basic block containing MI into two blocks, which are joined by
719 /// an unconditional branch. Update data structures and renumber blocks to
720 /// account for this change and returns the newly created block.
721 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
722 MachineBasicBlock *OrigBB = MI->getParent();
723 MachineFunction &MF = *OrigBB->getParent();
725 // Create a new MBB for the code after the OrigBB.
726 MachineBasicBlock *NewBB =
727 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
728 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
729 MF.insert(MBBI, NewBB);
731 // Splice the instructions starting with MI over to NewBB.
732 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
734 // Add an unconditional branch from OrigBB to NewBB.
735 // Note the new unconditional branch is not being recorded.
736 // There doesn't seem to be meaningful DebugInfo available; this doesn't
737 // correspond to anything in the source.
738 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
739 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
742 // Update the CFG. All succs of OrigBB are now succs of NewBB.
743 while (!OrigBB->succ_empty()) {
744 MachineBasicBlock *Succ = *OrigBB->succ_begin();
745 OrigBB->removeSuccessor(Succ);
746 NewBB->addSuccessor(Succ);
748 // This pass should be run after register allocation, so there should be no
749 // PHI nodes to update.
750 assert((Succ->empty() || !Succ->begin()->isPHI())
751 && "PHI nodes should be eliminated by now!");
754 // OrigBB branches to NewBB.
755 OrigBB->addSuccessor(NewBB);
757 // Update internal data structures to account for the newly inserted MBB.
758 // This is almost the same as UpdateForInsertedWaterBlock, except that
759 // the Water goes after OrigBB, not NewBB.
760 MF.RenumberBlocks(NewBB);
762 // Insert a size into BBSizes to align it properly with the (newly
763 // renumbered) block numbers.
764 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
766 // Likewise for BBOffsets.
767 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
769 // Next, update WaterList. Specifically, we need to add OrigMBB as having
770 // available water after it (but not if it's already there, which happens
771 // when splitting before a conditional branch that is followed by an
772 // unconditional branch - in that case we want to insert NewBB).
774 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
776 MachineBasicBlock* WaterBB = *IP;
777 if (WaterBB == OrigBB)
778 WaterList.insert(llvm::next(IP), NewBB);
780 WaterList.insert(IP, OrigBB);
781 NewWaterList.insert(OrigBB);
783 unsigned OrigBBI = OrigBB->getNumber();
784 unsigned NewBBI = NewBB->getNumber();
786 int delta = isThumb1 ? 2 : 4;
788 // Figure out how large the OrigBB is. As the first half of the original
789 // block, it cannot contain a tablejump. The size includes
790 // the new jump we added. (It should be possible to do this without
791 // recounting everything, but it's very confusing, and this is rarely
793 unsigned OrigBBSize = 0;
794 for (MachineBasicBlock::iterator I = OrigBB->begin(), E = OrigBB->end();
796 OrigBBSize += TII->GetInstSizeInBytes(I);
797 BBSizes[OrigBBI] = OrigBBSize;
799 // ...and adjust BBOffsets for NewBB accordingly.
800 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
802 // Figure out how large the NewMBB is. As the second half of the original
803 // block, it may contain a tablejump.
804 unsigned NewBBSize = 0;
805 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
807 NewBBSize += TII->GetInstSizeInBytes(I);
808 // Set the size of NewBB in BBSizes. It does not include any padding now.
809 BBSizes[NewBBI] = NewBBSize;
811 MachineInstr* ThumbJTMI = prior(NewBB->end());
812 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
813 // We've added another 2-byte instruction before this tablejump, which
814 // means we will always need padding if we didn't before, and vice versa.
816 // The original offset of the jump instruction was:
817 unsigned OrigOffset = BBOffsets[OrigBBI] + BBSizes[OrigBBI] - delta;
818 if (OrigOffset%4 == 0) {
819 // We had padding before and now we don't. No net change in code size.
822 // We didn't have padding before and now we do.
823 BBSizes[NewBBI] += 2;
828 // All BBOffsets following these blocks must be modified.
830 AdjustBBOffsetsAfter(NewBB, delta);
835 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
836 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
837 /// constant pool entry).
838 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
839 unsigned TrialOffset, unsigned MaxDisp,
840 bool NegativeOK, bool IsSoImm) {
841 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
842 // purposes of the displacement computation; compensate for that here.
843 // Effectively, the valid range of displacements is 2 bytes smaller for such
845 unsigned TotalAdj = 0;
846 if (isThumb && UserOffset%4 !=0) {
850 // CPEs will be rounded up to a multiple of 4.
851 if (isThumb && TrialOffset%4 != 0) {
856 // In Thumb2 mode, later branch adjustments can shift instructions up and
857 // cause alignment change. In the worst case scenario this can cause the
858 // user's effective address to be subtracted by 2 and the CPE's address to
860 if (isThumb2 && TotalAdj != 4)
861 MaxDisp -= (4 - TotalAdj);
863 if (UserOffset <= TrialOffset) {
864 // User before the Trial.
865 if (TrialOffset - UserOffset <= MaxDisp)
867 // FIXME: Make use full range of soimm values.
868 } else if (NegativeOK) {
869 if (UserOffset - TrialOffset <= MaxDisp)
871 // FIXME: Make use full range of soimm values.
876 /// WaterIsInRange - Returns true if a CPE placed after the specified
877 /// Water (a basic block) will be in range for the specific MI.
879 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
880 MachineBasicBlock* Water, CPUser &U) {
881 unsigned MaxDisp = U.MaxDisp;
882 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
883 BBSizes[Water->getNumber()];
885 // If the CPE is to be inserted before the instruction, that will raise
886 // the offset of the instruction.
887 if (CPEOffset < UserOffset)
888 UserOffset += U.CPEMI->getOperand(2).getImm();
890 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
893 /// CPEIsInRange - Returns true if the distance between specific MI and
894 /// specific ConstPool entry instruction can fit in MI's displacement field.
895 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
896 MachineInstr *CPEMI, unsigned MaxDisp,
897 bool NegOk, bool DoDump) {
898 unsigned CPEOffset = GetOffsetOf(CPEMI);
899 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
902 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
903 << " max delta=" << MaxDisp
904 << " insn address=" << UserOffset
905 << " CPE address=" << CPEOffset
906 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
909 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
913 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
914 /// unconditionally branches to its only successor.
915 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
916 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
919 MachineBasicBlock *Succ = *MBB->succ_begin();
920 MachineBasicBlock *Pred = *MBB->pred_begin();
921 MachineInstr *PredMI = &Pred->back();
922 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
923 || PredMI->getOpcode() == ARM::t2B)
924 return PredMI->getOperand(0).getMBB() == Succ;
929 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
931 MachineFunction::iterator MBBI = BB; MBBI = llvm::next(MBBI);
932 for(unsigned i = BB->getNumber()+1, e = BB->getParent()->getNumBlockIDs();
934 BBOffsets[i] += delta;
935 // If some existing blocks have padding, adjust the padding as needed, a
936 // bit tricky. delta can be negative so don't use % on that.
939 MachineBasicBlock *MBB = MBBI;
940 if (!MBB->empty() && !HasInlineAsm) {
941 // Constant pool entries require padding.
942 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
943 unsigned OldOffset = BBOffsets[i] - delta;
944 if ((OldOffset%4) == 0 && (BBOffsets[i]%4) != 0) {
948 } else if ((OldOffset%4) != 0 && (BBOffsets[i]%4) == 0) {
949 // remove existing padding
954 // Thumb1 jump tables require padding. They should be at the end;
955 // following unconditional branches are removed by AnalyzeBranch.
956 // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
957 // table entries. So this code checks whether offset of tBR_JTr
958 // is aligned; if it is, the offset of the jump table following the
959 // instruction will not be aligned, and we need padding.
960 MachineInstr *ThumbJTMI = prior(MBB->end());
961 if (ThumbJTMI->getOpcode() == ARM::tBR_JTr) {
962 unsigned NewMIOffset = GetOffsetOf(ThumbJTMI);
963 unsigned OldMIOffset = NewMIOffset - delta;
964 if ((OldMIOffset%4) == 0 && (NewMIOffset%4) != 0) {
965 // remove existing padding
968 } else if ((OldMIOffset%4) != 0 && (NewMIOffset%4) == 0) {
977 MBBI = llvm::next(MBBI);
981 /// DecrementOldEntry - find the constant pool entry with index CPI
982 /// and instruction CPEMI, and decrement its refcount. If the refcount
983 /// becomes 0 remove the entry and instruction. Returns true if we removed
984 /// the entry, false if we didn't.
986 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
987 // Find the old entry. Eliminate it if it is no longer used.
988 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
989 assert(CPE && "Unexpected!");
990 if (--CPE->RefCount == 0) {
991 RemoveDeadCPEMI(CPEMI);
999 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1000 /// if not, see if an in-range clone of the CPE is in range, and if so,
1001 /// change the data structures so the user references the clone. Returns:
1002 /// 0 = no existing entry found
1003 /// 1 = entry found, and there were no code insertions or deletions
1004 /// 2 = entry found, and there were code insertions or deletions
1005 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1007 MachineInstr *UserMI = U.MI;
1008 MachineInstr *CPEMI = U.CPEMI;
1010 // Check to see if the CPE is already in-range.
1011 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
1012 DEBUG(errs() << "In range\n");
1016 // No. Look for previously created clones of the CPE that are in range.
1017 unsigned CPI = CPEMI->getOperand(1).getIndex();
1018 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1019 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1020 // We already tried this one
1021 if (CPEs[i].CPEMI == CPEMI)
1023 // Removing CPEs can leave empty entries, skip
1024 if (CPEs[i].CPEMI == NULL)
1026 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1027 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1028 << CPEs[i].CPI << "\n");
1029 // Point the CPUser node to the replacement
1030 U.CPEMI = CPEs[i].CPEMI;
1031 // Change the CPI in the instruction operand to refer to the clone.
1032 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1033 if (UserMI->getOperand(j).isCPI()) {
1034 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1037 // Adjust the refcount of the clone...
1039 // ...and the original. If we didn't remove the old entry, none of the
1040 // addresses changed, so we don't need another pass.
1041 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1047 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1048 /// the specific unconditional branch instruction.
1049 static inline unsigned getUnconditionalBrDisp(int Opc) {
1052 return ((1<<10)-1)*2;
1054 return ((1<<23)-1)*2;
1059 return ((1<<23)-1)*4;
1062 /// LookForWater - Look for an existing entry in the WaterList in which
1063 /// we can place the CPE referenced from U so it's within range of U's MI.
1064 /// Returns true if found, false if not. If it returns true, WaterIter
1065 /// is set to the WaterList entry. For Thumb, prefer water that will not
1066 /// introduce padding to water that will. To ensure that this pass
1067 /// terminates, the CPE location for a particular CPUser is only allowed to
1068 /// move to a lower address, so search backward from the end of the list and
1069 /// prefer the first water that is in range.
1070 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1071 water_iterator &WaterIter) {
1072 if (WaterList.empty())
1075 bool FoundWaterThatWouldPad = false;
1076 water_iterator IPThatWouldPad;
1077 for (water_iterator IP = prior(WaterList.end()),
1078 B = WaterList.begin();; --IP) {
1079 MachineBasicBlock* WaterBB = *IP;
1080 // Check if water is in range and is either at a lower address than the
1081 // current "high water mark" or a new water block that was created since
1082 // the previous iteration by inserting an unconditional branch. In the
1083 // latter case, we want to allow resetting the high water mark back to
1084 // this new water since we haven't seen it before. Inserting branches
1085 // should be relatively uncommon and when it does happen, we want to be
1086 // sure to take advantage of it for all the CPEs near that block, so that
1087 // we don't insert more branches than necessary.
1088 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1089 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1090 NewWaterList.count(WaterBB))) {
1091 unsigned WBBId = WaterBB->getNumber();
1093 (BBOffsets[WBBId] + BBSizes[WBBId])%4 != 0) {
1094 // This is valid Water, but would introduce padding. Remember
1095 // it in case we don't find any Water that doesn't do this.
1096 if (!FoundWaterThatWouldPad) {
1097 FoundWaterThatWouldPad = true;
1098 IPThatWouldPad = IP;
1108 if (FoundWaterThatWouldPad) {
1109 WaterIter = IPThatWouldPad;
1115 /// CreateNewWater - No existing WaterList entry will work for
1116 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1117 /// block is used if in range, and the conditional branch munged so control
1118 /// flow is correct. Otherwise the block is split to create a hole with an
1119 /// unconditional branch around it. In either case NewMBB is set to a
1120 /// block following which the new island can be inserted (the WaterList
1121 /// is not adjusted).
1122 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1123 unsigned UserOffset,
1124 MachineBasicBlock *&NewMBB) {
1125 CPUser &U = CPUsers[CPUserIndex];
1126 MachineInstr *UserMI = U.MI;
1127 MachineInstr *CPEMI = U.CPEMI;
1128 MachineBasicBlock *UserMBB = UserMI->getParent();
1129 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
1130 BBSizes[UserMBB->getNumber()];
1131 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
1133 // If the block does not end in an unconditional branch already, and if the
1134 // end of the block is within range, make new water there. (The addition
1135 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1136 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1137 // inside OffsetIsInRange.
1138 if (BBHasFallthrough(UserMBB) &&
1139 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1140 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1141 DEBUG(errs() << "Split at end of block\n");
1142 if (&UserMBB->back() == UserMI)
1143 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1144 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1145 // Add an unconditional branch from UserMBB to fallthrough block.
1146 // Record it for branch lengthening; this new branch will not get out of
1147 // range, but if the preceding conditional branch is out of range, the
1148 // targets will be exchanged, and the altered branch may be out of
1149 // range, so the machinery has to know about it.
1150 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1151 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1152 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1153 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1154 MaxDisp, false, UncondBr));
1155 int delta = isThumb1 ? 2 : 4;
1156 BBSizes[UserMBB->getNumber()] += delta;
1157 AdjustBBOffsetsAfter(UserMBB, delta);
1159 // What a big block. Find a place within the block to split it.
1160 // This is a little tricky on Thumb1 since instructions are 2 bytes
1161 // and constant pool entries are 4 bytes: if instruction I references
1162 // island CPE, and instruction I+1 references CPE', it will
1163 // not work well to put CPE as far forward as possible, since then
1164 // CPE' cannot immediately follow it (that location is 2 bytes
1165 // farther away from I+1 than CPE was from I) and we'd need to create
1166 // a new island. So, we make a first guess, then walk through the
1167 // instructions between the one currently being looked at and the
1168 // possible insertion point, and make sure any other instructions
1169 // that reference CPEs will be able to use the same island area;
1170 // if not, we back up the insertion point.
1172 // The 4 in the following is for the unconditional branch we'll be
1173 // inserting (allows for long branch on Thumb1). Alignment of the
1174 // island is handled inside OffsetIsInRange.
1175 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1176 // This could point off the end of the block if we've already got
1177 // constant pool entries following this block; only the last one is
1178 // in the water list. Back past any possible branches (allow for a
1179 // conditional and a maximally long unconditional).
1180 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1181 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1183 unsigned EndInsertOffset = BaseInsertOffset +
1184 CPEMI->getOperand(2).getImm();
1185 MachineBasicBlock::iterator MI = UserMI;
1187 unsigned CPUIndex = CPUserIndex+1;
1188 unsigned NumCPUsers = CPUsers.size();
1189 MachineInstr *LastIT = 0;
1190 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1191 Offset < BaseInsertOffset;
1192 Offset += TII->GetInstSizeInBytes(MI),
1193 MI = llvm::next(MI)) {
1194 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1195 CPUser &U = CPUsers[CPUIndex];
1196 if (!OffsetIsInRange(Offset, EndInsertOffset,
1197 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1198 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1199 EndInsertOffset -= (isThumb1 ? 2 : 4);
1201 // This is overly conservative, as we don't account for CPEMIs
1202 // being reused within the block, but it doesn't matter much.
1203 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1207 // Remember the last IT instruction.
1208 if (MI->getOpcode() == ARM::t2IT)
1212 DEBUG(errs() << "Split in middle of big block\n");
1215 // Avoid splitting an IT block.
1217 unsigned PredReg = 0;
1218 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1219 if (CC != ARMCC::AL)
1222 NewMBB = SplitBlockBeforeInstr(MI);
1226 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1227 /// is out-of-range. If so, pick up the constant pool value and move it some
1228 /// place in-range. Return true if we changed any addresses (thus must run
1229 /// another pass of branch lengthening), false otherwise.
1230 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1231 unsigned CPUserIndex) {
1232 CPUser &U = CPUsers[CPUserIndex];
1233 MachineInstr *UserMI = U.MI;
1234 MachineInstr *CPEMI = U.CPEMI;
1235 unsigned CPI = CPEMI->getOperand(1).getIndex();
1236 unsigned Size = CPEMI->getOperand(2).getImm();
1237 // Compute this only once, it's expensive. The 4 or 8 is the value the
1238 // hardware keeps in the PC.
1239 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1241 // See if the current entry is within range, or there is a clone of it
1243 int result = LookForExistingCPEntry(U, UserOffset);
1244 if (result==1) return false;
1245 else if (result==2) return true;
1247 // No existing clone of this CPE is within range.
1248 // We will be generating a new clone. Get a UID for it.
1249 unsigned ID = AFI->createConstPoolEntryUId();
1251 // Look for water where we can place this CPE.
1252 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1253 MachineBasicBlock *NewMBB;
1255 if (LookForWater(U, UserOffset, IP)) {
1256 DEBUG(errs() << "found water in range\n");
1257 MachineBasicBlock *WaterBB = *IP;
1259 // If the original WaterList entry was "new water" on this iteration,
1260 // propagate that to the new island. This is just keeping NewWaterList
1261 // updated to match the WaterList, which will be updated below.
1262 if (NewWaterList.count(WaterBB)) {
1263 NewWaterList.erase(WaterBB);
1264 NewWaterList.insert(NewIsland);
1266 // The new CPE goes before the following block (NewMBB).
1267 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1271 DEBUG(errs() << "No water found\n");
1272 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1274 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1275 // called while handling branches so that the water will be seen on the
1276 // next iteration for constant pools, but in this context, we don't want
1277 // it. Check for this so it will be removed from the WaterList.
1278 // Also remove any entry from NewWaterList.
1279 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1280 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1281 if (IP != WaterList.end())
1282 NewWaterList.erase(WaterBB);
1284 // We are adding new water. Update NewWaterList.
1285 NewWaterList.insert(NewIsland);
1288 // Remove the original WaterList entry; we want subsequent insertions in
1289 // this vicinity to go after the one we're about to insert. This
1290 // considerably reduces the number of times we have to move the same CPE
1291 // more than once and is also important to ensure the algorithm terminates.
1292 if (IP != WaterList.end())
1293 WaterList.erase(IP);
1295 // Okay, we know we can put an island before NewMBB now, do it!
1296 MF.insert(NewMBB, NewIsland);
1298 // Update internal data structures to account for the newly inserted MBB.
1299 UpdateForInsertedWaterBlock(NewIsland);
1301 // Decrement the old entry, and remove it if refcount becomes 0.
1302 DecrementOldEntry(CPI, CPEMI);
1304 // Now that we have an island to add the CPE to, clone the original CPE and
1305 // add it to the island.
1306 U.HighWaterMark = NewIsland;
1307 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1308 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1309 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1312 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1313 // Compensate for .align 2 in thumb mode.
1314 if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 != 0 || HasInlineAsm))
1316 // Increase the size of the island block to account for the new entry.
1317 BBSizes[NewIsland->getNumber()] += Size;
1318 AdjustBBOffsetsAfter(NewIsland, Size);
1320 // Finally, change the CPI in the instruction operand to be ID.
1321 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1322 if (UserMI->getOperand(i).isCPI()) {
1323 UserMI->getOperand(i).setIndex(ID);
1327 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1328 << '\t' << *UserMI);
1333 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1334 /// sizes and offsets of impacted basic blocks.
1335 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1336 MachineBasicBlock *CPEBB = CPEMI->getParent();
1337 unsigned Size = CPEMI->getOperand(2).getImm();
1338 CPEMI->eraseFromParent();
1339 BBSizes[CPEBB->getNumber()] -= Size;
1340 // All succeeding offsets have the current size value added in, fix this.
1341 if (CPEBB->empty()) {
1342 // In thumb1 mode, the size of island may be padded by two to compensate for
1343 // the alignment requirement. Then it will now be 2 when the block is
1344 // empty, so fix this.
1345 // All succeeding offsets have the current size value added in, fix this.
1346 if (BBSizes[CPEBB->getNumber()] != 0) {
1347 Size += BBSizes[CPEBB->getNumber()];
1348 BBSizes[CPEBB->getNumber()] = 0;
1351 AdjustBBOffsetsAfter(CPEBB, -Size);
1352 // An island has only one predecessor BB and one successor BB. Check if
1353 // this BB's predecessor jumps directly to this BB's successor. This
1354 // shouldn't happen currently.
1355 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1356 // FIXME: remove the empty blocks after all the work is done?
1359 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1361 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1362 unsigned MadeChange = false;
1363 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1364 std::vector<CPEntry> &CPEs = CPEntries[i];
1365 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1366 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1367 RemoveDeadCPEMI(CPEs[j].CPEMI);
1368 CPEs[j].CPEMI = NULL;
1376 /// BBIsInRange - Returns true if the distance between specific MI and
1377 /// specific BB can fit in MI's displacement field.
1378 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1380 unsigned PCAdj = isThumb ? 4 : 8;
1381 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1382 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1384 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1385 << " from BB#" << MI->getParent()->getNumber()
1386 << " max delta=" << MaxDisp
1387 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1388 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1390 if (BrOffset <= DestOffset) {
1391 // Branch before the Dest.
1392 if (DestOffset-BrOffset <= MaxDisp)
1395 if (BrOffset-DestOffset <= MaxDisp)
1401 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1402 /// away to fit in its displacement field.
1403 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1404 MachineInstr *MI = Br.MI;
1405 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1407 // Check to see if the DestBB is already in-range.
1408 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1412 return FixUpUnconditionalBr(MF, Br);
1413 return FixUpConditionalBr(MF, Br);
1416 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1417 /// too far away to fit in its displacement field. If the LR register has been
1418 /// spilled in the epilogue, then we can use BL to implement a far jump.
1419 /// Otherwise, add an intermediate branch instruction to a branch.
1421 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1422 MachineInstr *MI = Br.MI;
1423 MachineBasicBlock *MBB = MI->getParent();
1425 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1427 // Use BL to implement far jump.
1428 Br.MaxDisp = (1 << 21) * 2;
1429 MI->setDesc(TII->get(ARM::tBfar));
1430 BBSizes[MBB->getNumber()] += 2;
1431 AdjustBBOffsetsAfter(MBB, 2);
1435 DEBUG(errs() << " Changed B to long jump " << *MI);
1440 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1441 /// far away to fit in its displacement field. It is converted to an inverse
1442 /// conditional branch + an unconditional branch to the destination.
1444 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1445 MachineInstr *MI = Br.MI;
1446 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1448 // Add an unconditional branch to the destination and invert the branch
1449 // condition to jump over it:
1455 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1456 CC = ARMCC::getOppositeCondition(CC);
1457 unsigned CCReg = MI->getOperand(2).getReg();
1459 // If the branch is at the end of its MBB and that has a fall-through block,
1460 // direct the updated conditional branch to the fall-through block. Otherwise,
1461 // split the MBB before the next instruction.
1462 MachineBasicBlock *MBB = MI->getParent();
1463 MachineInstr *BMI = &MBB->back();
1464 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1468 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1469 BMI->getOpcode() == Br.UncondBr) {
1470 // Last MI in the BB is an unconditional branch. Can we simply invert the
1471 // condition and swap destinations:
1477 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1478 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1479 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1481 BMI->getOperand(0).setMBB(DestBB);
1482 MI->getOperand(0).setMBB(NewDest);
1483 MI->getOperand(1).setImm(CC);
1490 SplitBlockBeforeInstr(MI);
1491 // No need for the branch to the next block. We're adding an unconditional
1492 // branch to the destination.
1493 int delta = TII->GetInstSizeInBytes(&MBB->back());
1494 BBSizes[MBB->getNumber()] -= delta;
1495 MachineBasicBlock* SplitBB = llvm::next(MachineFunction::iterator(MBB));
1496 AdjustBBOffsetsAfter(SplitBB, -delta);
1497 MBB->back().eraseFromParent();
1498 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1500 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1502 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1503 << " also invert condition and change dest. to BB#"
1504 << NextBB->getNumber() << "\n");
1506 // Insert a new conditional branch and a new unconditional branch.
1507 // Also update the ImmBranch as well as adding a new entry for the new branch.
1508 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1509 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1510 Br.MI = &MBB->back();
1511 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1512 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1513 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1514 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1515 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1517 // Remove the old conditional branch. It may or may not still be in MBB.
1518 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1519 MI->eraseFromParent();
1521 // The net size change is an addition of one unconditional branch.
1522 int delta = TII->GetInstSizeInBytes(&MBB->back());
1523 AdjustBBOffsetsAfter(MBB, delta);
1527 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1528 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1529 /// to do this if tBfar is not used.
1530 bool ARMConstantIslands::UndoLRSpillRestore() {
1531 bool MadeChange = false;
1532 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1533 MachineInstr *MI = PushPopMIs[i];
1534 // First two operands are predicates.
1535 if (MI->getOpcode() == ARM::tPOP_RET &&
1536 MI->getOperand(2).getReg() == ARM::PC &&
1537 MI->getNumExplicitOperands() == 3) {
1538 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1539 MI->eraseFromParent();
1546 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1547 bool MadeChange = false;
1549 // Shrink ADR and LDR from constantpool.
1550 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1551 CPUser &U = CPUsers[i];
1552 unsigned Opcode = U.MI->getOpcode();
1553 unsigned NewOpc = 0;
1558 case ARM::t2LEApcrel:
1559 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1560 NewOpc = ARM::tLEApcrel;
1566 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1567 NewOpc = ARM::tLDRpci;
1577 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1578 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1579 // FIXME: Check if offset is multiple of scale if scale is not 4.
1580 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1581 U.MI->setDesc(TII->get(NewOpc));
1582 MachineBasicBlock *MBB = U.MI->getParent();
1583 BBSizes[MBB->getNumber()] -= 2;
1584 AdjustBBOffsetsAfter(MBB, -2);
1590 MadeChange |= OptimizeThumb2Branches(MF);
1591 MadeChange |= OptimizeThumb2JumpTables(MF);
1595 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1596 bool MadeChange = false;
1598 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1599 ImmBranch &Br = ImmBranches[i];
1600 unsigned Opcode = Br.MI->getOpcode();
1601 unsigned NewOpc = 0;
1619 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1620 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1621 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1622 Br.MI->setDesc(TII->get(NewOpc));
1623 MachineBasicBlock *MBB = Br.MI->getParent();
1624 BBSizes[MBB->getNumber()] -= 2;
1625 AdjustBBOffsetsAfter(MBB, -2);
1631 Opcode = Br.MI->getOpcode();
1632 if (Opcode != ARM::tBcc)
1636 unsigned PredReg = 0;
1637 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1638 if (Pred == ARMCC::EQ)
1640 else if (Pred == ARMCC::NE)
1641 NewOpc = ARM::tCBNZ;
1644 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1645 // Check if the distance is within 126. Subtract starting offset by 2
1646 // because the cmp will be eliminated.
1647 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1648 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1649 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1650 MachineBasicBlock::iterator CmpMI = Br.MI; --CmpMI;
1651 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1652 unsigned Reg = CmpMI->getOperand(0).getReg();
1653 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1654 if (Pred == ARMCC::AL &&
1655 CmpMI->getOperand(1).getImm() == 0 &&
1656 isARMLowRegister(Reg)) {
1657 MachineBasicBlock *MBB = Br.MI->getParent();
1658 MachineInstr *NewBR =
1659 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1660 .addReg(Reg).addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1661 CmpMI->eraseFromParent();
1662 Br.MI->eraseFromParent();
1664 BBSizes[MBB->getNumber()] -= 2;
1665 AdjustBBOffsetsAfter(MBB, -2);
1676 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1677 /// jumptables when it's possible.
1678 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1679 bool MadeChange = false;
1681 // FIXME: After the tables are shrunk, can we get rid some of the
1682 // constantpool tables?
1683 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1684 if (MJTI == 0) return false;
1686 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1687 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1688 MachineInstr *MI = T2JumpTables[i];
1689 const TargetInstrDesc &TID = MI->getDesc();
1690 unsigned NumOps = TID.getNumOperands();
1691 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1692 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1693 unsigned JTI = JTOP.getIndex();
1694 assert(JTI < JT.size());
1697 bool HalfWordOk = true;
1698 unsigned JTOffset = GetOffsetOf(MI) + 4;
1699 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1700 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1701 MachineBasicBlock *MBB = JTBBs[j];
1702 unsigned DstOffset = BBOffsets[MBB->getNumber()];
1703 // Negative offset is not ok. FIXME: We should change BB layout to make
1704 // sure all the branches are forward.
1705 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1707 unsigned TBHLimit = ((1<<16)-1)*2;
1708 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1710 if (!ByteOk && !HalfWordOk)
1714 if (ByteOk || HalfWordOk) {
1715 MachineBasicBlock *MBB = MI->getParent();
1716 unsigned BaseReg = MI->getOperand(0).getReg();
1717 bool BaseRegKill = MI->getOperand(0).isKill();
1720 unsigned IdxReg = MI->getOperand(1).getReg();
1721 bool IdxRegKill = MI->getOperand(1).isKill();
1723 // Scan backwards to find the instruction that defines the base
1724 // register. Due to post-RA scheduling, we can't count on it
1725 // immediately preceding the branch instruction.
1726 MachineBasicBlock::iterator PrevI = MI;
1727 MachineBasicBlock::iterator B = MBB->begin();
1728 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1731 // If for some reason we didn't find it, we can't do anything, so
1732 // just skip this one.
1733 if (!PrevI->definesRegister(BaseReg))
1736 MachineInstr *AddrMI = PrevI;
1738 // Examine the instruction that calculates the jumptable entry address.
1739 // Make sure it only defines the base register and kills any uses
1740 // other than the index register.
1741 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1742 const MachineOperand &MO = AddrMI->getOperand(k);
1743 if (!MO.isReg() || !MO.getReg())
1745 if (MO.isDef() && MO.getReg() != BaseReg) {
1749 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1757 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1758 // that gave us the initial base register definition.
1759 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1762 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1763 // to delete it as well.
1764 MachineInstr *LeaMI = PrevI;
1765 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1766 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1767 LeaMI->getOperand(0).getReg() != BaseReg)
1773 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1774 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1775 .addReg(IdxReg, getKillRegState(IdxRegKill))
1776 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1777 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1778 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1779 // is 2-byte aligned. For now, asm printer will fix it up.
1780 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1781 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1782 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1783 OrigSize += TII->GetInstSizeInBytes(MI);
1785 AddrMI->eraseFromParent();
1786 LeaMI->eraseFromParent();
1787 MI->eraseFromParent();
1789 int delta = OrigSize - NewSize;
1790 BBSizes[MBB->getNumber()] -= delta;
1791 AdjustBBOffsetsAfter(MBB, -delta);
1801 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1802 /// jump tables always branch forwards, since that's what tbb and tbh need.
1803 bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1804 bool MadeChange = false;
1806 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1807 if (MJTI == 0) return false;
1809 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1810 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1811 MachineInstr *MI = T2JumpTables[i];
1812 const TargetInstrDesc &TID = MI->getDesc();
1813 unsigned NumOps = TID.getNumOperands();
1814 unsigned JTOpIdx = NumOps - (TID.isPredicable() ? 3 : 2);
1815 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1816 unsigned JTI = JTOP.getIndex();
1817 assert(JTI < JT.size());
1819 // We prefer if target blocks for the jump table come after the jump
1820 // instruction so we can use TB[BH]. Loop through the target blocks
1821 // and try to adjust them such that that's true.
1822 int JTNumber = MI->getParent()->getNumber();
1823 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1824 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1825 MachineBasicBlock *MBB = JTBBs[j];
1826 int DTNumber = MBB->getNumber();
1828 if (DTNumber < JTNumber) {
1829 // The destination precedes the switch. Try to move the block forward
1830 // so we have a positive offset.
1831 MachineBasicBlock *NewBB =
1832 AdjustJTTargetBlockForward(MBB, MI->getParent());
1834 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1843 MachineBasicBlock *ARMConstantIslands::
1844 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1846 MachineFunction &MF = *BB->getParent();
1848 // If the destination block is terminated by an unconditional branch,
1849 // try to move it; otherwise, create a new block following the jump
1850 // table that branches back to the actual target. This is a very simple
1851 // heuristic. FIXME: We can definitely improve it.
1852 MachineBasicBlock *TBB = 0, *FBB = 0;
1853 SmallVector<MachineOperand, 4> Cond;
1854 SmallVector<MachineOperand, 4> CondPrior;
1855 MachineFunction::iterator BBi = BB;
1856 MachineFunction::iterator OldPrior = prior(BBi);
1858 // If the block terminator isn't analyzable, don't try to move the block
1859 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1861 // If the block ends in an unconditional branch, move it. The prior block
1862 // has to have an analyzable terminator for us to move this one. Be paranoid
1863 // and make sure we're not trying to move the entry block of the function.
1864 if (!B && Cond.empty() && BB != MF.begin() &&
1865 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1866 BB->moveAfter(JTBB);
1867 OldPrior->updateTerminator();
1868 BB->updateTerminator();
1869 // Update numbering to account for the block being moved.
1870 MF.RenumberBlocks();
1875 // Create a new MBB for the code after the jump BB.
1876 MachineBasicBlock *NewBB =
1877 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1878 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1879 MF.insert(MBBI, NewBB);
1881 // Add an unconditional branch from NewBB to BB.
1882 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1883 // correspond directly to anything in the source.
1884 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1885 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB);
1887 // Update internal data structures to account for the newly inserted MBB.
1888 MF.RenumberBlocks(NewBB);
1891 NewBB->addSuccessor(BB);
1892 JTBB->removeSuccessor(BB);
1893 JTBB->addSuccessor(NewBB);