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/Support/ErrorHandling.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
33 STATISTIC(NumCPEs, "Number of constpool entries");
34 STATISTIC(NumSplit, "Number of uncond branches inserted");
35 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
36 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
39 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
40 /// requires constant pool entries to be scattered among the instructions
41 /// inside a function. To do this, it completely ignores the normal LLVM
42 /// constant pool; instead, it places constants wherever it feels like with
43 /// special instructions.
45 /// The terminology used in this pass includes:
46 /// Islands - Clumps of constants placed in the function.
47 /// Water - Potential places where an island could be formed.
48 /// CPE - A constant pool entry that has been placed somewhere, which
49 /// tracks a list of users.
50 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
51 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
52 /// by MBB Number. The two-byte pads required for Thumb alignment are
53 /// counted as part of the following block (i.e., the offset and size for
54 /// a padded block will both be ==2 mod 4).
55 std::vector<unsigned> BBSizes;
57 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
58 /// The two-byte pads required for Thumb alignment are counted as part of
59 /// the following block.
60 std::vector<unsigned> BBOffsets;
62 /// WaterList - A sorted list of basic blocks where islands could be placed
63 /// (i.e. blocks that don't fall through to the following block, due
64 /// to a return, unreachable, or unconditional branch).
65 std::vector<MachineBasicBlock*> WaterList;
67 /// CPUser - One user of a constant pool, keeping the machine instruction
68 /// pointer, the constant pool being referenced, and the max displacement
69 /// allowed from the instruction to the CP.
75 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp, bool neg)
76 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg) {}
79 /// CPUsers - Keep track of all of the machine instructions that use various
80 /// constant pools and their max displacement.
81 std::vector<CPUser> CPUsers;
83 /// CPEntry - One per constant pool entry, keeping the machine instruction
84 /// pointer, the constpool index, and the number of CPUser's which
85 /// reference this entry.
90 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
91 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
94 /// CPEntries - Keep track of all of the constant pool entry machine
95 /// instructions. For each original constpool index (i.e. those that
96 /// existed upon entry to this pass), it keeps a vector of entries.
97 /// Original elements are cloned as we go along; the clones are
98 /// put in the vector of the original element, but have distinct CPIs.
99 std::vector<std::vector<CPEntry> > CPEntries;
101 /// ImmBranch - One per immediate branch, keeping the machine instruction
102 /// pointer, conditional or unconditional, the max displacement,
103 /// and (if isCond is true) the corresponding unconditional branch
107 unsigned MaxDisp : 31;
110 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
111 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
114 /// ImmBranches - Keep track of all the immediate branch instructions.
116 std::vector<ImmBranch> ImmBranches;
118 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
120 SmallVector<MachineInstr*, 4> PushPopMIs;
122 /// HasFarJump - True if any far jump instruction has been emitted during
123 /// the branch fix up pass.
126 const TargetInstrInfo *TII;
127 ARMFunctionInfo *AFI;
133 ARMConstantIslands() : MachineFunctionPass(&ID) {}
135 virtual bool runOnMachineFunction(MachineFunction &Fn);
137 virtual const char *getPassName() const {
138 return "ARM constant island placement and branch shortening pass";
142 void DoInitialPlacement(MachineFunction &Fn,
143 std::vector<MachineInstr*> &CPEMIs);
144 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
145 void InitialFunctionScan(MachineFunction &Fn,
146 const std::vector<MachineInstr*> &CPEMIs);
147 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
148 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
149 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
150 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
151 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
152 bool LookForWater(CPUser&U, unsigned UserOffset,
153 MachineBasicBlock** NewMBB);
154 MachineBasicBlock* AcceptWater(MachineBasicBlock *WaterBB,
155 std::vector<MachineBasicBlock*>::iterator IP);
156 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
157 MachineBasicBlock** NewMBB);
158 bool HandleConstantPoolUser(MachineFunction &Fn, unsigned CPUserIndex);
159 void RemoveDeadCPEMI(MachineInstr *CPEMI);
160 bool RemoveUnusedCPEntries();
161 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
162 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
163 bool DoDump = false);
164 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
166 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
167 unsigned Disp, bool NegativeOK);
168 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
169 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
170 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
171 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
172 bool UndoLRSpillRestore();
174 unsigned GetOffsetOf(MachineInstr *MI) const;
176 void verify(MachineFunction &Fn);
178 char ARMConstantIslands::ID = 0;
181 /// verify - check BBOffsets, BBSizes, alignment of islands
182 void ARMConstantIslands::verify(MachineFunction &Fn) {
183 assert(BBOffsets.size() == BBSizes.size());
184 for (unsigned i = 1, e = BBOffsets.size(); i != e; ++i)
185 assert(BBOffsets[i-1]+BBSizes[i-1] == BBOffsets[i]);
187 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
189 MachineBasicBlock *MBB = MBBI;
191 MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
192 assert((BBOffsets[MBB->getNumber()]%4 == 0 &&
193 BBSizes[MBB->getNumber()]%4 == 0) ||
194 (BBOffsets[MBB->getNumber()]%4 != 0 &&
195 BBSizes[MBB->getNumber()]%4 != 0));
200 /// print block size and offset information - debugging
201 void ARMConstantIslands::dumpBBs() {
202 for (unsigned J = 0, E = BBOffsets.size(); J !=E; ++J) {
203 DOUT << "block " << J << " offset " << BBOffsets[J] <<
204 " size " << BBSizes[J] << "\n";
208 /// createARMConstantIslandPass - returns an instance of the constpool
210 FunctionPass *llvm::createARMConstantIslandPass() {
211 return new ARMConstantIslands();
214 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
215 MachineConstantPool &MCP = *Fn.getConstantPool();
217 TII = Fn.getTarget().getInstrInfo();
218 AFI = Fn.getInfo<ARMFunctionInfo>();
219 isThumb = AFI->isThumbFunction();
220 isThumb1Only = AFI->isThumb1OnlyFunction();
221 isThumb2 = AFI->isThumb2Function();
225 // Renumber all of the machine basic blocks in the function, guaranteeing that
226 // the numbers agree with the position of the block in the function.
229 /// Thumb1 functions containing constant pools get 2-byte alignment.
230 /// This is so we can keep exact track of where the alignment padding goes.
232 AFI->setAlign(isThumb1Only ? 1U : 2U);
234 // Perform the initial placement of the constant pool entries. To start with,
235 // we put them all at the end of the function.
236 std::vector<MachineInstr*> CPEMIs;
237 if (!MCP.isEmpty()) {
238 DoInitialPlacement(Fn, CPEMIs);
243 /// The next UID to take is the first unused one.
244 AFI->initConstPoolEntryUId(CPEMIs.size());
246 // Do the initial scan of the function, building up information about the
247 // sizes of each block, the location of all the water, and finding all of the
248 // constant pool users.
249 InitialFunctionScan(Fn, CPEMIs);
252 /// Remove dead constant pool entries.
253 RemoveUnusedCPEntries();
255 // Iteratively place constant pool entries and fix up branches until there
257 bool MadeChange = false;
260 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
261 Change |= HandleConstantPoolUser(Fn, i);
263 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
264 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
271 // After a while, this might be made debug-only, but it is not expensive.
274 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
275 // Undo the spill / restore of LR if possible.
276 if (!HasFarJump && AFI->isLRSpilledForFarJump() && isThumb)
277 MadeChange |= UndoLRSpillRestore();
290 /// DoInitialPlacement - Perform the initial placement of the constant pool
291 /// entries. To start with, we put them all at the end of the function.
292 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
293 std::vector<MachineInstr*> &CPEMIs) {
294 // Create the basic block to hold the CPE's.
295 MachineBasicBlock *BB = Fn.CreateMachineBasicBlock();
298 // Add all of the constants from the constant pool to the end block, use an
299 // identity mapping of CPI's to CPE's.
300 const std::vector<MachineConstantPoolEntry> &CPs =
301 Fn.getConstantPool()->getConstants();
303 const TargetData &TD = *Fn.getTarget().getTargetData();
304 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
305 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
306 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
307 // we would have to pad them out or something so that instructions stay
309 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
310 MachineInstr *CPEMI =
311 BuildMI(BB, DebugLoc::getUnknownLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
312 .addImm(i).addConstantPoolIndex(i).addImm(Size);
313 CPEMIs.push_back(CPEMI);
315 // Add a new CPEntry, but no corresponding CPUser yet.
316 std::vector<CPEntry> CPEs;
317 CPEs.push_back(CPEntry(CPEMI, i));
318 CPEntries.push_back(CPEs);
320 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
324 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
325 /// into the block immediately after it.
326 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
327 // Get the next machine basic block in the function.
328 MachineFunction::iterator MBBI = MBB;
329 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
332 MachineBasicBlock *NextBB = next(MBBI);
333 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
334 E = MBB->succ_end(); I != E; ++I)
341 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
342 /// look up the corresponding CPEntry.
343 ARMConstantIslands::CPEntry
344 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
345 const MachineInstr *CPEMI) {
346 std::vector<CPEntry> &CPEs = CPEntries[CPI];
347 // Number of entries per constpool index should be small, just do a
349 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
350 if (CPEs[i].CPEMI == CPEMI)
356 /// InitialFunctionScan - Do the initial scan of the function, building up
357 /// information about the sizes of each block, the location of all the water,
358 /// and finding all of the constant pool users.
359 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
360 const std::vector<MachineInstr*> &CPEMIs) {
362 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
364 MachineBasicBlock &MBB = *MBBI;
366 // If this block doesn't fall through into the next MBB, then this is
367 // 'water' that a constant pool island could be placed.
368 if (!BBHasFallthrough(&MBB))
369 WaterList.push_back(&MBB);
371 unsigned MBBSize = 0;
372 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
374 // Add instruction size to MBBSize.
375 MBBSize += TII->GetInstSizeInBytes(I);
377 int Opc = I->getOpcode();
378 if (I->getDesc().isBranch()) {
387 case ARM::t2BR_JTadd:
388 // A Thumb table jump may involve padding; for the offsets to
389 // be right, functions containing these must be 4-byte aligned.
391 if ((Offset+MBBSize)%4 != 0)
392 MBBSize += 2; // padding
393 continue; // Does not get an entry in ImmBranches
395 continue; // Ignore other JT branches
426 // Record this immediate branch.
427 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
428 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
431 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
432 PushPopMIs.push_back(I);
434 // Scan the instructions for constant pool operands.
435 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
436 if (I->getOperand(op).isCPI()) {
437 // We found one. The addressing mode tells us the max displacement
438 // from the PC that this instruction permits.
440 // Basic size info comes from the TSFlags field.
443 unsigned TSFlags = I->getDesc().TSFlags;
445 switch (TSFlags & ARMII::AddrModeMask) {
447 // Constant pool entries can reach anything.
448 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
450 if (I->getOpcode() == ARM::tLEApcrel) {
451 Bits = 8; // Taking the address of a CP entry.
454 llvm_unreachable("Unknown addressing mode for CP reference!");
455 case ARMII::AddrMode1: // AM1: 8 bits << 2 - FIXME: this is wrong?
457 Scale = 4; // Taking the address of a CP entry.
460 case ARMII::AddrMode2:
461 Bits = 12; // +-offset_12
464 case ARMII::AddrMode3:
465 Bits = 8; // +-offset_8
468 // addrmode4 has no immediate offset.
469 case ARMII::AddrMode5:
471 Scale = 4; // +-(offset_8*4)
474 // addrmode6 has no immediate offset.
475 case ARMII::AddrModeT1_1:
476 Bits = 5; // +offset_5
478 case ARMII::AddrModeT1_2:
480 Scale = 2; // +(offset_5*2)
482 case ARMII::AddrModeT1_4:
484 Scale = 4; // +(offset_5*4)
486 case ARMII::AddrModeT1_s:
488 Scale = 4; // +(offset_8*4)
490 case ARMII::AddrModeT2_pc:
491 Bits = 12; // +-offset_12
495 // Remember that this is a user of a CP entry.
496 unsigned CPI = I->getOperand(op).getIndex();
497 MachineInstr *CPEMI = CPEMIs[CPI];
498 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
499 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk));
501 // Increment corresponding CPEntry reference count.
502 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
503 assert(CPE && "Cannot find a corresponding CPEntry!");
506 // Instructions can only use one CP entry, don't bother scanning the
507 // rest of the operands.
512 // In thumb mode, if this block is a constpool island, we may need padding
513 // so it's aligned on 4 byte boundary.
516 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY &&
520 BBSizes.push_back(MBBSize);
521 BBOffsets.push_back(Offset);
526 /// GetOffsetOf - Return the current offset of the specified machine instruction
527 /// from the start of the function. This offset changes as stuff is moved
528 /// around inside the function.
529 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
530 MachineBasicBlock *MBB = MI->getParent();
532 // The offset is composed of two things: the sum of the sizes of all MBB's
533 // before this instruction's block, and the offset from the start of the block
535 unsigned Offset = BBOffsets[MBB->getNumber()];
537 // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
538 // alignment padding, and compensate if so.
540 MI->getOpcode() == ARM::CONSTPOOL_ENTRY &&
544 // Sum instructions before MI in MBB.
545 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
546 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
547 if (&*I == MI) return Offset;
548 Offset += TII->GetInstSizeInBytes(I);
552 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
554 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
555 const MachineBasicBlock *RHS) {
556 return LHS->getNumber() < RHS->getNumber();
559 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
560 /// machine function, it upsets all of the block numbers. Renumber the blocks
561 /// and update the arrays that parallel this numbering.
562 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
563 // Renumber the MBB's to keep them consequtive.
564 NewBB->getParent()->RenumberBlocks(NewBB);
566 // Insert a size into BBSizes to align it properly with the (newly
567 // renumbered) block numbers.
568 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
570 // Likewise for BBOffsets.
571 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
573 // Next, update WaterList. Specifically, we need to add NewMBB as having
574 // available water after it.
575 std::vector<MachineBasicBlock*>::iterator IP =
576 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
578 WaterList.insert(IP, NewBB);
582 /// Split the basic block containing MI into two blocks, which are joined by
583 /// an unconditional branch. Update datastructures and renumber blocks to
584 /// account for this change and returns the newly created block.
585 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
586 MachineBasicBlock *OrigBB = MI->getParent();
587 MachineFunction &MF = *OrigBB->getParent();
589 // Create a new MBB for the code after the OrigBB.
590 MachineBasicBlock *NewBB =
591 MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
592 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
593 MF.insert(MBBI, NewBB);
595 // Splice the instructions starting with MI over to NewBB.
596 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
598 // Add an unconditional branch from OrigBB to NewBB.
599 // Note the new unconditional branch is not being recorded.
600 // There doesn't seem to be meaningful DebugInfo available; this doesn't
601 // correspond to anything in the source.
602 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
603 BuildMI(OrigBB, DebugLoc::getUnknownLoc(), TII->get(Opc)).addMBB(NewBB);
606 // Update the CFG. All succs of OrigBB are now succs of NewBB.
607 while (!OrigBB->succ_empty()) {
608 MachineBasicBlock *Succ = *OrigBB->succ_begin();
609 OrigBB->removeSuccessor(Succ);
610 NewBB->addSuccessor(Succ);
612 // This pass should be run after register allocation, so there should be no
613 // PHI nodes to update.
614 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
615 && "PHI nodes should be eliminated by now!");
618 // OrigBB branches to NewBB.
619 OrigBB->addSuccessor(NewBB);
621 // Update internal data structures to account for the newly inserted MBB.
622 // This is almost the same as UpdateForInsertedWaterBlock, except that
623 // the Water goes after OrigBB, not NewBB.
624 MF.RenumberBlocks(NewBB);
626 // Insert a size into BBSizes to align it properly with the (newly
627 // renumbered) block numbers.
628 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
630 // Likewise for BBOffsets.
631 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
633 // Next, update WaterList. Specifically, we need to add OrigMBB as having
634 // available water after it (but not if it's already there, which happens
635 // when splitting before a conditional branch that is followed by an
636 // unconditional branch - in that case we want to insert NewBB).
637 std::vector<MachineBasicBlock*>::iterator IP =
638 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
640 MachineBasicBlock* WaterBB = *IP;
641 if (WaterBB == OrigBB)
642 WaterList.insert(next(IP), NewBB);
644 WaterList.insert(IP, OrigBB);
646 // Figure out how large the first NewMBB is. (It cannot
647 // contain a constpool_entry or tablejump.)
648 unsigned NewBBSize = 0;
649 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
651 NewBBSize += TII->GetInstSizeInBytes(I);
653 unsigned OrigBBI = OrigBB->getNumber();
654 unsigned NewBBI = NewBB->getNumber();
655 // Set the size of NewBB in BBSizes.
656 BBSizes[NewBBI] = NewBBSize;
658 // We removed instructions from UserMBB, subtract that off from its size.
659 // Add 2 or 4 to the block to count the unconditional branch we added to it.
660 unsigned delta = isThumb1Only ? 2 : 4;
661 BBSizes[OrigBBI] -= NewBBSize - delta;
663 // ...and adjust BBOffsets for NewBB accordingly.
664 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
666 // All BBOffsets following these blocks must be modified.
667 AdjustBBOffsetsAfter(NewBB, delta);
672 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
673 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
674 /// constant pool entry).
675 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
676 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
677 // On Thumb offsets==2 mod 4 are rounded down by the hardware for
678 // purposes of the displacement computation; compensate for that here.
679 // Effectively, the valid range of displacements is 2 bytes smaller for such
681 if (isThumb && UserOffset%4 !=0)
683 // CPEs will be rounded up to a multiple of 4.
684 if (isThumb && TrialOffset%4 != 0)
687 if (UserOffset <= TrialOffset) {
688 // User before the Trial.
689 if (TrialOffset-UserOffset <= MaxDisp)
691 } else if (NegativeOK) {
692 if (UserOffset-TrialOffset <= MaxDisp)
698 /// WaterIsInRange - Returns true if a CPE placed after the specified
699 /// Water (a basic block) will be in range for the specific MI.
701 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
702 MachineBasicBlock* Water, CPUser &U) {
703 unsigned MaxDisp = U.MaxDisp;
704 MachineFunction::iterator I = next(MachineFunction::iterator(Water));
705 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
706 BBSizes[Water->getNumber()];
708 // If the CPE is to be inserted before the instruction, that will raise
709 // the offset of the instruction. (Currently applies only to ARM, so
710 // no alignment compensation attempted here.)
711 if (CPEOffset < UserOffset)
712 UserOffset += U.CPEMI->getOperand(2).getImm();
714 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk);
717 /// CPEIsInRange - Returns true if the distance between specific MI and
718 /// specific ConstPool entry instruction can fit in MI's displacement field.
719 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
720 MachineInstr *CPEMI, unsigned MaxDisp,
721 bool NegOk, bool DoDump) {
722 unsigned CPEOffset = GetOffsetOf(CPEMI);
723 assert(CPEOffset%4 == 0 && "Misaligned CPE");
726 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
727 << " max delta=" << MaxDisp
728 << " insn address=" << UserOffset
729 << " CPE address=" << CPEOffset
730 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
733 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
737 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
738 /// unconditionally branches to its only successor.
739 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
740 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
743 MachineBasicBlock *Succ = *MBB->succ_begin();
744 MachineBasicBlock *Pred = *MBB->pred_begin();
745 MachineInstr *PredMI = &Pred->back();
746 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
747 || PredMI->getOpcode() == ARM::t2B)
748 return PredMI->getOperand(0).getMBB() == Succ;
753 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
755 MachineFunction::iterator MBBI = BB; MBBI = next(MBBI);
756 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++) {
757 BBOffsets[i] += delta;
758 // If some existing blocks have padding, adjust the padding as needed, a
759 // bit tricky. delta can be negative so don't use % on that.
761 MachineBasicBlock *MBB = MBBI;
763 // Constant pool entries require padding.
764 if (MBB->begin()->getOpcode() == ARM::CONSTPOOL_ENTRY) {
765 unsigned oldOffset = BBOffsets[i] - delta;
766 if (oldOffset%4==0 && BBOffsets[i]%4!=0) {
770 } else if (oldOffset%4!=0 && BBOffsets[i]%4==0) {
771 // remove existing padding
776 // Thumb jump tables require padding. They should be at the end;
777 // following unconditional branches are removed by AnalyzeBranch.
778 MachineInstr *ThumbJTMI = NULL;
779 if ((prior(MBB->end())->getOpcode() == ARM::tBR_JTr)
780 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTr)
781 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTm)
782 || (prior(MBB->end())->getOpcode() == ARM::t2BR_JTadd))
783 ThumbJTMI = prior(MBB->end());
785 unsigned newMIOffset = GetOffsetOf(ThumbJTMI);
786 unsigned oldMIOffset = newMIOffset - delta;
787 if (oldMIOffset%4 == 0 && newMIOffset%4 != 0) {
788 // remove existing padding
791 } else if (oldMIOffset%4 != 0 && newMIOffset%4 == 0) {
805 /// DecrementOldEntry - find the constant pool entry with index CPI
806 /// and instruction CPEMI, and decrement its refcount. If the refcount
807 /// becomes 0 remove the entry and instruction. Returns true if we removed
808 /// the entry, false if we didn't.
810 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
811 // Find the old entry. Eliminate it if it is no longer used.
812 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
813 assert(CPE && "Unexpected!");
814 if (--CPE->RefCount == 0) {
815 RemoveDeadCPEMI(CPEMI);
823 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
824 /// if not, see if an in-range clone of the CPE is in range, and if so,
825 /// change the data structures so the user references the clone. Returns:
826 /// 0 = no existing entry found
827 /// 1 = entry found, and there were no code insertions or deletions
828 /// 2 = entry found, and there were code insertions or deletions
829 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
831 MachineInstr *UserMI = U.MI;
832 MachineInstr *CPEMI = U.CPEMI;
834 // Check to see if the CPE is already in-range.
835 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
836 DOUT << "In range\n";
840 // No. Look for previously created clones of the CPE that are in range.
841 unsigned CPI = CPEMI->getOperand(1).getIndex();
842 std::vector<CPEntry> &CPEs = CPEntries[CPI];
843 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
844 // We already tried this one
845 if (CPEs[i].CPEMI == CPEMI)
847 // Removing CPEs can leave empty entries, skip
848 if (CPEs[i].CPEMI == NULL)
850 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk)) {
851 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
852 // Point the CPUser node to the replacement
853 U.CPEMI = CPEs[i].CPEMI;
854 // Change the CPI in the instruction operand to refer to the clone.
855 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
856 if (UserMI->getOperand(j).isCPI()) {
857 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
860 // Adjust the refcount of the clone...
862 // ...and the original. If we didn't remove the old entry, none of the
863 // addresses changed, so we don't need another pass.
864 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
870 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
871 /// the specific unconditional branch instruction.
872 static inline unsigned getUnconditionalBrDisp(int Opc) {
875 return ((1<<10)-1)*2;
877 return ((1<<23)-1)*2;
882 return ((1<<23)-1)*4;
885 /// AcceptWater - Small amount of common code factored out of the following.
887 MachineBasicBlock* ARMConstantIslands::AcceptWater(MachineBasicBlock *WaterBB,
888 std::vector<MachineBasicBlock*>::iterator IP) {
889 DOUT << "found water in range\n";
890 // Remove the original WaterList entry; we want subsequent
891 // insertions in this vicinity to go after the one we're
892 // about to insert. This considerably reduces the number
893 // of times we have to move the same CPE more than once.
895 // CPE goes before following block (NewMBB).
896 return next(MachineFunction::iterator(WaterBB));
899 /// LookForWater - look for an existing entry in the WaterList in which
900 /// we can place the CPE referenced from U so it's within range of U's MI.
901 /// Returns true if found, false if not. If it returns true, *NewMBB
902 /// is set to the WaterList entry.
903 /// For ARM, we prefer the water that's farthest away. For Thumb, prefer
904 /// water that will not introduce padding to water that will; within each
905 /// group, prefer the water that's farthest away.
907 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
908 MachineBasicBlock** NewMBB) {
909 std::vector<MachineBasicBlock*>::iterator IPThatWouldPad;
910 MachineBasicBlock* WaterBBThatWouldPad = NULL;
911 if (!WaterList.empty()) {
912 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
913 B = WaterList.begin();; --IP) {
914 MachineBasicBlock* WaterBB = *IP;
915 if (WaterIsInRange(UserOffset, WaterBB, U)) {
917 (BBOffsets[WaterBB->getNumber()] +
918 BBSizes[WaterBB->getNumber()])%4 != 0) {
919 // This is valid Water, but would introduce padding. Remember
920 // it in case we don't find any Water that doesn't do this.
921 if (!WaterBBThatWouldPad) {
922 WaterBBThatWouldPad = WaterBB;
926 *NewMBB = AcceptWater(WaterBB, IP);
934 if (isThumb && WaterBBThatWouldPad) {
935 *NewMBB = AcceptWater(WaterBBThatWouldPad, IPThatWouldPad);
941 /// CreateNewWater - No existing WaterList entry will work for
942 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
943 /// block is used if in range, and the conditional branch munged so control
944 /// flow is correct. Otherwise the block is split to create a hole with an
945 /// unconditional branch around it. In either case *NewMBB is set to a
946 /// block following which the new island can be inserted (the WaterList
947 /// is not adjusted).
949 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
950 unsigned UserOffset, MachineBasicBlock** NewMBB) {
951 CPUser &U = CPUsers[CPUserIndex];
952 MachineInstr *UserMI = U.MI;
953 MachineInstr *CPEMI = U.CPEMI;
954 MachineBasicBlock *UserMBB = UserMI->getParent();
955 unsigned OffsetOfNextBlock = BBOffsets[UserMBB->getNumber()] +
956 BBSizes[UserMBB->getNumber()];
957 assert(OffsetOfNextBlock== BBOffsets[UserMBB->getNumber()+1]);
959 // If the use is at the end of the block, or the end of the block
960 // is within range, make new water there. (The addition below is
961 // for the unconditional branch we will be adding: 4 bytes on ARM,
962 // 2 on Thumb. Possible Thumb alignment padding is allowed for
963 // inside OffsetIsInRange.
964 // If the block ends in an unconditional branch already, it is water,
965 // and is known to be out of range, so we'll always be adding a branch.)
966 if (&UserMBB->back() == UserMI ||
967 OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb ? 2: 4),
968 U.MaxDisp, !isThumb)) {
969 DOUT << "Split at end of block\n";
970 if (&UserMBB->back() == UserMI)
971 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
972 *NewMBB = next(MachineFunction::iterator(UserMBB));
973 // Add an unconditional branch from UserMBB to fallthrough block.
974 // Record it for branch lengthening; this new branch will not get out of
975 // range, but if the preceding conditional branch is out of range, the
976 // targets will be exchanged, and the altered branch may be out of
977 // range, so the machinery has to know about it.
978 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
979 BuildMI(UserMBB, DebugLoc::getUnknownLoc(),
980 TII->get(UncondBr)).addMBB(*NewMBB);
981 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
982 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
983 MaxDisp, false, UncondBr));
984 int delta = isThumb ? 2 : 4;
985 BBSizes[UserMBB->getNumber()] += delta;
986 AdjustBBOffsetsAfter(UserMBB, delta);
988 // What a big block. Find a place within the block to split it.
989 // This is a little tricky on Thumb since instructions are 2 bytes
990 // and constant pool entries are 4 bytes: if instruction I references
991 // island CPE, and instruction I+1 references CPE', it will
992 // not work well to put CPE as far forward as possible, since then
993 // CPE' cannot immediately follow it (that location is 2 bytes
994 // farther away from I+1 than CPE was from I) and we'd need to create
995 // a new island. So, we make a first guess, then walk through the
996 // instructions between the one currently being looked at and the
997 // possible insertion point, and make sure any other instructions
998 // that reference CPEs will be able to use the same island area;
999 // if not, we back up the insertion point.
1001 // The 4 in the following is for the unconditional branch we'll be
1002 // inserting (allows for long branch on Thumb). Alignment of the
1003 // island is handled inside OffsetIsInRange.
1004 unsigned BaseInsertOffset = UserOffset + U.MaxDisp -4;
1005 // This could point off the end of the block if we've already got
1006 // constant pool entries following this block; only the last one is
1007 // in the water list. Back past any possible branches (allow for a
1008 // conditional and a maximally long unconditional).
1009 if (BaseInsertOffset >= BBOffsets[UserMBB->getNumber()+1])
1010 BaseInsertOffset = BBOffsets[UserMBB->getNumber()+1] -
1012 unsigned EndInsertOffset = BaseInsertOffset +
1013 CPEMI->getOperand(2).getImm();
1014 MachineBasicBlock::iterator MI = UserMI;
1016 unsigned CPUIndex = CPUserIndex+1;
1017 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1018 Offset < BaseInsertOffset;
1019 Offset += TII->GetInstSizeInBytes(MI),
1021 if (CPUIndex < CPUsers.size() && CPUsers[CPUIndex].MI == MI) {
1022 if (!OffsetIsInRange(Offset, EndInsertOffset,
1023 CPUsers[CPUIndex].MaxDisp, !isThumb)) {
1024 BaseInsertOffset -= (isThumb ? 2 : 4);
1025 EndInsertOffset -= (isThumb ? 2 : 4);
1027 // This is overly conservative, as we don't account for CPEMIs
1028 // being reused within the block, but it doesn't matter much.
1029 EndInsertOffset += CPUsers[CPUIndex].CPEMI->getOperand(2).getImm();
1033 DOUT << "Split in middle of big block\n";
1034 *NewMBB = SplitBlockBeforeInstr(prior(MI));
1038 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1039 /// is out-of-range. If so, pick up the constant pool value and move it some
1040 /// place in-range. Return true if we changed any addresses (thus must run
1041 /// another pass of branch lengthening), false otherwise.
1042 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn,
1043 unsigned CPUserIndex) {
1044 CPUser &U = CPUsers[CPUserIndex];
1045 MachineInstr *UserMI = U.MI;
1046 MachineInstr *CPEMI = U.CPEMI;
1047 unsigned CPI = CPEMI->getOperand(1).getIndex();
1048 unsigned Size = CPEMI->getOperand(2).getImm();
1049 MachineBasicBlock *NewMBB;
1050 // Compute this only once, it's expensive. The 4 or 8 is the value the
1051 // hardware keeps in the PC (2 insns ahead of the reference).
1052 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
1054 // Special case: tLEApcrel are two instructions MI's. The actual user is the
1055 // second instruction.
1056 if (UserMI->getOpcode() == ARM::tLEApcrel)
1059 // See if the current entry is within range, or there is a clone of it
1061 int result = LookForExistingCPEntry(U, UserOffset);
1062 if (result==1) return false;
1063 else if (result==2) return true;
1065 // No existing clone of this CPE is within range.
1066 // We will be generating a new clone. Get a UID for it.
1067 unsigned ID = AFI->createConstPoolEntryUId();
1069 // Look for water where we can place this CPE. We look for the farthest one
1070 // away that will work. Forward references only for now (although later
1071 // we might find some that are backwards).
1073 if (!LookForWater(U, UserOffset, &NewMBB)) {
1075 DOUT << "No water found\n";
1076 CreateNewWater(CPUserIndex, UserOffset, &NewMBB);
1079 // Okay, we know we can put an island before NewMBB now, do it!
1080 MachineBasicBlock *NewIsland = Fn.CreateMachineBasicBlock();
1081 Fn.insert(NewMBB, NewIsland);
1083 // Update internal data structures to account for the newly inserted MBB.
1084 UpdateForInsertedWaterBlock(NewIsland);
1086 // Decrement the old entry, and remove it if refcount becomes 0.
1087 DecrementOldEntry(CPI, CPEMI);
1089 // Now that we have an island to add the CPE to, clone the original CPE and
1090 // add it to the island.
1091 U.CPEMI = BuildMI(NewIsland, DebugLoc::getUnknownLoc(),
1092 TII->get(ARM::CONSTPOOL_ENTRY))
1093 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1094 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1097 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
1098 // Compensate for .align 2 in thumb mode.
1099 if (isThumb && BBOffsets[NewIsland->getNumber()]%4 != 0)
1101 // Increase the size of the island block to account for the new entry.
1102 BBSizes[NewIsland->getNumber()] += Size;
1103 AdjustBBOffsetsAfter(NewIsland, Size);
1105 // Finally, change the CPI in the instruction operand to be ID.
1106 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1107 if (UserMI->getOperand(i).isCPI()) {
1108 UserMI->getOperand(i).setIndex(ID);
1112 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
1117 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1118 /// sizes and offsets of impacted basic blocks.
1119 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1120 MachineBasicBlock *CPEBB = CPEMI->getParent();
1121 unsigned Size = CPEMI->getOperand(2).getImm();
1122 CPEMI->eraseFromParent();
1123 BBSizes[CPEBB->getNumber()] -= Size;
1124 // All succeeding offsets have the current size value added in, fix this.
1125 if (CPEBB->empty()) {
1126 // In thumb mode, the size of island may be padded by two to compensate for
1127 // the alignment requirement. Then it will now be 2 when the block is
1128 // empty, so fix this.
1129 // All succeeding offsets have the current size value added in, fix this.
1130 if (BBSizes[CPEBB->getNumber()] != 0) {
1131 Size += BBSizes[CPEBB->getNumber()];
1132 BBSizes[CPEBB->getNumber()] = 0;
1135 AdjustBBOffsetsAfter(CPEBB, -Size);
1136 // An island has only one predecessor BB and one successor BB. Check if
1137 // this BB's predecessor jumps directly to this BB's successor. This
1138 // shouldn't happen currently.
1139 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1140 // FIXME: remove the empty blocks after all the work is done?
1143 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1145 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1146 unsigned MadeChange = false;
1147 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1148 std::vector<CPEntry> &CPEs = CPEntries[i];
1149 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1150 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1151 RemoveDeadCPEMI(CPEs[j].CPEMI);
1152 CPEs[j].CPEMI = NULL;
1160 /// BBIsInRange - Returns true if the distance between specific MI and
1161 /// specific BB can fit in MI's displacement field.
1162 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1164 unsigned PCAdj = isThumb ? 4 : 8;
1165 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1166 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
1168 DOUT << "Branch of destination BB#" << DestBB->getNumber()
1169 << " from BB#" << MI->getParent()->getNumber()
1170 << " max delta=" << MaxDisp
1171 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1172 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI;
1174 if (BrOffset <= DestOffset) {
1175 // Branch before the Dest.
1176 if (DestOffset-BrOffset <= MaxDisp)
1179 if (BrOffset-DestOffset <= MaxDisp)
1185 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1186 /// away to fit in its displacement field.
1187 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
1188 MachineInstr *MI = Br.MI;
1189 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1191 // Check to see if the DestBB is already in-range.
1192 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1196 return FixUpUnconditionalBr(Fn, Br);
1197 return FixUpConditionalBr(Fn, Br);
1200 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1201 /// too far away to fit in its displacement field. If the LR register has been
1202 /// spilled in the epilogue, then we can use BL to implement a far jump.
1203 /// Otherwise, add an intermediate branch instruction to a branch.
1205 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1206 MachineInstr *MI = Br.MI;
1207 MachineBasicBlock *MBB = MI->getParent();
1208 assert(isThumb && !isThumb2 && "Expected a Thumb-1 function!");
1210 // Use BL to implement far jump.
1211 Br.MaxDisp = (1 << 21) * 2;
1212 MI->setDesc(TII->get(ARM::tBfar));
1213 BBSizes[MBB->getNumber()] += 2;
1214 AdjustBBOffsetsAfter(MBB, 2);
1218 DOUT << " Changed B to long jump " << *MI;
1223 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1224 /// far away to fit in its displacement field. It is converted to an inverse
1225 /// conditional branch + an unconditional branch to the destination.
1227 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
1228 MachineInstr *MI = Br.MI;
1229 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1231 // Add an unconditional branch to the destination and invert the branch
1232 // condition to jump over it:
1238 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1239 CC = ARMCC::getOppositeCondition(CC);
1240 unsigned CCReg = MI->getOperand(2).getReg();
1242 // If the branch is at the end of its MBB and that has a fall-through block,
1243 // direct the updated conditional branch to the fall-through block. Otherwise,
1244 // split the MBB before the next instruction.
1245 MachineBasicBlock *MBB = MI->getParent();
1246 MachineInstr *BMI = &MBB->back();
1247 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1251 if (next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1252 BMI->getOpcode() == Br.UncondBr) {
1253 // Last MI in the BB is an unconditional branch. Can we simply invert the
1254 // condition and swap destinations:
1260 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1261 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1262 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
1263 BMI->getOperand(0).setMBB(DestBB);
1264 MI->getOperand(0).setMBB(NewDest);
1265 MI->getOperand(1).setImm(CC);
1272 SplitBlockBeforeInstr(MI);
1273 // No need for the branch to the next block. We're adding an unconditional
1274 // branch to the destination.
1275 int delta = TII->GetInstSizeInBytes(&MBB->back());
1276 BBSizes[MBB->getNumber()] -= delta;
1277 MachineBasicBlock* SplitBB = next(MachineFunction::iterator(MBB));
1278 AdjustBBOffsetsAfter(SplitBB, -delta);
1279 MBB->back().eraseFromParent();
1280 // BBOffsets[SplitBB] is wrong temporarily, fixed below
1282 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1284 DOUT << " Insert B to BB#" << DestBB->getNumber()
1285 << " also invert condition and change dest. to BB#"
1286 << NextBB->getNumber() << "\n";
1288 // Insert a new conditional branch and a new unconditional branch.
1289 // Also update the ImmBranch as well as adding a new entry for the new branch.
1290 BuildMI(MBB, DebugLoc::getUnknownLoc(),
1291 TII->get(MI->getOpcode()))
1292 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1293 Br.MI = &MBB->back();
1294 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1295 BuildMI(MBB, DebugLoc::getUnknownLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1296 BBSizes[MBB->getNumber()] += TII->GetInstSizeInBytes(&MBB->back());
1297 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1298 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1300 // Remove the old conditional branch. It may or may not still be in MBB.
1301 BBSizes[MI->getParent()->getNumber()] -= TII->GetInstSizeInBytes(MI);
1302 MI->eraseFromParent();
1304 // The net size change is an addition of one unconditional branch.
1305 int delta = TII->GetInstSizeInBytes(&MBB->back());
1306 AdjustBBOffsetsAfter(MBB, delta);
1310 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1311 /// LR / restores LR to pc.
1312 bool ARMConstantIslands::UndoLRSpillRestore() {
1313 bool MadeChange = false;
1314 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1315 MachineInstr *MI = PushPopMIs[i];
1316 if (MI->getOpcode() == ARM::tPOP_RET &&
1317 MI->getOperand(0).getReg() == ARM::PC &&
1318 MI->getNumExplicitOperands() == 1) {
1319 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET));
1320 MI->eraseFromParent();