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]"));
54 /// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
55 /// add padding such that:
57 /// 1. The result is aligned to 1 << LogAlign.
59 /// 2. No other value of the unknown bits would require more padding.
61 /// This may add more padding than is required to satisfy just one of the
62 /// constraints. It is necessary to compute alignment this way to guarantee
63 /// that we don't underestimate the padding before an aligned block. If the
64 /// real padding before a block is larger than we think, constant pool entries
65 /// may go out of range.
66 static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
68 // Add the worst possible padding that the unknown bits could cause.
69 if (KnownBits < LogAlign)
70 Offset += (1u << LogAlign) - (1u << KnownBits);
72 // Then align the result.
73 return RoundUpToAlignment(Offset, 1u << LogAlign);
77 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
78 /// requires constant pool entries to be scattered among the instructions
79 /// inside a function. To do this, it completely ignores the normal LLVM
80 /// constant pool; instead, it places constants wherever it feels like with
81 /// special instructions.
83 /// The terminology used in this pass includes:
84 /// Islands - Clumps of constants placed in the function.
85 /// Water - Potential places where an island could be formed.
86 /// CPE - A constant pool entry that has been placed somewhere, which
87 /// tracks a list of users.
88 class ARMConstantIslands : public MachineFunctionPass {
89 /// BasicBlockInfo - Information about the offset and size of a single
91 struct BasicBlockInfo {
92 /// Offset - Distance from the beginning of the function to the beginning
93 /// of this basic block.
95 /// The offset is always aligned as required by the basic block.
98 /// Size - Size of the basic block in bytes. If the block contains
99 /// inline assembly, this is a worst case estimate.
101 /// The size does not include any alignment padding whether from the
102 /// beginning of the block, or from an aligned jump table at the end.
105 /// KnownBits - The number of low bits in Offset that are known to be
106 /// exact. The remaining bits of Offset are an upper bound.
109 /// Unalign - When non-zero, the block contains instructions (inline asm)
110 /// of unknown size. The real size may be smaller than Size bytes by a
111 /// multiple of 1 << Unalign.
114 /// PostAlign - When non-zero, the block terminator contains a .align
115 /// directive, so the end of the block is aligned to 1 << PostAlign
119 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
122 /// Compute the offset immediately following this block.
123 unsigned postOffset() const {
124 unsigned PO = Offset + Size;
127 // Add alignment padding from the terminator.
128 return WorstCaseAlign(PO, PostAlign, Unalign ? Unalign : KnownBits);
131 /// Compute the number of known low bits of postOffset. If this block
132 /// contains inline asm, the number of known bits drops to the
133 /// instruction alignment. An aligned terminator may increase the number
135 unsigned postKnownBits() const {
136 return std::max(PostAlign, Unalign ? Unalign : KnownBits);
140 std::vector<BasicBlockInfo> BBInfo;
142 /// WaterList - A sorted list of basic blocks where islands could be placed
143 /// (i.e. blocks that don't fall through to the following block, due
144 /// to a return, unreachable, or unconditional branch).
145 std::vector<MachineBasicBlock*> WaterList;
147 /// NewWaterList - The subset of WaterList that was created since the
148 /// previous iteration by inserting unconditional branches.
149 SmallSet<MachineBasicBlock*, 4> NewWaterList;
151 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
153 /// CPUser - One user of a constant pool, keeping the machine instruction
154 /// pointer, the constant pool being referenced, and the max displacement
155 /// allowed from the instruction to the CP. The HighWaterMark records the
156 /// highest basic block where a new CPEntry can be placed. To ensure this
157 /// pass terminates, the CP entries are initially placed at the end of the
158 /// function and then move monotonically to lower addresses. The
159 /// exception to this rule is when the current CP entry for a particular
160 /// CPUser is out of range, but there is another CP entry for the same
161 /// constant value in range. We want to use the existing in-range CP
162 /// entry, but if it later moves out of range, the search for new water
163 /// should resume where it left off. The HighWaterMark is used to record
168 MachineBasicBlock *HighWaterMark;
172 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
173 bool neg, bool soimm)
174 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {
175 HighWaterMark = CPEMI->getParent();
179 /// CPUsers - Keep track of all of the machine instructions that use various
180 /// constant pools and their max displacement.
181 std::vector<CPUser> CPUsers;
183 /// CPEntry - One per constant pool entry, keeping the machine instruction
184 /// pointer, the constpool index, and the number of CPUser's which
185 /// reference this entry.
190 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
191 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
194 /// CPEntries - Keep track of all of the constant pool entry machine
195 /// instructions. For each original constpool index (i.e. those that
196 /// existed upon entry to this pass), it keeps a vector of entries.
197 /// Original elements are cloned as we go along; the clones are
198 /// put in the vector of the original element, but have distinct CPIs.
199 std::vector<std::vector<CPEntry> > CPEntries;
201 /// ImmBranch - One per immediate branch, keeping the machine instruction
202 /// pointer, conditional or unconditional, the max displacement,
203 /// and (if isCond is true) the corresponding unconditional branch
207 unsigned MaxDisp : 31;
210 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
211 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
214 /// ImmBranches - Keep track of all the immediate branch instructions.
216 std::vector<ImmBranch> ImmBranches;
218 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
220 SmallVector<MachineInstr*, 4> PushPopMIs;
222 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
223 SmallVector<MachineInstr*, 4> T2JumpTables;
225 /// HasFarJump - True if any far jump instruction has been emitted during
226 /// the branch fix up pass.
229 /// HasInlineAsm - True if the function contains inline assembly.
232 const ARMInstrInfo *TII;
233 const ARMSubtarget *STI;
234 ARMFunctionInfo *AFI;
240 ARMConstantIslands() : MachineFunctionPass(ID) {}
242 virtual bool runOnMachineFunction(MachineFunction &MF);
244 virtual const char *getPassName() const {
245 return "ARM constant island placement and branch shortening pass";
249 void DoInitialPlacement(MachineFunction &MF,
250 std::vector<MachineInstr*> &CPEMIs);
251 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
252 void JumpTableFunctionScan(MachineFunction &MF);
253 void InitialFunctionScan(MachineFunction &MF,
254 const std::vector<MachineInstr*> &CPEMIs);
255 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
256 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
257 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
258 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
259 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
260 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
261 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
262 MachineBasicBlock *&NewMBB);
263 bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
264 void RemoveDeadCPEMI(MachineInstr *CPEMI);
265 bool RemoveUnusedCPEntries();
266 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
267 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
268 bool DoDump = false);
269 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
271 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
272 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
273 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
274 bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
275 bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
276 bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
277 bool UndoLRSpillRestore();
278 bool OptimizeThumb2Instructions(MachineFunction &MF);
279 bool OptimizeThumb2Branches(MachineFunction &MF);
280 bool ReorderThumb2JumpTables(MachineFunction &MF);
281 bool OptimizeThumb2JumpTables(MachineFunction &MF);
282 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
283 MachineBasicBlock *JTBB);
285 void ComputeBlockSize(MachineBasicBlock *MBB);
286 unsigned GetOffsetOf(MachineInstr *MI) const;
288 void verify(MachineFunction &MF);
290 char ARMConstantIslands::ID = 0;
293 /// verify - check BBOffsets, BBSizes, alignment of islands
294 void ARMConstantIslands::verify(MachineFunction &MF) {
298 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
300 MachineBasicBlock *MBB = MBBI;
302 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
303 unsigned MBBId = MBB->getNumber();
304 assert(HasInlineAsm ||
305 (BBInfo[MBBId].Offset%4 == 0 && BBInfo[MBBId].Size%4 == 0) ||
306 (BBInfo[MBBId].Offset%4 != 0 && BBInfo[MBBId].Size%4 != 0));
309 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
310 CPUser &U = CPUsers[i];
311 unsigned UserOffset = GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
312 unsigned CPEOffset = GetOffsetOf(U.CPEMI);
313 unsigned Disp = UserOffset < CPEOffset ? CPEOffset - UserOffset :
314 UserOffset - CPEOffset;
315 assert(Disp <= U.MaxDisp || "Constant pool entry out of range!");
320 /// print block size and offset information - debugging
321 void ARMConstantIslands::dumpBBs() {
322 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
323 DEBUG(errs() << "block " << J << " offset " << BBInfo[J].Offset
324 << " size " << BBInfo[J].Size << "\n");
328 /// createARMConstantIslandPass - returns an instance of the constpool
330 FunctionPass *llvm::createARMConstantIslandPass() {
331 return new ARMConstantIslands();
334 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
335 MachineConstantPool &MCP = *MF.getConstantPool();
337 TII = (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
338 AFI = MF.getInfo<ARMFunctionInfo>();
339 STI = &MF.getTarget().getSubtarget<ARMSubtarget>();
341 isThumb = AFI->isThumbFunction();
342 isThumb1 = AFI->isThumb1OnlyFunction();
343 isThumb2 = AFI->isThumb2Function();
346 HasInlineAsm = false;
348 // Renumber all of the machine basic blocks in the function, guaranteeing that
349 // the numbers agree with the position of the block in the function.
352 // Try to reorder and otherwise adjust the block layout to make good use
353 // of the TB[BH] instructions.
354 bool MadeChange = false;
355 if (isThumb2 && AdjustJumpTableBlocks) {
356 JumpTableFunctionScan(MF);
357 MadeChange |= ReorderThumb2JumpTables(MF);
358 // Data is out of date, so clear it. It'll be re-computed later.
359 T2JumpTables.clear();
360 // Blocks may have shifted around. Keep the numbering up to date.
364 // Thumb1 functions containing constant pools get 4-byte alignment.
365 // This is so we can keep exact track of where the alignment padding goes.
367 // ARM and Thumb2 functions need to be 4-byte aligned.
369 MF.EnsureAlignment(2); // 2 = log2(4)
371 // Perform the initial placement of the constant pool entries. To start with,
372 // we put them all at the end of the function.
373 std::vector<MachineInstr*> CPEMIs;
374 if (!MCP.isEmpty()) {
375 DoInitialPlacement(MF, CPEMIs);
377 MF.EnsureAlignment(2); // 2 = log2(4)
380 /// The next UID to take is the first unused one.
381 AFI->initPICLabelUId(CPEMIs.size());
383 // Do the initial scan of the function, building up information about the
384 // sizes of each block, the location of all the water, and finding all of the
385 // constant pool users.
386 InitialFunctionScan(MF, CPEMIs);
391 /// Remove dead constant pool entries.
392 MadeChange |= RemoveUnusedCPEntries();
394 // Iteratively place constant pool entries and fix up branches until there
396 unsigned NoCPIters = 0, NoBRIters = 0;
398 bool CPChange = false;
399 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
400 CPChange |= HandleConstantPoolUser(MF, i);
401 if (CPChange && ++NoCPIters > 30)
402 llvm_unreachable("Constant Island pass failed to converge!");
405 // Clear NewWaterList now. If we split a block for branches, it should
406 // appear as "new water" for the next iteration of constant pool placement.
407 NewWaterList.clear();
409 bool BRChange = false;
410 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
411 BRChange |= FixUpImmediateBr(MF, ImmBranches[i]);
412 if (BRChange && ++NoBRIters > 30)
413 llvm_unreachable("Branch Fix Up pass failed to converge!");
416 if (!CPChange && !BRChange)
421 // Shrink 32-bit Thumb2 branch, load, and store instructions.
422 if (isThumb2 && !STI->prefers32BitThumb())
423 MadeChange |= OptimizeThumb2Instructions(MF);
425 // After a while, this might be made debug-only, but it is not expensive.
428 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
429 // undo the spill / restore of LR if possible.
430 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
431 MadeChange |= UndoLRSpillRestore();
433 // Save the mapping between original and cloned constpool entries.
434 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
435 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
436 const CPEntry & CPE = CPEntries[i][j];
437 AFI->recordCPEClone(i, CPE.CPI);
441 DEBUG(errs() << '\n'; dumpBBs());
449 T2JumpTables.clear();
454 /// DoInitialPlacement - Perform the initial placement of the constant pool
455 /// entries. To start with, we put them all at the end of the function.
456 void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
457 std::vector<MachineInstr*> &CPEMIs) {
458 // Create the basic block to hold the CPE's.
459 MachineBasicBlock *BB = MF.CreateMachineBasicBlock();
462 // Mark the basic block as 4-byte aligned as required by the const-pool.
465 // Add all of the constants from the constant pool to the end block, use an
466 // identity mapping of CPI's to CPE's.
467 const std::vector<MachineConstantPoolEntry> &CPs =
468 MF.getConstantPool()->getConstants();
470 const TargetData &TD = *MF.getTarget().getTargetData();
471 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
472 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
473 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
474 // we would have to pad them out or something so that instructions stay
476 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
477 MachineInstr *CPEMI =
478 BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
479 .addImm(i).addConstantPoolIndex(i).addImm(Size);
480 CPEMIs.push_back(CPEMI);
482 // Add a new CPEntry, but no corresponding CPUser yet.
483 std::vector<CPEntry> CPEs;
484 CPEs.push_back(CPEntry(CPEMI, i));
485 CPEntries.push_back(CPEs);
487 DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
492 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
493 /// into the block immediately after it.
494 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
495 // Get the next machine basic block in the function.
496 MachineFunction::iterator MBBI = MBB;
497 // Can't fall off end of function.
498 if (llvm::next(MBBI) == MBB->getParent()->end())
501 MachineBasicBlock *NextBB = llvm::next(MBBI);
502 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
503 E = MBB->succ_end(); I != E; ++I)
510 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
511 /// look up the corresponding CPEntry.
512 ARMConstantIslands::CPEntry
513 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
514 const MachineInstr *CPEMI) {
515 std::vector<CPEntry> &CPEs = CPEntries[CPI];
516 // Number of entries per constpool index should be small, just do a
518 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
519 if (CPEs[i].CPEMI == CPEMI)
525 /// JumpTableFunctionScan - Do a scan of the function, building up
526 /// information about the sizes of each block and the locations of all
528 void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
529 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
531 MachineBasicBlock &MBB = *MBBI;
533 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
535 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
536 T2JumpTables.push_back(I);
540 /// InitialFunctionScan - Do the initial scan of the function, building up
541 /// information about the sizes of each block, the location of all the water,
542 /// and finding all of the constant pool users.
543 void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
544 const std::vector<MachineInstr*> &CPEMIs) {
546 BBInfo.resize(MF.getNumBlockIDs());
548 // First thing, compute the size of all basic blocks, and see if the function
549 // has any inline assembly in it. If so, we have to be conservative about
550 // alignment assumptions, as we don't know for sure the size of any
551 // instructions in the inline assembly.
552 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
555 // The known bits of the entry block offset are determined by the function
557 BBInfo.front().KnownBits = MF.getAlignment();
559 // Compute block offsets and known bits.
560 AdjustBBOffsetsAfter(MF.begin());
562 // Now go back through the instructions and build up our data structures.
563 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
565 MachineBasicBlock &MBB = *MBBI;
567 // If this block doesn't fall through into the next MBB, then this is
568 // 'water' that a constant pool island could be placed.
569 if (!BBHasFallthrough(&MBB))
570 WaterList.push_back(&MBB);
572 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
574 if (I->isDebugValue())
577 int Opc = I->getOpcode();
585 continue; // Ignore other JT branches
587 T2JumpTables.push_back(I);
588 continue; // Does not get an entry in ImmBranches
619 // Record this immediate branch.
620 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
621 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
624 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
625 PushPopMIs.push_back(I);
627 if (Opc == ARM::CONSTPOOL_ENTRY)
630 // Scan the instructions for constant pool operands.
631 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
632 if (I->getOperand(op).isCPI()) {
633 // We found one. The addressing mode tells us the max displacement
634 // from the PC that this instruction permits.
636 // Basic size info comes from the TSFlags field.
640 bool IsSoImm = false;
644 llvm_unreachable("Unknown addressing mode for CP reference!");
647 // Taking the address of a CP entry.
649 // This takes a SoImm, which is 8 bit immediate rotated. We'll
650 // pretend the maximum offset is 255 * 4. Since each instruction
651 // 4 byte wide, this is always correct. We'll check for other
652 // displacements that fits in a SoImm as well.
658 case ARM::t2LEApcrel:
670 Bits = 12; // +-offset_12
676 Scale = 4; // +(offset_8*4)
682 Scale = 4; // +-(offset_8*4)
687 // Remember that this is a user of a CP entry.
688 unsigned CPI = I->getOperand(op).getIndex();
689 MachineInstr *CPEMI = CPEMIs[CPI];
690 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
691 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
693 // Increment corresponding CPEntry reference count.
694 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
695 assert(CPE && "Cannot find a corresponding CPEntry!");
698 // Instructions can only use one CP entry, don't bother scanning the
699 // rest of the operands.
706 /// ComputeBlockSize - Compute the size and some alignment information for MBB.
707 /// This function updates BBInfo directly.
708 void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
709 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
714 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
716 BBI.Size += TII->GetInstSizeInBytes(I);
717 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
718 // The actual size may be smaller, but still a multiple of the instr size.
719 if (I->isInlineAsm()) {
720 BBI.Unalign = isThumb ? 1 : 2;
725 // tBR_JTr contains a .align 2 directive.
726 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
728 MBB->getParent()->EnsureAlignment(2);
732 /// GetOffsetOf - Return the current offset of the specified machine instruction
733 /// from the start of the function. This offset changes as stuff is moved
734 /// around inside the function.
735 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
736 MachineBasicBlock *MBB = MI->getParent();
738 // The offset is composed of two things: the sum of the sizes of all MBB's
739 // before this instruction's block, and the offset from the start of the block
741 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
743 // Sum instructions before MI in MBB.
744 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
745 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
746 if (&*I == MI) return Offset;
747 Offset += TII->GetInstSizeInBytes(I);
751 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
753 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
754 const MachineBasicBlock *RHS) {
755 return LHS->getNumber() < RHS->getNumber();
758 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
759 /// machine function, it upsets all of the block numbers. Renumber the blocks
760 /// and update the arrays that parallel this numbering.
761 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
762 // Renumber the MBB's to keep them consecutive.
763 NewBB->getParent()->RenumberBlocks(NewBB);
765 // Insert an entry into BBInfo to align it properly with the (newly
766 // renumbered) block numbers.
767 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
769 // Next, update WaterList. Specifically, we need to add NewMBB as having
770 // available water after it.
772 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
774 WaterList.insert(IP, NewBB);
778 /// Split the basic block containing MI into two blocks, which are joined by
779 /// an unconditional branch. Update data structures and renumber blocks to
780 /// account for this change and returns the newly created block.
781 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
782 MachineBasicBlock *OrigBB = MI->getParent();
783 MachineFunction &MF = *OrigBB->getParent();
785 // Create a new MBB for the code after the OrigBB.
786 MachineBasicBlock *NewBB =
787 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
788 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
789 MF.insert(MBBI, NewBB);
791 // Splice the instructions starting with MI over to NewBB.
792 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
794 // Add an unconditional branch from OrigBB to NewBB.
795 // Note the new unconditional branch is not being recorded.
796 // There doesn't seem to be meaningful DebugInfo available; this doesn't
797 // correspond to anything in the source.
798 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
800 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
802 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
803 .addImm(ARMCC::AL).addReg(0);
806 // Update the CFG. All succs of OrigBB are now succs of NewBB.
807 NewBB->transferSuccessors(OrigBB);
809 // OrigBB branches to NewBB.
810 OrigBB->addSuccessor(NewBB);
812 // Update internal data structures to account for the newly inserted MBB.
813 // This is almost the same as UpdateForInsertedWaterBlock, except that
814 // the Water goes after OrigBB, not NewBB.
815 MF.RenumberBlocks(NewBB);
817 // Insert an entry into BBInfo to align it properly with the (newly
818 // renumbered) block numbers.
819 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
821 // Next, update WaterList. Specifically, we need to add OrigMBB as having
822 // available water after it (but not if it's already there, which happens
823 // when splitting before a conditional branch that is followed by an
824 // unconditional branch - in that case we want to insert NewBB).
826 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
828 MachineBasicBlock* WaterBB = *IP;
829 if (WaterBB == OrigBB)
830 WaterList.insert(llvm::next(IP), NewBB);
832 WaterList.insert(IP, OrigBB);
833 NewWaterList.insert(OrigBB);
835 // Figure out how large the OrigBB is. As the first half of the original
836 // block, it cannot contain a tablejump. The size includes
837 // the new jump we added. (It should be possible to do this without
838 // recounting everything, but it's very confusing, and this is rarely
840 ComputeBlockSize(OrigBB);
842 // Figure out how large the NewMBB is. As the second half of the original
843 // block, it may contain a tablejump.
844 ComputeBlockSize(NewBB);
846 // All BBOffsets following these blocks must be modified.
847 AdjustBBOffsetsAfter(OrigBB);
852 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
853 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
854 /// constant pool entry).
855 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
856 unsigned TrialOffset, unsigned MaxDisp,
857 bool NegativeOK, bool IsSoImm) {
858 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
859 // purposes of the displacement computation; compensate for that here.
860 // Effectively, the valid range of displacements is 2 bytes smaller for such
862 unsigned TotalAdj = 0;
863 if (isThumb && UserOffset%4 !=0) {
867 // CPEs will be rounded up to a multiple of 4.
868 if (isThumb && TrialOffset%4 != 0) {
873 // In Thumb2 mode, later branch adjustments can shift instructions up and
874 // cause alignment change. In the worst case scenario this can cause the
875 // user's effective address to be subtracted by 2 and the CPE's address to
877 if (isThumb2 && TotalAdj != 4)
878 MaxDisp -= (4 - TotalAdj);
880 if (UserOffset <= TrialOffset) {
881 // User before the Trial.
882 if (TrialOffset - UserOffset <= MaxDisp)
884 // FIXME: Make use full range of soimm values.
885 } else if (NegativeOK) {
886 if (UserOffset - TrialOffset <= MaxDisp)
888 // FIXME: Make use full range of soimm values.
893 /// WaterIsInRange - Returns true if a CPE placed after the specified
894 /// Water (a basic block) will be in range for the specific MI.
896 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
897 MachineBasicBlock* Water, CPUser &U) {
898 unsigned MaxDisp = U.MaxDisp;
899 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset();
901 // If the CPE is to be inserted before the instruction, that will raise
902 // the offset of the instruction.
903 if (CPEOffset < UserOffset)
904 UserOffset += U.CPEMI->getOperand(2).getImm();
906 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoImm);
909 /// CPEIsInRange - Returns true if the distance between specific MI and
910 /// specific ConstPool entry instruction can fit in MI's displacement field.
911 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
912 MachineInstr *CPEMI, unsigned MaxDisp,
913 bool NegOk, bool DoDump) {
914 unsigned CPEOffset = GetOffsetOf(CPEMI);
915 assert((CPEOffset%4 == 0 || HasInlineAsm) && "Misaligned CPE");
918 DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
919 << " max delta=" << MaxDisp
920 << " insn address=" << UserOffset
921 << " CPE address=" << CPEOffset
922 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI);
925 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
929 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
930 /// unconditionally branches to its only successor.
931 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
932 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
935 MachineBasicBlock *Succ = *MBB->succ_begin();
936 MachineBasicBlock *Pred = *MBB->pred_begin();
937 MachineInstr *PredMI = &Pred->back();
938 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
939 || PredMI->getOpcode() == ARM::t2B)
940 return PredMI->getOperand(0).getMBB() == Succ;
945 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
946 MachineFunction *MF = BB->getParent();
947 for(unsigned i = BB->getNumber() + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
948 // Get the offset and known bits at the end of the layout predecessor.
949 unsigned Offset = BBInfo[i - 1].postOffset();
950 unsigned KnownBits = BBInfo[i - 1].postKnownBits();
952 // Add padding before an aligned block. This may teach us more bits.
953 if (unsigned Align = MF->getBlockNumbered(i)->getAlignment()) {
954 Offset = WorstCaseAlign(Offset, Align, KnownBits);
955 KnownBits = std::max(KnownBits, Align);
958 // This is where block i begins.
959 BBInfo[i].Offset = Offset;
960 BBInfo[i].KnownBits = KnownBits;
964 /// DecrementOldEntry - find the constant pool entry with index CPI
965 /// and instruction CPEMI, and decrement its refcount. If the refcount
966 /// becomes 0 remove the entry and instruction. Returns true if we removed
967 /// the entry, false if we didn't.
969 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
970 // Find the old entry. Eliminate it if it is no longer used.
971 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
972 assert(CPE && "Unexpected!");
973 if (--CPE->RefCount == 0) {
974 RemoveDeadCPEMI(CPEMI);
982 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
983 /// if not, see if an in-range clone of the CPE is in range, and if so,
984 /// change the data structures so the user references the clone. Returns:
985 /// 0 = no existing entry found
986 /// 1 = entry found, and there were no code insertions or deletions
987 /// 2 = entry found, and there were code insertions or deletions
988 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
990 MachineInstr *UserMI = U.MI;
991 MachineInstr *CPEMI = U.CPEMI;
993 // Check to see if the CPE is already in-range.
994 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
995 DEBUG(errs() << "In range\n");
999 // No. Look for previously created clones of the CPE that are in range.
1000 unsigned CPI = CPEMI->getOperand(1).getIndex();
1001 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1002 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1003 // We already tried this one
1004 if (CPEs[i].CPEMI == CPEMI)
1006 // Removing CPEs can leave empty entries, skip
1007 if (CPEs[i].CPEMI == NULL)
1009 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
1010 DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
1011 << CPEs[i].CPI << "\n");
1012 // Point the CPUser node to the replacement
1013 U.CPEMI = CPEs[i].CPEMI;
1014 // Change the CPI in the instruction operand to refer to the clone.
1015 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1016 if (UserMI->getOperand(j).isCPI()) {
1017 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1020 // Adjust the refcount of the clone...
1022 // ...and the original. If we didn't remove the old entry, none of the
1023 // addresses changed, so we don't need another pass.
1024 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1030 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1031 /// the specific unconditional branch instruction.
1032 static inline unsigned getUnconditionalBrDisp(int Opc) {
1035 return ((1<<10)-1)*2;
1037 return ((1<<23)-1)*2;
1042 return ((1<<23)-1)*4;
1045 /// LookForWater - Look for an existing entry in the WaterList in which
1046 /// we can place the CPE referenced from U so it's within range of U's MI.
1047 /// Returns true if found, false if not. If it returns true, WaterIter
1048 /// is set to the WaterList entry. For Thumb, prefer water that will not
1049 /// introduce padding to water that will. To ensure that this pass
1050 /// terminates, the CPE location for a particular CPUser is only allowed to
1051 /// move to a lower address, so search backward from the end of the list and
1052 /// prefer the first water that is in range.
1053 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1054 water_iterator &WaterIter) {
1055 if (WaterList.empty())
1058 bool FoundWaterThatWouldPad = false;
1059 water_iterator IPThatWouldPad;
1060 for (water_iterator IP = prior(WaterList.end()),
1061 B = WaterList.begin();; --IP) {
1062 MachineBasicBlock* WaterBB = *IP;
1063 // Check if water is in range and is either at a lower address than the
1064 // current "high water mark" or a new water block that was created since
1065 // the previous iteration by inserting an unconditional branch. In the
1066 // latter case, we want to allow resetting the high water mark back to
1067 // this new water since we haven't seen it before. Inserting branches
1068 // should be relatively uncommon and when it does happen, we want to be
1069 // sure to take advantage of it for all the CPEs near that block, so that
1070 // we don't insert more branches than necessary.
1071 if (WaterIsInRange(UserOffset, WaterBB, U) &&
1072 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1073 NewWaterList.count(WaterBB))) {
1074 unsigned WBBId = WaterBB->getNumber();
1075 if (isThumb && BBInfo[WBBId].postOffset()%4 != 0) {
1076 // This is valid Water, but would introduce padding. Remember
1077 // it in case we don't find any Water that doesn't do this.
1078 if (!FoundWaterThatWouldPad) {
1079 FoundWaterThatWouldPad = true;
1080 IPThatWouldPad = IP;
1090 if (FoundWaterThatWouldPad) {
1091 WaterIter = IPThatWouldPad;
1097 /// CreateNewWater - No existing WaterList entry will work for
1098 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1099 /// block is used if in range, and the conditional branch munged so control
1100 /// flow is correct. Otherwise the block is split to create a hole with an
1101 /// unconditional branch around it. In either case NewMBB is set to a
1102 /// block following which the new island can be inserted (the WaterList
1103 /// is not adjusted).
1104 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1105 unsigned UserOffset,
1106 MachineBasicBlock *&NewMBB) {
1107 CPUser &U = CPUsers[CPUserIndex];
1108 MachineInstr *UserMI = U.MI;
1109 MachineInstr *CPEMI = U.CPEMI;
1110 MachineBasicBlock *UserMBB = UserMI->getParent();
1111 unsigned OffsetOfNextBlock = BBInfo[UserMBB->getNumber()].postOffset();
1113 // If the block does not end in an unconditional branch already, and if the
1114 // end of the block is within range, make new water there. (The addition
1115 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1116 // Thumb2, 2 on Thumb1. Possible Thumb1 alignment padding is allowed for
1117 // inside OffsetIsInRange.
1118 if (BBHasFallthrough(UserMBB) &&
1119 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
1120 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1121 DEBUG(errs() << "Split at end of block\n");
1122 if (&UserMBB->back() == UserMI)
1123 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
1124 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1125 // Add an unconditional branch from UserMBB to fallthrough block.
1126 // Record it for branch lengthening; this new branch will not get out of
1127 // range, but if the preceding conditional branch is out of range, the
1128 // targets will be exchanged, and the altered branch may be out of
1129 // range, so the machinery has to know about it.
1130 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1132 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1134 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1135 .addImm(ARMCC::AL).addReg(0);
1136 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1137 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1138 MaxDisp, false, UncondBr));
1139 int delta = isThumb1 ? 2 : 4;
1140 BBInfo[UserMBB->getNumber()].Size += delta;
1141 AdjustBBOffsetsAfter(UserMBB);
1143 // What a big block. Find a place within the block to split it.
1144 // This is a little tricky on Thumb1 since instructions are 2 bytes
1145 // and constant pool entries are 4 bytes: if instruction I references
1146 // island CPE, and instruction I+1 references CPE', it will
1147 // not work well to put CPE as far forward as possible, since then
1148 // CPE' cannot immediately follow it (that location is 2 bytes
1149 // farther away from I+1 than CPE was from I) and we'd need to create
1150 // a new island. So, we make a first guess, then walk through the
1151 // instructions between the one currently being looked at and the
1152 // possible insertion point, and make sure any other instructions
1153 // that reference CPEs will be able to use the same island area;
1154 // if not, we back up the insertion point.
1156 // The 4 in the following is for the unconditional branch we'll be
1157 // inserting (allows for long branch on Thumb1). Alignment of the
1158 // island is handled inside OffsetIsInRange.
1159 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1160 // This could point off the end of the block if we've already got
1161 // constant pool entries following this block; only the last one is
1162 // in the water list. Back past any possible branches (allow for a
1163 // conditional and a maximally long unconditional).
1164 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1165 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1167 unsigned EndInsertOffset = BaseInsertOffset +
1168 CPEMI->getOperand(2).getImm();
1169 MachineBasicBlock::iterator MI = UserMI;
1171 unsigned CPUIndex = CPUserIndex+1;
1172 unsigned NumCPUsers = CPUsers.size();
1173 MachineInstr *LastIT = 0;
1174 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1175 Offset < BaseInsertOffset;
1176 Offset += TII->GetInstSizeInBytes(MI),
1177 MI = llvm::next(MI)) {
1178 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1179 CPUser &U = CPUsers[CPUIndex];
1180 if (!OffsetIsInRange(Offset, EndInsertOffset,
1181 U.MaxDisp, U.NegOk, U.IsSoImm)) {
1182 BaseInsertOffset -= (isThumb1 ? 2 : 4);
1183 EndInsertOffset -= (isThumb1 ? 2 : 4);
1185 // This is overly conservative, as we don't account for CPEMIs
1186 // being reused within the block, but it doesn't matter much.
1187 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1191 // Remember the last IT instruction.
1192 if (MI->getOpcode() == ARM::t2IT)
1196 DEBUG(errs() << "Split in middle of big block\n");
1199 // Avoid splitting an IT block.
1201 unsigned PredReg = 0;
1202 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1203 if (CC != ARMCC::AL)
1206 NewMBB = SplitBlockBeforeInstr(MI);
1210 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1211 /// is out-of-range. If so, pick up the constant pool value and move it some
1212 /// place in-range. Return true if we changed any addresses (thus must run
1213 /// another pass of branch lengthening), false otherwise.
1214 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
1215 unsigned CPUserIndex) {
1216 CPUser &U = CPUsers[CPUserIndex];
1217 MachineInstr *UserMI = U.MI;
1218 MachineInstr *CPEMI = U.CPEMI;
1219 unsigned CPI = CPEMI->getOperand(1).getIndex();
1220 unsigned Size = CPEMI->getOperand(2).getImm();
1221 // Compute this only once, it's expensive. The 4 or 8 is the value the
1222 // hardware keeps in the PC.
1223 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1225 // See if the current entry is within range, or there is a clone of it
1227 int result = LookForExistingCPEntry(U, UserOffset);
1228 if (result==1) return false;
1229 else if (result==2) return true;
1231 // No existing clone of this CPE is within range.
1232 // We will be generating a new clone. Get a UID for it.
1233 unsigned ID = AFI->createPICLabelUId();
1235 // Look for water where we can place this CPE.
1236 MachineBasicBlock *NewIsland = MF.CreateMachineBasicBlock();
1237 MachineBasicBlock *NewMBB;
1239 if (LookForWater(U, UserOffset, IP)) {
1240 DEBUG(errs() << "found water in range\n");
1241 MachineBasicBlock *WaterBB = *IP;
1243 // If the original WaterList entry was "new water" on this iteration,
1244 // propagate that to the new island. This is just keeping NewWaterList
1245 // updated to match the WaterList, which will be updated below.
1246 if (NewWaterList.count(WaterBB)) {
1247 NewWaterList.erase(WaterBB);
1248 NewWaterList.insert(NewIsland);
1250 // The new CPE goes before the following block (NewMBB).
1251 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1255 DEBUG(errs() << "No water found\n");
1256 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1258 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1259 // called while handling branches so that the water will be seen on the
1260 // next iteration for constant pools, but in this context, we don't want
1261 // it. Check for this so it will be removed from the WaterList.
1262 // Also remove any entry from NewWaterList.
1263 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1264 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1265 if (IP != WaterList.end())
1266 NewWaterList.erase(WaterBB);
1268 // We are adding new water. Update NewWaterList.
1269 NewWaterList.insert(NewIsland);
1272 // Remove the original WaterList entry; we want subsequent insertions in
1273 // this vicinity to go after the one we're about to insert. This
1274 // considerably reduces the number of times we have to move the same CPE
1275 // more than once and is also important to ensure the algorithm terminates.
1276 if (IP != WaterList.end())
1277 WaterList.erase(IP);
1279 // Okay, we know we can put an island before NewMBB now, do it!
1280 MF.insert(NewMBB, NewIsland);
1282 // Update internal data structures to account for the newly inserted MBB.
1283 UpdateForInsertedWaterBlock(NewIsland);
1285 // Decrement the old entry, and remove it if refcount becomes 0.
1286 DecrementOldEntry(CPI, CPEMI);
1288 // Now that we have an island to add the CPE to, clone the original CPE and
1289 // add it to the island.
1290 U.HighWaterMark = NewIsland;
1291 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1292 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1293 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1296 // Mark the basic block as 4-byte aligned as required by the const-pool entry.
1297 NewIsland->setAlignment(2);
1299 // Increase the size of the island block to account for the new entry.
1300 BBInfo[NewIsland->getNumber()].Size += Size;
1301 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1303 // Finally, change the CPI in the instruction operand to be ID.
1304 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1305 if (UserMI->getOperand(i).isCPI()) {
1306 UserMI->getOperand(i).setIndex(ID);
1310 DEBUG(errs() << " Moved CPE to #" << ID << " CPI=" << CPI
1311 << '\t' << *UserMI);
1316 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1317 /// sizes and offsets of impacted basic blocks.
1318 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1319 MachineBasicBlock *CPEBB = CPEMI->getParent();
1320 unsigned Size = CPEMI->getOperand(2).getImm();
1321 CPEMI->eraseFromParent();
1322 BBInfo[CPEBB->getNumber()].Size -= Size;
1323 // All succeeding offsets have the current size value added in, fix this.
1324 if (CPEBB->empty()) {
1325 // In thumb1 mode, the size of island may be padded by two to compensate for
1326 // the alignment requirement. Then it will now be 2 when the block is
1327 // empty, so fix this.
1328 // All succeeding offsets have the current size value added in, fix this.
1329 if (BBInfo[CPEBB->getNumber()].Size != 0) {
1330 Size += BBInfo[CPEBB->getNumber()].Size;
1331 BBInfo[CPEBB->getNumber()].Size = 0;
1334 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1335 CPEBB->setAlignment(0);
1337 AdjustBBOffsetsAfter(CPEBB);
1338 // An island has only one predecessor BB and one successor BB. Check if
1339 // this BB's predecessor jumps directly to this BB's successor. This
1340 // shouldn't happen currently.
1341 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1342 // FIXME: remove the empty blocks after all the work is done?
1345 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1347 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1348 unsigned MadeChange = false;
1349 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1350 std::vector<CPEntry> &CPEs = CPEntries[i];
1351 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1352 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1353 RemoveDeadCPEMI(CPEs[j].CPEMI);
1354 CPEs[j].CPEMI = NULL;
1362 /// BBIsInRange - Returns true if the distance between specific MI and
1363 /// specific BB can fit in MI's displacement field.
1364 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1366 unsigned PCAdj = isThumb ? 4 : 8;
1367 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1368 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1370 DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
1371 << " from BB#" << MI->getParent()->getNumber()
1372 << " max delta=" << MaxDisp
1373 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1374 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1376 if (BrOffset <= DestOffset) {
1377 // Branch before the Dest.
1378 if (DestOffset-BrOffset <= MaxDisp)
1381 if (BrOffset-DestOffset <= MaxDisp)
1387 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1388 /// away to fit in its displacement field.
1389 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br) {
1390 MachineInstr *MI = Br.MI;
1391 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1393 // Check to see if the DestBB is already in-range.
1394 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1398 return FixUpUnconditionalBr(MF, Br);
1399 return FixUpConditionalBr(MF, Br);
1402 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1403 /// too far away to fit in its displacement field. If the LR register has been
1404 /// spilled in the epilogue, then we can use BL to implement a far jump.
1405 /// Otherwise, add an intermediate branch instruction to a branch.
1407 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br) {
1408 MachineInstr *MI = Br.MI;
1409 MachineBasicBlock *MBB = MI->getParent();
1411 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1413 // Use BL to implement far jump.
1414 Br.MaxDisp = (1 << 21) * 2;
1415 MI->setDesc(TII->get(ARM::tBfar));
1416 BBInfo[MBB->getNumber()].Size += 2;
1417 AdjustBBOffsetsAfter(MBB);
1421 DEBUG(errs() << " Changed B to long jump " << *MI);
1426 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1427 /// far away to fit in its displacement field. It is converted to an inverse
1428 /// conditional branch + an unconditional branch to the destination.
1430 ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br) {
1431 MachineInstr *MI = Br.MI;
1432 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1434 // Add an unconditional branch to the destination and invert the branch
1435 // condition to jump over it:
1441 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1442 CC = ARMCC::getOppositeCondition(CC);
1443 unsigned CCReg = MI->getOperand(2).getReg();
1445 // If the branch is at the end of its MBB and that has a fall-through block,
1446 // direct the updated conditional branch to the fall-through block. Otherwise,
1447 // split the MBB before the next instruction.
1448 MachineBasicBlock *MBB = MI->getParent();
1449 MachineInstr *BMI = &MBB->back();
1450 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1454 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1455 BMI->getOpcode() == Br.UncondBr) {
1456 // Last MI in the BB is an unconditional branch. Can we simply invert the
1457 // condition and swap destinations:
1463 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1464 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1465 DEBUG(errs() << " Invert Bcc condition and swap its destination with "
1467 BMI->getOperand(0).setMBB(DestBB);
1468 MI->getOperand(0).setMBB(NewDest);
1469 MI->getOperand(1).setImm(CC);
1476 SplitBlockBeforeInstr(MI);
1477 // No need for the branch to the next block. We're adding an unconditional
1478 // branch to the destination.
1479 int delta = TII->GetInstSizeInBytes(&MBB->back());
1480 BBInfo[MBB->getNumber()].Size -= delta;
1481 MBB->back().eraseFromParent();
1482 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1484 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1486 DEBUG(errs() << " Insert B to BB#" << DestBB->getNumber()
1487 << " also invert condition and change dest. to BB#"
1488 << NextBB->getNumber() << "\n");
1490 // Insert a new conditional branch and a new unconditional branch.
1491 // Also update the ImmBranch as well as adding a new entry for the new branch.
1492 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1493 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1494 Br.MI = &MBB->back();
1495 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1497 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1498 .addImm(ARMCC::AL).addReg(0);
1500 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1501 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1502 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1503 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1505 // Remove the old conditional branch. It may or may not still be in MBB.
1506 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1507 MI->eraseFromParent();
1508 AdjustBBOffsetsAfter(MBB);
1512 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1513 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1514 /// to do this if tBfar is not used.
1515 bool ARMConstantIslands::UndoLRSpillRestore() {
1516 bool MadeChange = false;
1517 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1518 MachineInstr *MI = PushPopMIs[i];
1519 // First two operands are predicates.
1520 if (MI->getOpcode() == ARM::tPOP_RET &&
1521 MI->getOperand(2).getReg() == ARM::PC &&
1522 MI->getNumExplicitOperands() == 3) {
1523 // Create the new insn and copy the predicate from the old.
1524 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1525 .addOperand(MI->getOperand(0))
1526 .addOperand(MI->getOperand(1));
1527 MI->eraseFromParent();
1534 bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
1535 bool MadeChange = false;
1537 // Shrink ADR and LDR from constantpool.
1538 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1539 CPUser &U = CPUsers[i];
1540 unsigned Opcode = U.MI->getOpcode();
1541 unsigned NewOpc = 0;
1546 case ARM::t2LEApcrel:
1547 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1548 NewOpc = ARM::tLEApcrel;
1554 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1555 NewOpc = ARM::tLDRpci;
1565 unsigned UserOffset = GetOffsetOf(U.MI) + 4;
1566 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1567 // FIXME: Check if offset is multiple of scale if scale is not 4.
1568 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1569 U.MI->setDesc(TII->get(NewOpc));
1570 MachineBasicBlock *MBB = U.MI->getParent();
1571 BBInfo[MBB->getNumber()].Size -= 2;
1572 AdjustBBOffsetsAfter(MBB);
1578 MadeChange |= OptimizeThumb2Branches(MF);
1579 MadeChange |= OptimizeThumb2JumpTables(MF);
1583 bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
1584 bool MadeChange = false;
1586 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1587 ImmBranch &Br = ImmBranches[i];
1588 unsigned Opcode = Br.MI->getOpcode();
1589 unsigned NewOpc = 0;
1607 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1608 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1609 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1610 Br.MI->setDesc(TII->get(NewOpc));
1611 MachineBasicBlock *MBB = Br.MI->getParent();
1612 BBInfo[MBB->getNumber()].Size -= 2;
1613 AdjustBBOffsetsAfter(MBB);
1619 Opcode = Br.MI->getOpcode();
1620 if (Opcode != ARM::tBcc)
1624 unsigned PredReg = 0;
1625 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1626 if (Pred == ARMCC::EQ)
1628 else if (Pred == ARMCC::NE)
1629 NewOpc = ARM::tCBNZ;
1632 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1633 // Check if the distance is within 126. Subtract starting offset by 2
1634 // because the cmp will be eliminated.
1635 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1636 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1637 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1638 MachineBasicBlock::iterator CmpMI = Br.MI;
1639 if (CmpMI != Br.MI->getParent()->begin()) {
1641 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1642 unsigned Reg = CmpMI->getOperand(0).getReg();
1643 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1644 if (Pred == ARMCC::AL &&
1645 CmpMI->getOperand(1).getImm() == 0 &&
1646 isARMLowRegister(Reg)) {
1647 MachineBasicBlock *MBB = Br.MI->getParent();
1648 MachineInstr *NewBR =
1649 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1650 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1651 CmpMI->eraseFromParent();
1652 Br.MI->eraseFromParent();
1654 BBInfo[MBB->getNumber()].Size -= 2;
1655 AdjustBBOffsetsAfter(MBB);
1667 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1668 /// jumptables when it's possible.
1669 bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
1670 bool MadeChange = false;
1672 // FIXME: After the tables are shrunk, can we get rid some of the
1673 // constantpool tables?
1674 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1675 if (MJTI == 0) return false;
1677 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1678 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1679 MachineInstr *MI = T2JumpTables[i];
1680 const MCInstrDesc &MCID = MI->getDesc();
1681 unsigned NumOps = MCID.getNumOperands();
1682 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1683 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1684 unsigned JTI = JTOP.getIndex();
1685 assert(JTI < JT.size());
1688 bool HalfWordOk = true;
1689 unsigned JTOffset = GetOffsetOf(MI) + 4;
1690 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1691 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1692 MachineBasicBlock *MBB = JTBBs[j];
1693 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1694 // Negative offset is not ok. FIXME: We should change BB layout to make
1695 // sure all the branches are forward.
1696 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1698 unsigned TBHLimit = ((1<<16)-1)*2;
1699 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1701 if (!ByteOk && !HalfWordOk)
1705 if (ByteOk || HalfWordOk) {
1706 MachineBasicBlock *MBB = MI->getParent();
1707 unsigned BaseReg = MI->getOperand(0).getReg();
1708 bool BaseRegKill = MI->getOperand(0).isKill();
1711 unsigned IdxReg = MI->getOperand(1).getReg();
1712 bool IdxRegKill = MI->getOperand(1).isKill();
1714 // Scan backwards to find the instruction that defines the base
1715 // register. Due to post-RA scheduling, we can't count on it
1716 // immediately preceding the branch instruction.
1717 MachineBasicBlock::iterator PrevI = MI;
1718 MachineBasicBlock::iterator B = MBB->begin();
1719 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1722 // If for some reason we didn't find it, we can't do anything, so
1723 // just skip this one.
1724 if (!PrevI->definesRegister(BaseReg))
1727 MachineInstr *AddrMI = PrevI;
1729 // Examine the instruction that calculates the jumptable entry address.
1730 // Make sure it only defines the base register and kills any uses
1731 // other than the index register.
1732 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1733 const MachineOperand &MO = AddrMI->getOperand(k);
1734 if (!MO.isReg() || !MO.getReg())
1736 if (MO.isDef() && MO.getReg() != BaseReg) {
1740 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1748 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1749 // that gave us the initial base register definition.
1750 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1753 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1754 // to delete it as well.
1755 MachineInstr *LeaMI = PrevI;
1756 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1757 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1758 LeaMI->getOperand(0).getReg() != BaseReg)
1764 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1765 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1766 .addReg(IdxReg, getKillRegState(IdxRegKill))
1767 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1768 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1769 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1770 // is 2-byte aligned. For now, asm printer will fix it up.
1771 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1772 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1773 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1774 OrigSize += TII->GetInstSizeInBytes(MI);
1776 AddrMI->eraseFromParent();
1777 LeaMI->eraseFromParent();
1778 MI->eraseFromParent();
1780 int delta = OrigSize - NewSize;
1781 BBInfo[MBB->getNumber()].Size -= delta;
1782 AdjustBBOffsetsAfter(MBB);
1792 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1793 /// jump tables always branch forwards, since that's what tbb and tbh need.
1794 bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
1795 bool MadeChange = false;
1797 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
1798 if (MJTI == 0) return false;
1800 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1801 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1802 MachineInstr *MI = T2JumpTables[i];
1803 const MCInstrDesc &MCID = MI->getDesc();
1804 unsigned NumOps = MCID.getNumOperands();
1805 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1806 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1807 unsigned JTI = JTOP.getIndex();
1808 assert(JTI < JT.size());
1810 // We prefer if target blocks for the jump table come after the jump
1811 // instruction so we can use TB[BH]. Loop through the target blocks
1812 // and try to adjust them such that that's true.
1813 int JTNumber = MI->getParent()->getNumber();
1814 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1815 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1816 MachineBasicBlock *MBB = JTBBs[j];
1817 int DTNumber = MBB->getNumber();
1819 if (DTNumber < JTNumber) {
1820 // The destination precedes the switch. Try to move the block forward
1821 // so we have a positive offset.
1822 MachineBasicBlock *NewBB =
1823 AdjustJTTargetBlockForward(MBB, MI->getParent());
1825 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
1834 MachineBasicBlock *ARMConstantIslands::
1835 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
1837 MachineFunction &MF = *BB->getParent();
1839 // If the destination block is terminated by an unconditional branch,
1840 // try to move it; otherwise, create a new block following the jump
1841 // table that branches back to the actual target. This is a very simple
1842 // heuristic. FIXME: We can definitely improve it.
1843 MachineBasicBlock *TBB = 0, *FBB = 0;
1844 SmallVector<MachineOperand, 4> Cond;
1845 SmallVector<MachineOperand, 4> CondPrior;
1846 MachineFunction::iterator BBi = BB;
1847 MachineFunction::iterator OldPrior = prior(BBi);
1849 // If the block terminator isn't analyzable, don't try to move the block
1850 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
1852 // If the block ends in an unconditional branch, move it. The prior block
1853 // has to have an analyzable terminator for us to move this one. Be paranoid
1854 // and make sure we're not trying to move the entry block of the function.
1855 if (!B && Cond.empty() && BB != MF.begin() &&
1856 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
1857 BB->moveAfter(JTBB);
1858 OldPrior->updateTerminator();
1859 BB->updateTerminator();
1860 // Update numbering to account for the block being moved.
1861 MF.RenumberBlocks();
1866 // Create a new MBB for the code after the jump BB.
1867 MachineBasicBlock *NewBB =
1868 MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
1869 MachineFunction::iterator MBBI = JTBB; ++MBBI;
1870 MF.insert(MBBI, NewBB);
1872 // Add an unconditional branch from NewBB to BB.
1873 // There doesn't seem to be meaningful DebugInfo available; this doesn't
1874 // correspond directly to anything in the source.
1875 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
1876 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
1877 .addImm(ARMCC::AL).addReg(0);
1879 // Update internal data structures to account for the newly inserted MBB.
1880 MF.RenumberBlocks(NewBB);
1883 NewBB->addSuccessor(BB);
1884 JTBB->removeSuccessor(BB);
1885 JTBB->addSuccessor(NewBB);