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 "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
32 STATISTIC(NumCPEs, "Number of constpool entries");
33 STATISTIC(NumSplit, "Number of uncond branches inserted");
34 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
38 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39 /// requires constant pool entries to be scattered among the instructions
40 /// inside a function. To do this, it completely ignores the normal LLVM
41 /// constant pool; instead, it places constants wherever it feels like with
42 /// special instructions.
44 /// The terminology used in this pass includes:
45 /// Islands - Clumps of constants placed in the function.
46 /// Water - Potential places where an island could be formed.
47 /// CPE - A constant pool entry that has been placed somewhere, which
48 /// tracks a list of users.
49 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
51 /// by MBB Number. The two-byte pads required for Thumb alignment are
52 /// counted as part of the following block (i.e., the offset and size for
53 /// a padded block will both be ==2 mod 4).
54 std::vector<unsigned> BBSizes;
56 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
57 /// The two-byte pads required for Thumb alignment are counted as part of
58 /// the following block.
59 std::vector<unsigned> BBOffsets;
61 /// WaterList - A sorted list of basic blocks where islands could be placed
62 /// (i.e. blocks that don't fall through to the following block, due
63 /// to a return, unreachable, or unconditional branch).
64 std::vector<MachineBasicBlock*> WaterList;
66 /// CPUser - One user of a constant pool, keeping the machine instruction
67 /// pointer, the constant pool being referenced, and the max displacement
68 /// allowed from the instruction to the CP.
73 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
74 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
77 /// CPUsers - Keep track of all of the machine instructions that use various
78 /// constant pools and their max displacement.
79 std::vector<CPUser> CPUsers;
81 /// CPEntry - One per constant pool entry, keeping the machine instruction
82 /// pointer, the constpool index, and the number of CPUser's which
83 /// reference this entry.
88 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
89 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
92 /// CPEntries - Keep track of all of the constant pool entry machine
93 /// instructions. For each original constpool index (i.e. those that
94 /// existed upon entry to this pass), it keeps a vector of entries.
95 /// Original elements are cloned as we go along; the clones are
96 /// put in the vector of the original element, but have distinct CPIs.
97 std::vector<std::vector<CPEntry> > CPEntries;
99 /// ImmBranch - One per immediate branch, keeping the machine instruction
100 /// pointer, conditional or unconditional, the max displacement,
101 /// and (if isCond is true) the corresponding unconditional branch
105 unsigned MaxDisp : 31;
108 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
109 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
112 /// ImmBranches - Keep track of all the immediate branch instructions.
114 std::vector<ImmBranch> ImmBranches;
116 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
118 SmallVector<MachineInstr*, 4> PushPopMIs;
120 /// HasFarJump - True if any far jump instruction has been emitted during
121 /// the branch fix up pass.
124 const TargetInstrInfo *TII;
125 ARMFunctionInfo *AFI;
130 ARMConstantIslands() : MachineFunctionPass(&ID) {}
132 virtual bool runOnMachineFunction(MachineFunction &Fn);
134 virtual const char *getPassName() const {
135 return "ARM constant island placement and branch shortening pass";
139 void DoInitialPlacement(MachineFunction &Fn,
140 std::vector<MachineInstr*> &CPEMIs);
141 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
142 void InitialFunctionScan(MachineFunction &Fn,
143 const std::vector<MachineInstr*> &CPEMIs);
144 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
145 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
146 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
147 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
148 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
149 bool LookForWater(CPUser&U, unsigned UserOffset,
150 MachineBasicBlock** NewMBB);
151 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
152 std::vector<MachineBasicBlock*>::iterator IP);
153 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
154 MachineBasicBlock** NewMBB);
155 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
156 void RemoveDeadCPEMI(MachineInstr *CPEMI);
157 bool RemoveUnusedCPEntries();
158 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
159 MachineInstr *CPEMI, unsigned Disp,
161 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
163 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
164 unsigned Disp, bool NegativeOK);
165 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
166 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
167 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
168 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
169 bool UndoLRSpillRestore();
171 unsigned GetOffsetOf(MachineInstr *MI) const;
173 void verify(MachineFunction &Fn);
175 char ARMConstantIslands::ID = 0;
178 /// verify - check BBOffsets, BBSizes, alignment of islands
179 void ARMConstantIslands::verify(MachineFunction &Fn) {
180 assert(BBOffsets.size() == BBSizes.size());
181 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
182 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
184 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
186 MachineBasicBlock *MBB = MBBI;
188 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
189 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
190 BBSizes[MBB->getNumber()]%4 == 0) ||
191 (BBOffsets[MBB->getNumber()]%4 != 0 &&
192 BBSizes[MBB->getNumber()]%4 != 0));
197 /// print block size and offset information - debugging
198 void ARMConstantIslands::dumpBBs() {
199 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
200 DOUT << "block " << J << " offset " << BBOffsets[J] <<
201 " size " << BBSizes[J] << "\n";
205 /// createARMConstantIslandPass - returns an instance of the constpool
207 FunctionPass *llvm::createARMConstantIslandPass() {
208 return new ARMConstantIslands();
211 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
212 MachineConstantPool &MCP = *Fn.getConstantPool();
214 TII = Fn.getTarget().getInstrInfo();
215 AFI = Fn.getInfo<ARMFunctionInfo>();
216 isThumb = AFI->isThumbFunction();
217 isThumb2 = AFI->isThumb2Function();
221 // Renumber all of the machine basic blocks in the function, guaranteeing that
222 // the numbers agree with the position of the block in the function.
225 /// Thumb functions containing constant pools get 2-byte alignment.
226 /// This is so we can keep exact track of where the alignment padding goes.
228 AFI->setAlign(isThumb ? 1U : 2U);
230 // Perform the initial placement of the constant pool entries. To start with,
231 // we put them all at the end of the function.
232 std::vector<MachineInstr*> CPEMIs;
233 if (!MCP.isEmpty()) {
234 DoInitialPlacement(Fn, CPEMIs);
239 /// The next UID to take is the first unused one.
240 AFI->initConstPoolEntryUId(CPEMIs.size());
242 // Do the initial scan of the function, building up information about the
243 // sizes of each block, the location of all the water, and finding all of the
244 // constant pool users.
245 InitialFunctionScan(Fn, CPEMIs);
248 /// Remove dead constant pool entries.
249 RemoveUnusedCPEntries();
251 // Iteratively place constant pool entries and fix up branches until there
253 bool MadeChange = false;
256 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
257 Change |= HandleConstantPoolUser(Fn, i);
259 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
260 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
267 // After a while, this might be made debug-only, but it is not expensive.
270 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
271 // Undo the spill / restore of LR if possible.
272 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
273 MadeChange |= UndoLRSpillRestore();
286 /// DoInitialPlacement - Perform the initial placement of the constant pool
287 /// entries. To start with, we put them all at the end of the function.
288 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
289 std::vector<MachineInstr*> &CPEMIs) {
290 // Create the basic block to hold the CPE's.
291 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
294 // Add all of the constants from the constant pool to the end block, use an
295 // identity mapping of CPI's to CPE's.
296 const std::vector<MachineConstantPoolEntry> &CPs =
297 Fn.getConstantPool()->getConstants();
299 const TargetData &TD = *Fn.getTarget().getTargetData();
300 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
301 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
302 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
303 // we would have to pad them out or something so that instructions stay
305 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
306 MachineInstr *CPEMI =
307 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
308 .addImm(i).addConstantPoolIndex(i).addImm(Size);
309 CPEMIs.push_back(CPEMI);
311 // Add a new CPEntry, but no corresponding CPUser yet.
312 std::vector<CPEntry> CPEs;
313 CPEs.push_back(CPEntry(CPEMI, i));
314 CPEntries.push_back(CPEs);
316 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
320 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
321 /// into the block immediately after it.
322 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
323 // Get the next machine basic block in the function.
324 MachineFunction::iterator MBBI = MBB;
325 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
328 MachineBasicBlock *NextBB = next(MBBI);
329 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
330 E = MBB->succ_end(); I != E; ++I)
337 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
338 /// look up the corresponding CPEntry.
339 ARMConstantIslands::CPEntry
340 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
341 const MachineInstr *CPEMI) {
342 std::vector<CPEntry> &CPEs = CPEntries[CPI];
343 // Number of entries per constpool index should be small, just do a
345 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
346 if (CPEs[i].CPEMI == CPEMI)
352 /// InitialFunctionScan - Do the initial scan of the function, building up
353 /// information about the sizes of each block, the location of all the water,
354 /// and finding all of the constant pool users.
355 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
356 const std::vector<MachineInstr*> &CPEMIs) {
358 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
360 MachineBasicBlock &MBB = *MBBI;
362 // If this block doesn't fall through into the next MBB, then this is
363 // 'water' that a constant pool island could be placed.
364 if (!BBHasFallthrough(&MBB))
365 WaterList.push_back(&MBB);
367 unsigned MBBSize = 0;
368 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
370 // Add instruction size to MBBSize.
371 MBBSize += TII->GetInstSizeInBytes(I);
373 int Opc = I->getOpcode();
374 if (I->getDesc().isBranch()) {
383 case ARM::t2BR_JTadd:
384 // A Thumb table jump may involve padding; for the offsets to
385 // be right, functions containing these must be 4-byte aligned.
387 if ((Offset+MBBSize)%4 != 0)
388 MBBSize += 2; // padding
389 continue; // Does not get an entry in ImmBranches
391 continue; // Ignore other JT branches
422 // Record this immediate branch.
423 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
424 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
427 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
428 PushPopMIs.push_back(I);
430 // Scan the instructions for constant pool operands.
431 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
432 if (I->getOperand(op).isCPI()) {
433 // We found one. The addressing mode tells us the max displacement
434 // from the PC that this instruction permits.
436 // Basic size info comes from the TSFlags field.
439 unsigned TSFlags = I->getDesc().TSFlags;
440 switch (TSFlags & ARMII::AddrModeMask) {
442 // Constant pool entries can reach anything.
443 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
445 if (I->getOpcode() == ARM::tLEApcrel) {
446 Bits = 8; // Taking the address of a CP entry.
449 assert(0 && "Unknown addressing mode for CP reference!");
450 case ARMII::AddrMode1: // AM1: 8 bits << 2
452 Scale = 4; // Taking the address of a CP entry.
454 case ARMII::AddrMode2:
455 Bits = 12; // +-offset_12
457 case ARMII::AddrMode3:
458 Bits = 8; // +-offset_8
460 // addrmode4 has no immediate offset.
461 case ARMII::AddrMode5:
463 Scale = 4; // +-(offset_8*4)
465 // addrmode6 has no immediate offset.
466 case ARMII::AddrModeT1_1:
467 Bits = 5; // +offset_5
469 case ARMII::AddrModeT1_2:
471 Scale = 2; // +(offset_5*2)
473 case ARMII::AddrModeT1_4:
475 Scale = 4; // +(offset_5*4)
477 case ARMII::AddrModeT1_s:
479 Scale = 4; // +(offset_8*4)
481 case ARMII::AddrModeT2_pc:
482 Bits = 12; // +-offset_12
486 // Remember that this is a user of a CP entry.
487 unsigned CPI = I->getOperand(op).getIndex();
488 MachineInstr *CPEMI = CPEMIs[CPI];
489 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
490 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
492 // Increment corresponding CPEntry reference count.
493 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
494 assert(CPE && "Cannot find a corresponding CPEntry!");
497 // Instructions can only use one CP entry, don't bother scanning the
498 // rest of the operands.
503 // In thumb mode, if this block is a constpool island, we may need padding
504 // so it's aligned on 4 byte boundary.
507 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
511 BBSizes.push_back(MBBSize);
512 BBOffsets.push_back(Offset);
517 /// GetOffsetOf - Return the current offset of the specified machine instruction
518 /// from the start of the function. This offset changes as stuff is moved
519 /// around inside the function.
520 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
521 MachineBasicBlock *MBB = MI->getParent();
523 // The offset is composed of two things: the sum of the sizes of all MBB's
524 // before this instruction's block, and the offset from the start of the block
526 unsigned Offset = BBOffsets[MBB->getNumber()];
528 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
529 // alignment padding, and compensate if so.
531 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
535 // Sum instructions before MI in MBB.
536 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
537 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
538 if (&*I == MI) return Offset;
539 Offset += TII->GetInstSizeInBytes(I);
543 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
545 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
546 const MachineBasicBlock *RHS) {
547 return LHS->getNumber() < RHS->getNumber();
550 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
551 /// machine function, it upsets all of the block numbers. Renumber the blocks
552 /// and update the arrays that parallel this numbering.
553 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
554 // Renumber the MBB's to keep them consequtive.
555 NewBB->getParent()->RenumberBlocks(NewBB);
557 // Insert a size into BBSizes to align it properly with the (newly
558 // renumbered) block numbers.
559 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
561 // Likewise for BBOffsets.
562 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
564 // Next, update WaterList. Specifically, we need to add NewMBB as having
565 // available water after it.
566 std::vector<MachineBasicBlock*>::iterator IP =
567 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
569 WaterList.insert(IP, NewBB);
573 /// Split the basic block containing MI into two blocks, which are joined by
574 /// an unconditional branch. Update datastructures and renumber blocks to
575 /// account for this change and returns the newly created block.
576 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
577 MachineBasicBlock *OrigBB = MI->getParent();
578 MachineFunction &MF = *OrigBB->getParent();
580 // Create a new MBB for the code after the OrigBB.
581 MachineBasicBlock *NewBB =
582 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
583 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
584 MF.insert(MBBI, NewBB);
586 // Splice the instructions starting with MI over to NewBB.
587 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
589 // Add an unconditional branch from OrigBB to NewBB.
590 // Note the new unconditional branch is not being recorded.
591 // There doesn't seem to be meaningful DebugInfo available; this doesn't
592 // correspond to anything in the source.
593 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
594 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
597 // Update the CFG. All succs of OrigBB are now succs of NewBB.
598 while (!OrigBB->succ_empty()) {
599 MachineBasicBlock *Succ = *OrigBB->succ_begin();
600 OrigBB->removeSuccessor(Succ);
601 NewBB->addSuccessor(Succ);
603 // This pass should be run after register allocation, so there should be no
604 // PHI nodes to update.
605 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
606 && "PHI nodes should be eliminated by now!");
609 // OrigBB branches to NewBB.
610 OrigBB->addSuccessor(NewBB);
612 // Update internal data structures to account for the newly inserted MBB.
613 // This is almost the same as UpdateForInsertedWaterBlock, except that
614 // the Water goes after OrigBB, not NewBB.
615 MF.RenumberBlocks(NewBB);
617 // Insert a size into BBSizes to align it properly with the (newly
618 // renumbered) block numbers.
619 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
621 // Likewise for BBOffsets.
622 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
624 // Next, update WaterList. Specifically, we need to add OrigMBB as having
625 // available water after it (but not if it's already there, which happens
626 // when splitting before a conditional branch that is followed by an
627 // unconditional branch - in that case we want to insert NewBB).
628 std::vector<MachineBasicBlock*>::iterator IP =
629 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
631 MachineBasicBlock* WaterBB = *IP;
632 if (WaterBB == OrigBB)
633 WaterList.insert(next(IP), NewBB);
635 WaterList.insert(IP, OrigBB);
637 // Figure out how large the first NewMBB is. (It cannot
638 // contain a constpool_entry or tablejump.)
639 unsigned NewBBSize = 0;
640 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
642 NewBBSize += TII->GetInstSizeInBytes(I);
644 unsigned OrigBBI = OrigBB->getNumber();
645 unsigned NewBBI = NewBB->getNumber();
646 // Set the size of NewBB in BBSizes.
647 BBSizes[NewBBI] = NewBBSize;
649 // We removed instructions from UserMBB, subtract that off from its size.
650 // Add 2 or 4 to the block to count the unconditional branch we added to it.
651 unsigned delta = isThumb ? 2 : 4;
652 BBSizes[OrigBBI] -= NewBBSize - delta;
654 // ...and adjust BBOffsets for NewBB accordingly.
655 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
657 // All BBOffsets following these blocks must be modified.
658 AdjustBBOffsetsAfter(NewBB, delta);
663 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
664 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
665 /// constant pool entry).
666 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
667 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
668 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
669 // purposes of the displacement computation; compensate for that here.
670 // Effectively, the valid range of displacements is 2 bytes smaller for such
672 if (isThumb && UserOffset%4 !=0)
674 // CPEs will be rounded up to a multiple of 4.
675 if (isThumb && TrialOffset%4 != 0)
678 if (UserOffset <= TrialOffset) {
679 // User before the Trial.
680 if (TrialOffset-UserOffset <= MaxDisp)
682 } else if (NegativeOK) {
683 if (UserOffset-TrialOffset <= MaxDisp)
689 /// WaterIsInRange - Returns true if a CPE placed after the specified
690 /// Water (a basic block) will be in range for the specific MI.
692 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
693 MachineBasicBlock* Water, CPUser &U)
695 unsigned MaxDisp = U.MaxDisp;
696 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
697 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
698 BBSizes[Water->getNumber()];
700 // If the CPE is to be inserted before the instruction, that will raise
701 // the offset of the instruction. (Currently applies only to ARM, so
702 // no alignment compensation attempted here.)
703 if (CPEOffset < UserOffset)
704 UserOffset += U.CPEMI->getOperand(2).getImm();
706 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
709 /// CPEIsInRange - Returns true if the distance between specific MI and
710 /// specific ConstPool entry instruction can fit in MI's displacement field.
711 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
713 unsigned MaxDisp, bool DoDump) {
714 unsigned CPEOffset = GetOffsetOf(CPEMI);
715 assert(CPEOffset%4 == 0 && "Misaligned CPE");
718 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
719 << " max delta=" << MaxDisp
720 << " insn address=" << UserOffset
721 << " CPE address=" << CPEOffset
722 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
725 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
729 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
730 /// unconditionally branches to its only successor.
731 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
732 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
735 MachineBasicBlock *Succ = *MBB->succ_begin();
736 MachineBasicBlock *Pred = *MBB->pred_begin();
737 MachineInstr *PredMI = &Pred->back();
738 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
739 || PredMI->getOpcode() == ARM::t2B)
740 return PredMI->getOperand(0).getMBB() == Succ;
745 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
747 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
748 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
749 BBOffsets[i] += delta;
750 // If some existing blocks have padding, adjust the padding as needed, a
751 // bit tricky. delta can be negative so don't use % on that.
753 MachineBasicBlock *MBB = MBBI;
755 // Constant pool entries require padding.
756 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
757 unsigned oldOffset = BBOffsets[i] - delta;
758 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
762 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
763 // remove existing padding
768 // Thumb jump tables require padding. They should be at the end;
769 // following unconditional branches are removed by AnalyzeBranch.
770 MachineInstr *ThumbJTMI = NULL;
771 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
772 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
773 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
774 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
775 ThumbJTMI = prior(MBB->end());
777 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
778 unsigned oldMIOffset = newMIOffset - delta;
779 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
780 // remove existing padding
783 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
797 /// DecrementOldEntry - find the constant pool entry with index CPI
798 /// and instruction CPEMI, and decrement its refcount. If the refcount
799 /// becomes 0 remove the entry and instruction. Returns true if we removed
800 /// the entry, false if we didn't.
802 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
803 // Find the old entry. Eliminate it if it is no longer used.
804 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
805 assert(CPE && "Unexpected!");
806 if (--CPE->RefCount == 0) {
807 RemoveDeadCPEMI(CPEMI);
815 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
816 /// if not, see if an in-range clone of the CPE is in range, and if so,
817 /// change the data structures so the user references the clone. Returns:
818 /// 0 = no existing entry found
819 /// 1 = entry found, and there were no code insertions or deletions
820 /// 2 = entry found, and there were code insertions or deletions
821 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
823 MachineInstr *UserMI = U.MI;
824 MachineInstr *CPEMI = U.CPEMI;
826 // Check to see if the CPE is already in-range.
827 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
828 DOUT << "In range\n";
832 // No. Look for previously created clones of the CPE that are in range.
833 unsigned CPI = CPEMI->getOperand(1).getIndex();
834 std::vector<CPEntry> &CPEs = CPEntries[CPI];
835 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
836 // We already tried this one
837 if (CPEs[i].CPEMI == CPEMI)
839 // Removing CPEs can leave empty entries, skip
840 if (CPEs[i].CPEMI == NULL)
842 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
843 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
844 // Point the CPUser node to the replacement
845 U.CPEMI = CPEs[i].CPEMI;
846 // Change the CPI in the instruction operand to refer to the clone.
847 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
848 if (UserMI->getOperand(j).isCPI()) {
849 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
852 // Adjust the refcount of the clone...
854 // ...and the original. If we didn't remove the old entry, none of the
855 // addresses changed, so we don't need another pass.
856 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
862 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
863 /// the specific unconditional branch instruction.
864 static inline unsigned getUnconditionalBrDisp(int Opc) {
867 return ((1<<10)-1)*2;
869 return ((1<<23)-1)*2;
874 return ((1<<23)-1)*4;
877 /// AcceptWater - Small amount of common code factored out of the following.
879 MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
880 std::vector<MachineBasicBlock*>::iterator IP) {
881 DOUT << "found water in range\n";
882 // Remove the original WaterList entry; we want subsequent
883 // insertions in this vicinity to go after the one we're
884 // about to insert. This considerably reduces the number
885 // of times we have to move the same CPE more than once.
887 // CPE goes before following block (NewMBB).
888 return next(MachineFunction::iterator(WaterBB));
891 /// LookForWater - look for an existing entry in the WaterList in which
892 /// we can place the CPE referenced from U so it's within range of U's MI.
893 /// Returns true if found, false if not. If it returns true, *NewMBB
894 /// is set to the WaterList entry.
895 /// For ARM, we prefer the water that's farthest away. For Thumb, prefer
896 /// water that will not introduce padding to water that will; within each
897 /// group, prefer the water that's farthest away.
899 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
900 MachineBasicBlock** NewMBB) {
901 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
902 MachineBasicBlock* WaterBBThatWouldPad = NULL;
903 if (!WaterList.empty()) {
904 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
905 B = WaterList.begin();; --IP) {
906 MachineBasicBlock* WaterBB = *IP;
907 if (WaterIsInRange(UserOffset, WaterBB, U)) {
909 (BBOffsets[WaterBB->getNumber()] +
910 BBSizes[WaterBB->getNumber()])%4 != 0) {
911 // This is valid Water, but would introduce padding. Remember
912 // it in case we don't find any Water that doesn't do this.
913 if (!WaterBBThatWouldPad) {
914 WaterBBThatWouldPad = WaterBB;
918 *NewMBB = AcceptWater(WaterBB, IP);
926 if (isThumb && WaterBBThatWouldPad) {
927 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
933 /// CreateNewWater - No existing WaterList entry will work for
934 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
935 /// block is used if in range, and the conditional branch munged so control
936 /// flow is correct. Otherwise the block is split to create a hole with an
937 /// unconditional branch around it. In either case *NewMBB is set to a
938 /// block following which the new island can be inserted (the WaterList
939 /// is not adjusted).
941 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
942 unsigned UserOffset, MachineBasicBlock** NewMBB) {
943 CPUser &U = CPUsers[CPUserIndex];
944 MachineInstr *UserMI = U.MI;
945 MachineInstr *CPEMI = U.CPEMI;
946 MachineBasicBlock *UserMBB = UserMI->getParent();
947 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
948 BBSizes[UserMBB->getNumber()];
949 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
951 // If the use is at the end of the block, or the end of the block
952 // is within range, make new water there. (The addition below is
953 // for the unconditional branch we will be adding: 4 bytes on ARM,
954 // 2 on Thumb. Possible Thumb alignment padding is allowed for
955 // inside OffsetIsInRange.
956 // If the block ends in an unconditional branch already, it is water,
957 // and is known to be out of range, so we'll always be adding a branch.)
958 if (&UserMBB->back() == UserMI ||
959 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
960 U.MaxDisp, !isThumb)) {
961 DOUT << "Split at end of block\n";
962 if (&UserMBB->back() == UserMI)
963 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
964 *NewMBB = next(MachineFunction::iterator(UserMBB));
965 // Add an unconditional branch from UserMBB to fallthrough block.
966 // Record it for branch lengthening; this new branch will not get out of
967 // range, but if the preceding conditional branch is out of range, the
968 // targets will be exchanged, and the altered branch may be out of
969 // range, so the machinery has to know about it.
970 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
971 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
972 TII->get(UncondBr)).addMBB(*NewMBB);
973 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
974 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
975 MaxDisp, false, UncondBr));
976 int delta = isThumb ? 2 : 4;
977 BBSizes[UserMBB->getNumber()] += delta;
978 AdjustBBOffsetsAfter(UserMBB, delta);
980 // What a big block. Find a place within the block to split it.
981 // This is a little tricky on Thumb since instructions are 2 bytes
982 // and constant pool entries are 4 bytes: if instruction I references
983 // island CPE, and instruction I+1 references CPE', it will
984 // not work well to put CPE as far forward as possible, since then
985 // CPE' cannot immediately follow it (that location is 2 bytes
986 // farther away from I+1 than CPE was from I) and we'd need to create
987 // a new island. So, we make a first guess, then walk through the
988 // instructions between the one currently being looked at and the
989 // possible insertion point, and make sure any other instructions
990 // that reference CPEs will be able to use the same island area;
991 // if not, we back up the insertion point.
993 // The 4 in the following is for the unconditional branch we'll be
994 // inserting (allows for long branch on Thumb). Alignment of the
995 // island is handled inside OffsetIsInRange.
996 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
997 // This could point off the end of the block if we've already got
998 // constant pool entries following this block; only the last one is
999 // in the water list. Back past any possible branches (allow for a
1000 // conditional and a maximally long unconditional).
1001 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1002 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1004 unsigned EndInsertOffset = BaseInsertOffset +
1005 CPEMI->getOperand(2).getImm();
1006 MachineBasicBlock::iterator MI = UserMI;
1008 unsigned CPUIndex = CPUserIndex+1;
1009 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1010 Offset < BaseInsertOffset;
1011 Offset += TII->GetInstSizeInBytes(MI),
1013 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1014 if (!OffsetIsInRange(Offset, EndInsertOffset,
1015 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1016 BaseInsertOffset -= (isThumb ? 2 : 4);
1017 EndInsertOffset -= (isThumb ? 2 : 4);
1019 // This is overly conservative, as we don't account for CPEMIs
1020 // being reused within the block, but it doesn't matter much.
1021 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1025 DOUT << "Split in middle of big block\n";
1026 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1030 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1031 /// is out-of-range. If so, pick up the constant pool value and move it some
1032 /// place in-range. Return true if we changed any addresses (thus must run
1033 /// another pass of branch lengthening), false otherwise.
1034 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1035 unsigned CPUserIndex) {
1036 CPUser &U = CPUsers[CPUserIndex];
1037 MachineInstr *UserMI = U.MI;
1038 MachineInstr *CPEMI = U.CPEMI;
1039 unsigned CPI = CPEMI->getOperand(1).getIndex();
1040 unsigned Size = CPEMI->getOperand(2).getImm();
1041 MachineBasicBlock *NewMBB;
1042 // Compute this only once, it's expensive. The 4 or 8 is the value the
1043 // hardware keeps in the PC (2 insns ahead of the reference).
1044 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1046 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1047 // second instruction.
1048 if (UserMI->getOpcode() == ARM::tLEApcrel)
1051 // See if the current entry is within range, or there is a clone of it
1053 int result = LookForExistingCPEntry(U, UserOffset);
1054 if (result==1) return false;
1055 else if (result==2) return true;
1057 // No existing clone of this CPE is within range.
1058 // We will be generating a new clone. Get a UID for it.
1059 unsigned ID = AFI->createConstPoolEntryUId();
1061 // Look for water where we can place this CPE. We look for the farthest one
1062 // away that will work. Forward references only for now (although later
1063 // we might find some that are backwards).
1065 if (!LookForWater(U, UserOffset, &NewMBB)) {
1067 DOUT << "No water found\n";
1068 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1071 // Okay, we know we can put an island before NewMBB now, do it!
1072 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1073 Fn.insert(NewMBB, NewIsland);
1075 // Update internal data structures to account for the newly inserted MBB.
1076 UpdateForInsertedWaterBlock(NewIsland);
1078 // Decrement the old entry, and remove it if refcount becomes 0.
1079 DecrementOldEntry(CPI, CPEMI);
1081 // Now that we have an island to add the CPE to, clone the original CPE and
1082 // add it to the island.
1083 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1084 TII->get(ARM::CONSTPOOL_ENTRY))
1085 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1086 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1089 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1090 // Compensate for .align 2 in thumb mode.
1091 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1093 // Increase the size of the island block to account for the new entry.
1094 BBSizes[NewIsland->getNumber()] += Size;
1095 AdjustBBOffsetsAfter(NewIsland, Size);
1097 // Finally, change the CPI in the instruction operand to be ID.
1098 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1099 if (UserMI->getOperand(i).isCPI()) {
1100 UserMI->getOperand(i).setIndex(ID);
1104 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
1109 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1110 /// sizes and offsets of impacted basic blocks.
1111 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1112 MachineBasicBlock *CPEBB = CPEMI->getParent();
1113 unsigned Size = CPEMI->getOperand(2).getImm();
1114 CPEMI->eraseFromParent();
1115 BBSizes[CPEBB->getNumber()] -= Size;
1116 // All succeeding offsets have the current size value added in, fix this.
1117 if (CPEBB->empty()) {
1118 // In thumb mode, the size of island may be padded by two to compensate for
1119 // the alignment requirement. Then it will now be 2 when the block is
1120 // empty, so fix this.
1121 // All succeeding offsets have the current size value added in, fix this.
1122 if (BBSizes[CPEBB->getNumber()] != 0) {
1123 Size += BBSizes[CPEBB->getNumber()];
1124 BBSizes[CPEBB->getNumber()] = 0;
1127 AdjustBBOffsetsAfter(CPEBB, -Size);
1128 // An island has only one predecessor BB and one successor BB. Check if
1129 // this BB's predecessor jumps directly to this BB's successor. This
1130 // shouldn't happen currently.
1131 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1132 // FIXME: remove the empty blocks after all the work is done?
1135 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1137 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1138 unsigned MadeChange = false;
1139 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1140 std::vector<CPEntry> &CPEs = CPEntries[i];
1141 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1142 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1143 RemoveDeadCPEMI(CPEs[j].CPEMI);
1144 CPEs[j].CPEMI = NULL;
1152 /// BBIsInRange - Returns true if the distance between specific MI and
1153 /// specific BB can fit in MI's displacement field.
1154 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1156 unsigned PCAdj = isThumb ? 4 : 8;
1157 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1158 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1160 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1161 << " from BB#" << MI->getParent()->getNumber()
1162 << " max delta=" << MaxDisp
1163 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1164 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1166 if (BrOffset <= DestOffset) {
1167 // Branch before the Dest.
1168 if (DestOffset-BrOffset <= MaxDisp)
1171 if (BrOffset-DestOffset <= MaxDisp)
1177 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1178 /// away to fit in its displacement field.
1179 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1180 MachineInstr *MI = Br.MI;
1181 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1183 // Check to see if the DestBB is already in-range.
1184 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1188 return FixUpUnconditionalBr(Fn, Br);
1189 return FixUpConditionalBr(Fn, Br);
1192 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1193 /// too far away to fit in its displacement field. If the LR register has been
1194 /// spilled in the epilogue, then we can use BL to implement a far jump.
1195 /// Otherwise, add an intermediate branch instruction to a branch.
1197 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1198 MachineInstr *MI = Br.MI;
1199 MachineBasicBlock *MBB = MI->getParent();
1200 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
1202 // Use BL to implement far jump.
1203 Br.MaxDisp = (1 << 21) * 2;
1204 MI->setDesc(TII->get(ARM::tBfar));
1205 BBSizes[MBB->getNumber()] += 2;
1206 AdjustBBOffsetsAfter(MBB, 2);
1210 DOUT << " Changed B to long jump " << *MI;
1215 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1216 /// far away to fit in its displacement field. It is converted to an inverse
1217 /// conditional branch + an unconditional branch to the destination.
1219 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1220 MachineInstr *MI = Br.MI;
1221 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1223 // Add an unconditional branch to the destination and invert the branch
1224 // condition to jump over it:
1230 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1231 CC = ARMCC::getOppositeCondition(CC);
1232 unsigned CCReg = MI->getOperand(2).getReg();
1234 // If the branch is at the end of its MBB and that has a fall-through block,
1235 // direct the updated conditional branch to the fall-through block. Otherwise,
1236 // split the MBB before the next instruction.
1237 MachineBasicBlock *MBB = MI->getParent();
1238 MachineInstr *BMI = &MBB->back();
1239 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1243 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1244 BMI->getOpcode() == Br.UncondBr) {
1245 // Last MI in the BB is an unconditional branch. Can we simply invert the
1246 // condition and swap destinations:
1252 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1253 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1254 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
1255 BMI->getOperand(0).setMBB(DestBB);
1256 MI->getOperand(0).setMBB(NewDest);
1257 MI->getOperand(1).setImm(CC);
1264 SplitBlockBeforeInstr(MI);
1265 // No need for the branch to the next block. We're adding an unconditional
1266 // branch to the destination.
1267 int delta = TII->GetInstSizeInBytes(&MBB->back());
1268 BBSizes[MBB->getNumber()] -= delta;
1269 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1270 AdjustBBOffsetsAfter(SplitBB, -delta);
1271 MBB->back().eraseFromParent();
1272 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1274 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1276 DOUT << " Insert B to BB#" << DestBB->getNumber()
1277 << " also invert condition and change dest. to BB#"
1278 << NextBB->getNumber() << "\n";
1280 // Insert a new conditional branch and a new unconditional branch.
1281 // Also update the ImmBranch as well as adding a new entry for the new branch.
1282 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1283 TII->get(MI->getOpcode()))
1284 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1285 Br.MI = &MBB->back();
1286 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1287 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1288 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1289 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1290 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1292 // Remove the old conditional branch. It may or may not still be in MBB.
1293 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1294 MI->eraseFromParent();
1296 // The net size change is an addition of one unconditional branch.
1297 int delta = TII->GetInstSizeInBytes(&MBB->back());
1298 AdjustBBOffsetsAfter(MBB, delta);
1302 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1303 /// LR / restores LR to pc.
1304 bool ARMConstantIslands::UndoLRSpillRestore() {
1305 bool MadeChange = false;
1306 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1307 MachineInstr *MI = PushPopMIs[i];
1308 if (MI->getOpcode() == ARM::tPOP_RET &&
1309 MI->getOperand(0).getReg() == ARM::PC &&
1310 MI->getNumExplicitOperands() == 1) {
1311 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1312 MI->eraseFromParent();