1 //===- BranchFolding.cpp - Fold machine code branch instructions ----------===//
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 pass forwards branches to unconditional branches to make them branch
11 // directly to the target block. This pass often results in dead MBB's, which
14 // Note that this pass must be run after register allocation, it cannot handle
15 // SSA form. It also must handle virtual registers for targets that emit virtual
18 //===----------------------------------------------------------------------===//
20 #include "BranchFolding.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
30 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/TargetPassConfig.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/MC/MCRegisterInfo.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/BlockFrequency.h"
46 #include "llvm/Support/BranchProbability.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetInstrInfo.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
63 #define DEBUG_TYPE "branch-folder"
65 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
66 STATISTIC(NumBranchOpts, "Number of branches optimized");
67 STATISTIC(NumTailMerge , "Number of block tails merged");
68 STATISTIC(NumHoist , "Number of times common instructions are hoisted");
69 STATISTIC(NumTailCalls, "Number of tail calls optimized");
71 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
72 cl::init(cl::BOU_UNSET), cl::Hidden);
74 // Throttle for huge numbers of predecessors (compile speed problems)
75 static cl::opt<unsigned>
76 TailMergeThreshold("tail-merge-threshold",
77 cl::desc("Max number of predecessors to consider tail merging"),
78 cl::init(150), cl::Hidden);
80 // Heuristic for tail merging (and, inversely, tail duplication).
81 // TODO: This should be replaced with a target query.
82 static cl::opt<unsigned>
83 TailMergeSize("tail-merge-size",
84 cl::desc("Min number of instructions to consider tail merging"),
85 cl::init(3), cl::Hidden);
89 /// BranchFolderPass - Wrap branch folder in a machine function pass.
90 class BranchFolderPass : public MachineFunctionPass {
94 explicit BranchFolderPass(): MachineFunctionPass(ID) {}
96 bool runOnMachineFunction(MachineFunction &MF) override;
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 AU.addRequired<MachineBlockFrequencyInfo>();
100 AU.addRequired<MachineBranchProbabilityInfo>();
101 AU.addRequired<TargetPassConfig>();
102 MachineFunctionPass::getAnalysisUsage(AU);
106 } // end anonymous namespace
108 char BranchFolderPass::ID = 0;
109 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
111 INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE,
112 "Control Flow Optimizer", false, false)
114 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
115 if (skipFunction(*MF.getFunction()))
118 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
119 // TailMerge can create jump into if branches that make CFG irreducible for
120 // HW that requires structurized CFG.
121 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
122 PassConfig->getEnableTailMerge();
123 BranchFolder::MBFIWrapper MBBFreqInfo(
124 getAnalysis<MachineBlockFrequencyInfo>());
125 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
126 getAnalysis<MachineBranchProbabilityInfo>());
127 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
128 MF.getSubtarget().getRegisterInfo(),
129 getAnalysisIfAvailable<MachineModuleInfo>());
132 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
133 MBFIWrapper &FreqInfo,
134 const MachineBranchProbabilityInfo &ProbInfo,
135 unsigned MinTailLength)
136 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
137 MBBFreqInfo(FreqInfo), MBPI(ProbInfo) {
138 if (MinCommonTailLength == 0)
139 MinCommonTailLength = TailMergeSize;
140 switch (FlagEnableTailMerge) {
141 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
142 case cl::BOU_TRUE: EnableTailMerge = true; break;
143 case cl::BOU_FALSE: EnableTailMerge = false; break;
147 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
148 assert(MBB->pred_empty() && "MBB must be dead!");
149 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
151 MachineFunction *MF = MBB->getParent();
152 // drop all successors.
153 while (!MBB->succ_empty())
154 MBB->removeSuccessor(MBB->succ_end()-1);
156 // Avoid matching if this pointer gets reused.
157 TriedMerging.erase(MBB);
161 FuncletMembership.erase(MBB);
163 MLI->removeBlock(MBB);
166 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
167 const TargetInstrInfo *tii,
168 const TargetRegisterInfo *tri,
169 MachineModuleInfo *mmi,
170 MachineLoopInfo *mli, bool AfterPlacement) {
171 if (!tii) return false;
173 TriedMerging.clear();
175 MachineRegisterInfo &MRI = MF.getRegInfo();
176 AfterBlockPlacement = AfterPlacement;
183 UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
185 MRI.invalidateLiveness();
187 // Fix CFG. The later algorithms expect it to be right.
188 bool MadeChange = false;
189 for (MachineBasicBlock &MBB : MF) {
190 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
191 SmallVector<MachineOperand, 4> Cond;
192 if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true))
193 MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
196 // Recalculate funclet membership.
197 FuncletMembership = getFuncletMembership(MF);
199 bool MadeChangeThisIteration = true;
200 while (MadeChangeThisIteration) {
201 MadeChangeThisIteration = TailMergeBlocks(MF);
202 // No need to clean up if tail merging does not change anything after the
204 if (!AfterBlockPlacement || MadeChangeThisIteration)
205 MadeChangeThisIteration |= OptimizeBranches(MF);
206 if (EnableHoistCommonCode)
207 MadeChangeThisIteration |= HoistCommonCode(MF);
208 MadeChange |= MadeChangeThisIteration;
211 // See if any jump tables have become dead as the code generator
213 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
217 // Walk the function to find jump tables that are live.
218 BitVector JTIsLive(JTI->getJumpTables().size());
219 for (const MachineBasicBlock &BB : MF) {
220 for (const MachineInstr &I : BB)
221 for (const MachineOperand &Op : I.operands()) {
222 if (!Op.isJTI()) continue;
224 // Remember that this JT is live.
225 JTIsLive.set(Op.getIndex());
229 // Finally, remove dead jump tables. This happens when the
230 // indirect jump was unreachable (and thus deleted).
231 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
232 if (!JTIsLive.test(i)) {
233 JTI->RemoveJumpTable(i);
240 //===----------------------------------------------------------------------===//
241 // Tail Merging of Blocks
242 //===----------------------------------------------------------------------===//
244 /// HashMachineInstr - Compute a hash value for MI and its operands.
245 static unsigned HashMachineInstr(const MachineInstr &MI) {
246 unsigned Hash = MI.getOpcode();
247 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
248 const MachineOperand &Op = MI.getOperand(i);
250 // Merge in bits from the operand if easy. We can't use MachineOperand's
251 // hash_code here because it's not deterministic and we sort by hash value
253 unsigned OperandHash = 0;
254 switch (Op.getType()) {
255 case MachineOperand::MO_Register:
256 OperandHash = Op.getReg();
258 case MachineOperand::MO_Immediate:
259 OperandHash = Op.getImm();
261 case MachineOperand::MO_MachineBasicBlock:
262 OperandHash = Op.getMBB()->getNumber();
264 case MachineOperand::MO_FrameIndex:
265 case MachineOperand::MO_ConstantPoolIndex:
266 case MachineOperand::MO_JumpTableIndex:
267 OperandHash = Op.getIndex();
269 case MachineOperand::MO_GlobalAddress:
270 case MachineOperand::MO_ExternalSymbol:
271 // Global address / external symbol are too hard, don't bother, but do
272 // pull in the offset.
273 OperandHash = Op.getOffset();
279 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
284 /// HashEndOfMBB - Hash the last instruction in the MBB.
285 static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
286 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
290 return HashMachineInstr(*I);
293 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
294 /// of instructions they actually have in common together at their end. Return
295 /// iterators for the first shared instruction in each block.
296 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
297 MachineBasicBlock *MBB2,
298 MachineBasicBlock::iterator &I1,
299 MachineBasicBlock::iterator &I2) {
303 unsigned TailLen = 0;
304 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
306 // Skip debugging pseudos; necessary to avoid changing the code.
307 while (I1->isDebugValue()) {
308 if (I1==MBB1->begin()) {
309 while (I2->isDebugValue()) {
310 if (I2==MBB2->begin())
311 // I1==DBG at begin; I2==DBG at begin
316 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
321 // I1==first (untested) non-DBG preceding known match
322 while (I2->isDebugValue()) {
323 if (I2==MBB2->begin()) {
325 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
330 // I1, I2==first (untested) non-DBGs preceding known match
331 if (!I1->isIdenticalTo(*I2) ||
332 // FIXME: This check is dubious. It's used to get around a problem where
333 // people incorrectly expect inline asm directives to remain in the same
334 // relative order. This is untenable because normal compiler
335 // optimizations (like this one) may reorder and/or merge these
343 // Back past possible debugging pseudos at beginning of block. This matters
344 // when one block differs from the other only by whether debugging pseudos
345 // are present at the beginning. (This way, the various checks later for
346 // I1==MBB1->begin() work as expected.)
347 if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
349 while (I2->isDebugValue()) {
350 if (I2 == MBB2->begin())
356 if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
358 while (I1->isDebugValue()) {
359 if (I1 == MBB1->begin())
368 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
369 MachineBasicBlock *NewDest) {
370 TII->ReplaceTailWithBranchTo(OldInst, NewDest);
373 NewDest->clearLiveIns();
374 computeLiveIns(LiveRegs, *MRI, *NewDest);
380 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
381 MachineBasicBlock::iterator BBI1,
382 const BasicBlock *BB) {
383 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
386 MachineFunction &MF = *CurMBB.getParent();
388 // Create the fall-through block.
389 MachineFunction::iterator MBBI = CurMBB.getIterator();
390 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB);
391 CurMBB.getParent()->insert(++MBBI, NewMBB);
393 // Move all the successors of this block to the specified block.
394 NewMBB->transferSuccessors(&CurMBB);
396 // Add an edge from CurMBB to NewMBB for the fall-through.
397 CurMBB.addSuccessor(NewMBB);
399 // Splice the code over.
400 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
402 // NewMBB belongs to the same loop as CurMBB.
404 if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
405 ML->addBasicBlockToLoop(NewMBB, MLI->getBase());
407 // NewMBB inherits CurMBB's block frequency.
408 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
411 computeLiveIns(LiveRegs, *MRI, *NewMBB);
413 // Add the new block to the funclet.
414 const auto &FuncletI = FuncletMembership.find(&CurMBB);
415 if (FuncletI != FuncletMembership.end()) {
416 auto n = FuncletI->second;
417 FuncletMembership[NewMBB] = n;
423 /// EstimateRuntime - Make a rough estimate for how long it will take to run
424 /// the specified code.
425 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
426 MachineBasicBlock::iterator E) {
428 for (; I != E; ++I) {
429 if (I->isDebugValue())
433 else if (I->mayLoad() || I->mayStore())
441 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
442 // branches temporarily for tail merging). In the case where CurMBB ends
443 // with a conditional branch to the next block, optimize by reversing the
444 // test and conditionally branching to SuccMBB instead.
445 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
446 const TargetInstrInfo *TII) {
447 MachineFunction *MF = CurMBB->getParent();
448 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
449 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
450 SmallVector<MachineOperand, 4> Cond;
451 DebugLoc dl = CurMBB->findBranchDebugLoc();
452 if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
453 MachineBasicBlock *NextBB = &*I;
454 if (TBB == NextBB && !Cond.empty() && !FBB) {
455 if (!TII->reverseBranchCondition(Cond)) {
456 TII->removeBranch(*CurMBB);
457 TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
462 TII->insertBranch(*CurMBB, SuccBB, nullptr,
463 SmallVector<MachineOperand, 0>(), dl);
467 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
468 if (getHash() < o.getHash())
470 if (getHash() > o.getHash())
472 if (getBlock()->getNumber() < o.getBlock()->getNumber())
474 if (getBlock()->getNumber() > o.getBlock()->getNumber())
476 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
477 // an object with itself.
478 #ifndef _GLIBCXX_DEBUG
479 llvm_unreachable("Predecessor appears twice");
486 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
487 auto I = MergedBBFreq.find(MBB);
489 if (I != MergedBBFreq.end())
492 return MBFI.getBlockFreq(MBB);
495 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
497 MergedBBFreq[MBB] = F;
501 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
502 const MachineBasicBlock *MBB) const {
503 return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
507 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
508 const BlockFrequency Freq) const {
509 return MBFI.printBlockFreq(OS, Freq);
512 void BranchFolder::MBFIWrapper::view(const Twine &Name, bool isSimple) {
513 MBFI.view(Name, isSimple);
517 BranchFolder::MBFIWrapper::getEntryFreq() const {
518 return MBFI.getEntryFreq();
521 /// CountTerminators - Count the number of terminators in the given
522 /// block and set I to the position of the first non-terminator, if there
523 /// is one, or MBB->end() otherwise.
524 static unsigned CountTerminators(MachineBasicBlock *MBB,
525 MachineBasicBlock::iterator &I) {
527 unsigned NumTerms = 0;
529 if (I == MBB->begin()) {
534 if (!I->isTerminator()) break;
540 /// A no successor, non-return block probably ends in unreachable and is cold.
541 /// Also consider a block that ends in an indirect branch to be a return block,
542 /// since many targets use plain indirect branches to return.
543 static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
544 if (!MBB->succ_empty())
548 return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
551 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
552 /// and decide if it would be profitable to merge those tails. Return the
553 /// length of the common tail and iterators to the first common instruction
555 /// MBB1, MBB2 The blocks to check
556 /// MinCommonTailLength Minimum size of tail block to be merged.
557 /// CommonTailLen Out parameter to record the size of the shared tail between
559 /// I1, I2 Iterator references that will be changed to point to the first
560 /// instruction in the common tail shared by MBB1,MBB2
561 /// SuccBB A common successor of MBB1, MBB2 which are in a canonical form
562 /// relative to SuccBB
563 /// PredBB The layout predecessor of SuccBB, if any.
564 /// FuncletMembership map from block to funclet #.
565 /// AfterPlacement True if we are merging blocks after layout. Stricter
566 /// thresholds apply to prevent undoing tail-duplication.
568 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
569 unsigned MinCommonTailLength, unsigned &CommonTailLen,
570 MachineBasicBlock::iterator &I1,
571 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
572 MachineBasicBlock *PredBB,
573 DenseMap<const MachineBasicBlock *, int> &FuncletMembership,
574 bool AfterPlacement) {
575 // It is never profitable to tail-merge blocks from two different funclets.
576 if (!FuncletMembership.empty()) {
577 auto Funclet1 = FuncletMembership.find(MBB1);
578 assert(Funclet1 != FuncletMembership.end());
579 auto Funclet2 = FuncletMembership.find(MBB2);
580 assert(Funclet2 != FuncletMembership.end());
581 if (Funclet1->second != Funclet2->second)
585 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
586 if (CommonTailLen == 0)
588 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
589 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
592 // It's almost always profitable to merge any number of non-terminator
593 // instructions with the block that falls through into the common successor.
594 // This is true only for a single successor. For multiple successors, we are
595 // trading a conditional branch for an unconditional one.
596 // TODO: Re-visit successor size for non-layout tail merging.
597 if ((MBB1 == PredBB || MBB2 == PredBB) &&
598 (!AfterPlacement || MBB1->succ_size() == 1)) {
599 MachineBasicBlock::iterator I;
600 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
601 if (CommonTailLen > NumTerms)
605 // If these are identical non-return blocks with no successors, merge them.
606 // Such blocks are typically cold calls to noreturn functions like abort, and
607 // are unlikely to become a fallthrough target after machine block placement.
608 // Tail merging these blocks is unlikely to create additional unconditional
609 // branches, and will reduce the size of this cold code.
610 if (I1 == MBB1->begin() && I2 == MBB2->begin() &&
611 blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2))
614 // If one of the blocks can be completely merged and happens to be in
615 // a position where the other could fall through into it, merge any number
616 // of instructions, because it can be done without a branch.
617 // TODO: If the blocks are not adjacent, move one of them so that they are?
618 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
620 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
623 // If both blocks are identical and end in a branch, merge them unless they
624 // both have a fallthrough predecessor and successor.
625 // We can only do this after block placement because it depends on whether
626 // there are fallthroughs, and we don't know until after layout.
627 if (AfterPlacement && I1 == MBB1->begin() && I2 == MBB2->begin()) {
628 auto BothFallThrough = [](MachineBasicBlock *MBB) {
629 if (MBB->succ_size() != 0 && !MBB->canFallThrough())
631 MachineFunction::iterator I(MBB);
632 MachineFunction *MF = MBB->getParent();
633 return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough();
635 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
639 // If both blocks have an unconditional branch temporarily stripped out,
640 // count that as an additional common instruction for the following
641 // heuristics. This heuristic is only accurate for single-succ blocks, so to
642 // make sure that during layout merging and duplicating don't crash, we check
643 // for that when merging during layout.
644 unsigned EffectiveTailLen = CommonTailLen;
645 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
646 (MBB1->succ_size() == 1 || !AfterPlacement) &&
647 !MBB1->back().isBarrier() &&
648 !MBB2->back().isBarrier())
651 // Check if the common tail is long enough to be worthwhile.
652 if (EffectiveTailLen >= MinCommonTailLength)
655 // If we are optimizing for code size, 2 instructions in common is enough if
656 // we don't have to split a block. At worst we will be introducing 1 new
657 // branch instruction, which is likely to be smaller than the 2
658 // instructions that would be deleted in the merge.
659 MachineFunction *MF = MBB1->getParent();
660 return EffectiveTailLen >= 2 && MF->getFunction()->optForSize() &&
661 (I1 == MBB1->begin() || I2 == MBB2->begin());
664 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
665 unsigned MinCommonTailLength,
666 MachineBasicBlock *SuccBB,
667 MachineBasicBlock *PredBB) {
668 unsigned maxCommonTailLength = 0U;
670 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
671 MPIterator HighestMPIter = std::prev(MergePotentials.end());
672 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
673 B = MergePotentials.begin();
674 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
675 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
676 unsigned CommonTailLen;
677 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
679 CommonTailLen, TrialBBI1, TrialBBI2,
682 AfterBlockPlacement)) {
683 if (CommonTailLen > maxCommonTailLength) {
685 maxCommonTailLength = CommonTailLen;
686 HighestMPIter = CurMPIter;
687 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
689 if (HighestMPIter == CurMPIter &&
690 CommonTailLen == maxCommonTailLength)
691 SameTails.push_back(SameTailElt(I, TrialBBI2));
697 return maxCommonTailLength;
700 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
701 MachineBasicBlock *SuccBB,
702 MachineBasicBlock *PredBB) {
703 MPIterator CurMPIter, B;
704 for (CurMPIter = std::prev(MergePotentials.end()),
705 B = MergePotentials.begin();
706 CurMPIter->getHash() == CurHash; --CurMPIter) {
707 // Put the unconditional branch back, if we need one.
708 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
709 if (SuccBB && CurMBB != PredBB)
710 FixTail(CurMBB, SuccBB, TII);
714 if (CurMPIter->getHash() != CurHash)
716 MergePotentials.erase(CurMPIter, MergePotentials.end());
719 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
720 MachineBasicBlock *SuccBB,
721 unsigned maxCommonTailLength,
722 unsigned &commonTailIndex) {
724 unsigned TimeEstimate = ~0U;
725 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
726 // Use PredBB if possible; that doesn't require a new branch.
727 if (SameTails[i].getBlock() == PredBB) {
731 // Otherwise, make a (fairly bogus) choice based on estimate of
732 // how long it will take the various blocks to execute.
733 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
734 SameTails[i].getTailStartPos());
735 if (t <= TimeEstimate) {
741 MachineBasicBlock::iterator BBI =
742 SameTails[commonTailIndex].getTailStartPos();
743 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
745 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
746 << maxCommonTailLength);
748 // If the split block unconditionally falls-thru to SuccBB, it will be
749 // merged. In control flow terms it should then take SuccBB's name. e.g. If
750 // SuccBB is an inner loop, the common tail is still part of the inner loop.
751 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
752 SuccBB->getBasicBlock() : MBB->getBasicBlock();
753 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
755 DEBUG(dbgs() << "... failed!");
759 SameTails[commonTailIndex].setBlock(newMBB);
760 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
762 // If we split PredBB, newMBB is the new predecessor.
769 void BranchFolder::MergeCommonTailDebugLocs(unsigned commonTailIndex) {
770 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
772 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
773 for (unsigned int i = 0 ; i != SameTails.size() ; ++i) {
774 if (i != commonTailIndex)
775 NextCommonInsts[i] = SameTails[i].getTailStartPos();
777 assert(SameTails[i].getTailStartPos() == MBB->begin() &&
778 "MBB is not a common tail only block");
782 for (auto &MI : *MBB) {
783 if (MI.isDebugValue())
785 DebugLoc DL = MI.getDebugLoc();
786 for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
787 if (i == commonTailIndex)
790 auto &Pos = NextCommonInsts[i];
791 assert(Pos != SameTails[i].getBlock()->end() &&
792 "Reached BB end within common tail");
793 while (Pos->isDebugValue()) {
795 assert(Pos != SameTails[i].getBlock()->end() &&
796 "Reached BB end within common tail");
798 assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");
799 DL = DILocation::getMergedLocation(DL, Pos->getDebugLoc());
800 NextCommonInsts[i] = ++Pos;
807 mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
808 MachineBasicBlock &MBBCommon) {
809 MachineBasicBlock *MBB = MBBIStartPos->getParent();
810 // Note CommonTailLen does not necessarily matches the size of
811 // the common BB nor all its instructions because of debug
812 // instructions differences.
813 unsigned CommonTailLen = 0;
814 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
817 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
818 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
819 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
820 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
822 while (CommonTailLen--) {
823 assert(MBBI != MBBIE && "Reached BB end within common tail length!");
826 if (MBBI->isDebugValue()) {
831 while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
834 assert(MBBICommon != MBBIECommon &&
835 "Reached BB end within common tail length!");
836 assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
838 // Merge MMOs from memory operations in the common block.
839 if (MBBICommon->mayLoad() || MBBICommon->mayStore())
840 MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI));
841 // Drop undef flags if they aren't present in all merged instructions.
842 for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
843 MachineOperand &MO = MBBICommon->getOperand(I);
844 if (MO.isReg() && MO.isUndef()) {
845 const MachineOperand &OtherMO = MBBI->getOperand(I);
846 if (!OtherMO.isUndef())
847 MO.setIsUndef(false);
856 // See if any of the blocks in MergePotentials (which all have SuccBB as a
857 // successor, or all have no successor if it is null) can be tail-merged.
858 // If there is a successor, any blocks in MergePotentials that are not
859 // tail-merged and are not immediately before Succ must have an unconditional
860 // branch to Succ added (but the predecessor/successor lists need no
861 // adjustment). The lone predecessor of Succ that falls through into Succ,
862 // if any, is given in PredBB.
863 // MinCommonTailLength - Except for the special cases below, tail-merge if
864 // there are at least this many instructions in common.
865 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
866 MachineBasicBlock *PredBB,
867 unsigned MinCommonTailLength) {
868 bool MadeChange = false;
870 DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
871 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
872 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
873 << (i == e-1 ? "" : ", ");
876 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
878 dbgs() << " which has fall-through from BB#"
879 << PredBB->getNumber() << "\n";
881 dbgs() << "Looking for common tails of at least "
882 << MinCommonTailLength << " instruction"
883 << (MinCommonTailLength == 1 ? "" : "s") << '\n';
886 // Sort by hash value so that blocks with identical end sequences sort
888 array_pod_sort(MergePotentials.begin(), MergePotentials.end());
890 // Walk through equivalence sets looking for actual exact matches.
891 while (MergePotentials.size() > 1) {
892 unsigned CurHash = MergePotentials.back().getHash();
894 // Build SameTails, identifying the set of blocks with this hash code
895 // and with the maximum number of instructions in common.
896 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
900 // If we didn't find any pair that has at least MinCommonTailLength
901 // instructions in common, remove all blocks with this hash code and retry.
902 if (SameTails.empty()) {
903 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
907 // If one of the blocks is the entire common tail (and not the entry
908 // block, which we can't jump to), we can treat all blocks with this same
909 // tail at once. Use PredBB if that is one of the possibilities, as that
910 // will not introduce any extra branches.
911 MachineBasicBlock *EntryBB =
912 &MergePotentials.front().getBlock()->getParent()->front();
913 unsigned commonTailIndex = SameTails.size();
914 // If there are two blocks, check to see if one can be made to fall through
916 if (SameTails.size() == 2 &&
917 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
918 SameTails[1].tailIsWholeBlock())
920 else if (SameTails.size() == 2 &&
921 SameTails[1].getBlock()->isLayoutSuccessor(
922 SameTails[0].getBlock()) &&
923 SameTails[0].tailIsWholeBlock())
926 // Otherwise just pick one, favoring the fall-through predecessor if
928 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
929 MachineBasicBlock *MBB = SameTails[i].getBlock();
930 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
936 if (SameTails[i].tailIsWholeBlock())
941 if (commonTailIndex == SameTails.size() ||
942 (SameTails[commonTailIndex].getBlock() == PredBB &&
943 !SameTails[commonTailIndex].tailIsWholeBlock())) {
944 // None of the blocks consist entirely of the common tail.
945 // Split a block so that one does.
946 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
947 maxCommonTailLength, commonTailIndex)) {
948 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
953 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
955 // Recompute common tail MBB's edge weights and block frequency.
956 setCommonTailEdgeWeights(*MBB);
958 // Merge debug locations across identical instructions for common tail.
959 MergeCommonTailDebugLocs(commonTailIndex);
961 // MBB is common tail. Adjust all other BB's to jump to this one.
962 // Traversal must be forwards so erases work.
963 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
965 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
966 if (commonTailIndex == i)
968 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
969 << (i == e-1 ? "" : ", "));
970 // Merge operations (MMOs, undef flags)
971 mergeOperations(SameTails[i].getTailStartPos(), *MBB);
972 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
973 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
974 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
975 MergePotentials.erase(SameTails[i].getMPIter());
977 DEBUG(dbgs() << "\n");
978 // We leave commonTailIndex in the worklist in case there are other blocks
979 // that match it with a smaller number of instructions.
985 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
986 bool MadeChange = false;
987 if (!EnableTailMerge) return MadeChange;
989 // First find blocks with no successors.
990 // Block placement does not create new tail merging opportunities for these
992 if (!AfterBlockPlacement) {
993 MergePotentials.clear();
994 for (MachineBasicBlock &MBB : MF) {
995 if (MergePotentials.size() == TailMergeThreshold)
997 if (!TriedMerging.count(&MBB) && MBB.succ_empty())
998 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
1001 // If this is a large problem, avoid visiting the same basic blocks
1003 if (MergePotentials.size() == TailMergeThreshold)
1004 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1005 TriedMerging.insert(MergePotentials[i].getBlock());
1007 // See if we can do any tail merging on those.
1008 if (MergePotentials.size() >= 2)
1009 MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
1012 // Look at blocks (IBB) with multiple predecessors (PBB).
1013 // We change each predecessor to a canonical form, by
1014 // (1) temporarily removing any unconditional branch from the predecessor
1016 // (2) alter conditional branches so they branch to the other block
1017 // not IBB; this may require adding back an unconditional branch to IBB
1018 // later, where there wasn't one coming in. E.g.
1020 // fallthrough to QBB
1023 // with a conceptual B to IBB after that, which never actually exists.
1024 // With those changes, we see whether the predecessors' tails match,
1025 // and merge them if so. We change things out of canonical form and
1026 // back to the way they were later in the process. (OptimizeBranches
1027 // would undo some of this, but we can't use it, because we'd get into
1028 // a compile-time infinite loop repeatedly doing and undoing the same
1029 // transformations.)
1031 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1033 if (I->pred_size() < 2) continue;
1034 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
1035 MachineBasicBlock *IBB = &*I;
1036 MachineBasicBlock *PredBB = &*std::prev(I);
1037 MergePotentials.clear();
1040 // Bail if merging after placement and IBB is the loop header because
1041 // -- If merging predecessors that belong to the same loop as IBB, the
1042 // common tail of merged predecessors may become the loop top if block
1043 // placement is called again and the predecessors may branch to this common
1044 // tail and require more branches. This can be relaxed if
1045 // MachineBlockPlacement::findBestLoopTop is more flexible.
1046 // --If merging predecessors that do not belong to the same loop as IBB, the
1047 // loop info of IBB's loop and the other loops may be affected. Calling the
1048 // block placement again may make big change to the layout and eliminate the
1049 // reason to do tail merging here.
1050 if (AfterBlockPlacement && MLI) {
1051 ML = MLI->getLoopFor(IBB);
1052 if (ML && IBB == ML->getHeader())
1056 for (MachineBasicBlock *PBB : I->predecessors()) {
1057 if (MergePotentials.size() == TailMergeThreshold)
1060 if (TriedMerging.count(PBB))
1063 // Skip blocks that loop to themselves, can't tail merge these.
1067 // Visit each predecessor only once.
1068 if (!UniquePreds.insert(PBB).second)
1071 // Skip blocks which may jump to a landing pad. Can't tail merge these.
1072 if (PBB->hasEHPadSuccessor())
1075 // After block placement, only consider predecessors that belong to the
1076 // same loop as IBB. The reason is the same as above when skipping loop
1078 if (AfterBlockPlacement && MLI)
1079 if (ML != MLI->getLoopFor(PBB))
1082 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1083 SmallVector<MachineOperand, 4> Cond;
1084 if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1085 // Failing case: IBB is the target of a cbr, and we cannot reverse the
1087 SmallVector<MachineOperand, 4> NewCond(Cond);
1088 if (!Cond.empty() && TBB == IBB) {
1089 if (TII->reverseBranchCondition(NewCond))
1091 // This is the QBB case described above
1093 auto Next = ++PBB->getIterator();
1094 if (Next != MF.end())
1099 // Failing case: the only way IBB can be reached from PBB is via
1100 // exception handling. Happens for landing pads. Would be nice to have
1101 // a bit in the edge so we didn't have to do all this.
1102 if (IBB->isEHPad()) {
1103 MachineFunction::iterator IP = ++PBB->getIterator();
1104 MachineBasicBlock *PredNextBB = nullptr;
1108 if (IBB != PredNextBB) // fallthrough
1111 if (TBB != IBB && FBB != IBB) // cbr then ubr
1113 } else if (Cond.empty()) {
1114 if (TBB != IBB) // ubr
1117 if (TBB != IBB && IBB != PredNextBB) // cbr
1122 // Remove the unconditional branch at the end, if any.
1123 if (TBB && (Cond.empty() || FBB)) {
1124 DebugLoc dl = PBB->findBranchDebugLoc();
1125 TII->removeBranch(*PBB);
1127 // reinsert conditional branch only, for now
1128 TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1132 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
1136 // If this is a large problem, avoid visiting the same basic blocks multiple
1138 if (MergePotentials.size() == TailMergeThreshold)
1139 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1140 TriedMerging.insert(MergePotentials[i].getBlock());
1142 if (MergePotentials.size() >= 2)
1143 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1145 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1146 // result of removing blocks in TryTailMergeBlocks.
1147 PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
1148 if (MergePotentials.size() == 1 &&
1149 MergePotentials.begin()->getBlock() != PredBB)
1150 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1156 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1157 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1158 BlockFrequency AccumulatedMBBFreq;
1160 // Aggregate edge frequency of successor edge j:
1161 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1162 // where bb is a basic block that is in SameTails.
1163 for (const auto &Src : SameTails) {
1164 const MachineBasicBlock *SrcMBB = Src.getBlock();
1165 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1166 AccumulatedMBBFreq += BlockFreq;
1168 // It is not necessary to recompute edge weights if TailBB has less than two
1170 if (TailMBB.succ_size() <= 1)
1173 auto EdgeFreq = EdgeFreqLs.begin();
1175 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1176 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1177 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1180 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1182 if (TailMBB.succ_size() <= 1)
1186 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1188 auto EdgeFreq = EdgeFreqLs.begin();
1190 if (SumEdgeFreq > 0) {
1191 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1192 SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1193 auto Prob = BranchProbability::getBranchProbability(
1194 EdgeFreq->getFrequency(), SumEdgeFreq);
1195 TailMBB.setSuccProbability(SuccI, Prob);
1200 //===----------------------------------------------------------------------===//
1201 // Branch Optimization
1202 //===----------------------------------------------------------------------===//
1204 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1205 bool MadeChange = false;
1207 // Make sure blocks are numbered in order
1208 MF.RenumberBlocks();
1209 // Renumbering blocks alters funclet membership, recalculate it.
1210 FuncletMembership = getFuncletMembership(MF);
1212 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1214 MachineBasicBlock *MBB = &*I++;
1215 MadeChange |= OptimizeBlock(MBB);
1217 // If it is dead, remove it.
1218 if (MBB->pred_empty()) {
1219 RemoveDeadBlock(MBB);
1228 // Blocks should be considered empty if they contain only debug info;
1229 // else the debug info would affect codegen.
1230 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1231 return MBB->getFirstNonDebugInstr() == MBB->end();
1234 // Blocks with only debug info and branches should be considered the same
1235 // as blocks with only branches.
1236 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1237 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1238 assert(I != MBB->end() && "empty block!");
1239 return I->isBranch();
1242 /// IsBetterFallthrough - Return true if it would be clearly better to
1243 /// fall-through to MBB1 than to fall through into MBB2. This has to return
1244 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1245 /// result in infinite loops.
1246 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1247 MachineBasicBlock *MBB2) {
1248 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1249 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1250 // optimize branches that branch to either a return block or an assert block
1251 // into a fallthrough to the return.
1252 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1253 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1254 if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1257 // If there is a clear successor ordering we make sure that one block
1258 // will fall through to the next
1259 if (MBB1->isSuccessor(MBB2)) return true;
1260 if (MBB2->isSuccessor(MBB1)) return false;
1262 return MBB2I->isCall() && !MBB1I->isCall();
1265 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1266 /// instructions on the block.
1267 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1268 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1269 if (I != MBB.end() && I->isBranch())
1270 return I->getDebugLoc();
1274 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1275 bool MadeChange = false;
1276 MachineFunction &MF = *MBB->getParent();
1279 MachineFunction::iterator FallThrough = MBB->getIterator();
1282 // Make sure MBB and FallThrough belong to the same funclet.
1283 bool SameFunclet = true;
1284 if (!FuncletMembership.empty() && FallThrough != MF.end()) {
1285 auto MBBFunclet = FuncletMembership.find(MBB);
1286 assert(MBBFunclet != FuncletMembership.end());
1287 auto FallThroughFunclet = FuncletMembership.find(&*FallThrough);
1288 assert(FallThroughFunclet != FuncletMembership.end());
1289 SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1292 // If this block is empty, make everyone use its fall-through, not the block
1293 // explicitly. Landing pads should not do this since the landing-pad table
1294 // points to this block. Blocks with their addresses taken shouldn't be
1296 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1298 // Dead block? Leave for cleanup later.
1299 if (MBB->pred_empty()) return MadeChange;
1301 if (FallThrough == MF.end()) {
1302 // TODO: Simplify preds to not branch here if possible!
1303 } else if (FallThrough->isEHPad()) {
1304 // Don't rewrite to a landing pad fallthough. That could lead to the case
1305 // where a BB jumps to more than one landing pad.
1306 // TODO: Is it ever worth rewriting predecessors which don't already
1307 // jump to a landing pad, and so can safely jump to the fallthrough?
1308 } else if (MBB->isSuccessor(&*FallThrough)) {
1309 // Rewrite all predecessors of the old block to go to the fallthrough
1311 while (!MBB->pred_empty()) {
1312 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1313 Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
1315 // If MBB was the target of a jump table, update jump tables to go to the
1316 // fallthrough instead.
1317 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1318 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1324 // Check to see if we can simplify the terminator of the block before this
1326 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1328 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1329 SmallVector<MachineOperand, 4> PriorCond;
1330 bool PriorUnAnalyzable =
1331 TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1332 if (!PriorUnAnalyzable) {
1333 // If the CFG for the prior block has extra edges, remove them.
1334 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1335 !PriorCond.empty());
1337 // If the previous branch is conditional and both conditions go to the same
1338 // destination, remove the branch, replacing it with an unconditional one or
1340 if (PriorTBB && PriorTBB == PriorFBB) {
1341 DebugLoc dl = getBranchDebugLoc(PrevBB);
1342 TII->removeBranch(PrevBB);
1344 if (PriorTBB != MBB)
1345 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1348 goto ReoptimizeBlock;
1351 // If the previous block unconditionally falls through to this block and
1352 // this block has no other predecessors, move the contents of this block
1353 // into the prior block. This doesn't usually happen when SimplifyCFG
1354 // has been used, but it can happen if tail merging splits a fall-through
1355 // predecessor of a block.
1356 // This has to check PrevBB->succ_size() because EH edges are ignored by
1358 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1359 PrevBB.succ_size() == 1 &&
1360 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1361 DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1362 << "From MBB: " << *MBB);
1363 // Remove redundant DBG_VALUEs first.
1364 if (PrevBB.begin() != PrevBB.end()) {
1365 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1367 MachineBasicBlock::iterator MBBIter = MBB->begin();
1368 // Check if DBG_VALUE at the end of PrevBB is identical to the
1369 // DBG_VALUE at the beginning of MBB.
1370 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1371 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1372 if (!MBBIter->isIdenticalTo(*PrevBBIter))
1374 MachineInstr &DuplicateDbg = *MBBIter;
1375 ++MBBIter; -- PrevBBIter;
1376 DuplicateDbg.eraseFromParent();
1379 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1380 PrevBB.removeSuccessor(PrevBB.succ_begin());
1381 assert(PrevBB.succ_empty());
1382 PrevBB.transferSuccessors(MBB);
1387 // If the previous branch *only* branches to *this* block (conditional or
1388 // not) remove the branch.
1389 if (PriorTBB == MBB && !PriorFBB) {
1390 TII->removeBranch(PrevBB);
1393 goto ReoptimizeBlock;
1396 // If the prior block branches somewhere else on the condition and here if
1397 // the condition is false, remove the uncond second branch.
1398 if (PriorFBB == MBB) {
1399 DebugLoc dl = getBranchDebugLoc(PrevBB);
1400 TII->removeBranch(PrevBB);
1401 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1404 goto ReoptimizeBlock;
1407 // If the prior block branches here on true and somewhere else on false, and
1408 // if the branch condition is reversible, reverse the branch to create a
1410 if (PriorTBB == MBB) {
1411 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1412 if (!TII->reverseBranchCondition(NewPriorCond)) {
1413 DebugLoc dl = getBranchDebugLoc(PrevBB);
1414 TII->removeBranch(PrevBB);
1415 TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1418 goto ReoptimizeBlock;
1422 // If this block has no successors (e.g. it is a return block or ends with
1423 // a call to a no-return function like abort or __cxa_throw) and if the pred
1424 // falls through into this block, and if it would otherwise fall through
1425 // into the block after this, move this block to the end of the function.
1427 // We consider it more likely that execution will stay in the function (e.g.
1428 // due to loops) than it is to exit it. This asserts in loops etc, moving
1429 // the assert condition out of the loop body.
1430 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1431 MachineFunction::iterator(PriorTBB) == FallThrough &&
1432 !MBB->canFallThrough()) {
1433 bool DoTransform = true;
1435 // We have to be careful that the succs of PredBB aren't both no-successor
1436 // blocks. If neither have successors and if PredBB is the second from
1437 // last block in the function, we'd just keep swapping the two blocks for
1438 // last. Only do the swap if one is clearly better to fall through than
1440 if (FallThrough == --MF.end() &&
1441 !IsBetterFallthrough(PriorTBB, MBB))
1442 DoTransform = false;
1445 // Reverse the branch so we will fall through on the previous true cond.
1446 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1447 if (!TII->reverseBranchCondition(NewPriorCond)) {
1448 DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1449 << "To make fallthrough to: " << *PriorTBB << "\n");
1451 DebugLoc dl = getBranchDebugLoc(PrevBB);
1452 TII->removeBranch(PrevBB);
1453 TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1455 // Move this block to the end of the function.
1456 MBB->moveAfter(&MF.back());
1465 if (!IsEmptyBlock(MBB) && MBB->pred_size() == 1 &&
1466 MF.getFunction()->optForSize()) {
1467 // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch
1468 // direction, thereby defeating careful block placement and regressing
1469 // performance. Therefore, only consider this for optsize functions.
1470 MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
1471 if (TII->isUnconditionalTailCall(TailCall)) {
1472 MachineBasicBlock *Pred = *MBB->pred_begin();
1473 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1474 SmallVector<MachineOperand, 4> PredCond;
1475 bool PredAnalyzable =
1476 !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
1478 if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB) {
1479 // The predecessor has a conditional branch to this block which consists
1480 // of only a tail call. Try to fold the tail call into the conditional
1482 if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
1483 // TODO: It would be nice if analyzeBranch() could provide a pointer
1484 // to the branch insturction so replaceBranchWithTailCall() doesn't
1485 // have to search for it.
1486 TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
1488 Pred->removeSuccessor(MBB);
1493 // If the predecessor is falling through to this block, we could reverse
1494 // the branch condition and fold the tail call into that. However, after
1495 // that we might have to re-arrange the CFG to fall through to the other
1496 // block and there is a high risk of regressing code size rather than
1501 // Analyze the branch in the current block.
1502 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1503 SmallVector<MachineOperand, 4> CurCond;
1504 bool CurUnAnalyzable =
1505 TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1506 if (!CurUnAnalyzable) {
1507 // If the CFG for the prior block has extra edges, remove them.
1508 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1510 // If this is a two-way branch, and the FBB branches to this block, reverse
1511 // the condition so the single-basic-block loop is faster. Instead of:
1512 // Loop: xxx; jcc Out; jmp Loop
1514 // Loop: xxx; jncc Loop; jmp Out
1515 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1516 SmallVector<MachineOperand, 4> NewCond(CurCond);
1517 if (!TII->reverseBranchCondition(NewCond)) {
1518 DebugLoc dl = getBranchDebugLoc(*MBB);
1519 TII->removeBranch(*MBB);
1520 TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1523 goto ReoptimizeBlock;
1527 // If this branch is the only thing in its block, see if we can forward
1528 // other blocks across it.
1529 if (CurTBB && CurCond.empty() && !CurFBB &&
1530 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1531 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1532 DebugLoc dl = getBranchDebugLoc(*MBB);
1533 // This block may contain just an unconditional branch. Because there can
1534 // be 'non-branch terminators' in the block, try removing the branch and
1535 // then seeing if the block is empty.
1536 TII->removeBranch(*MBB);
1537 // If the only things remaining in the block are debug info, remove these
1538 // as well, so this will behave the same as an empty block in non-debug
1540 if (IsEmptyBlock(MBB)) {
1541 // Make the block empty, losing the debug info (we could probably
1542 // improve this in some cases.)
1543 MBB->erase(MBB->begin(), MBB->end());
1545 // If this block is just an unconditional branch to CurTBB, we can
1546 // usually completely eliminate the block. The only case we cannot
1547 // completely eliminate the block is when the block before this one
1548 // falls through into MBB and we can't understand the prior block's branch
1551 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1552 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1553 !PrevBB.isSuccessor(MBB)) {
1554 // If the prior block falls through into us, turn it into an
1555 // explicit branch to us to make updates simpler.
1556 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1557 PriorTBB != MBB && PriorFBB != MBB) {
1559 assert(PriorCond.empty() && !PriorFBB &&
1560 "Bad branch analysis");
1563 assert(!PriorFBB && "Machine CFG out of date!");
1566 DebugLoc pdl = getBranchDebugLoc(PrevBB);
1567 TII->removeBranch(PrevBB);
1568 TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1571 // Iterate through all the predecessors, revectoring each in-turn.
1573 bool DidChange = false;
1574 bool HasBranchToSelf = false;
1575 while(PI != MBB->pred_size()) {
1576 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1578 // If this block has an uncond branch to itself, leave it.
1580 HasBranchToSelf = true;
1583 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1584 // If this change resulted in PMBB ending in a conditional
1585 // branch where both conditions go to the same destination,
1586 // change this to an unconditional branch (and fix the CFG).
1587 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1588 SmallVector<MachineOperand, 4> NewCurCond;
1589 bool NewCurUnAnalyzable = TII->analyzeBranch(
1590 *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
1591 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1592 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1593 TII->removeBranch(*PMBB);
1595 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1598 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1603 // Change any jumptables to go to the new MBB.
1604 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1605 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1609 if (!HasBranchToSelf) return MadeChange;
1614 // Add the branch back if the block is more than just an uncond branch.
1615 TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1619 // If the prior block doesn't fall through into this block, and if this
1620 // block doesn't fall through into some other block, see if we can find a
1621 // place to move this block where a fall-through will happen.
1622 if (!PrevBB.canFallThrough()) {
1623 // Now we know that there was no fall-through into this block, check to
1624 // see if it has a fall-through into its successor.
1625 bool CurFallsThru = MBB->canFallThrough();
1627 if (!MBB->isEHPad()) {
1628 // Check all the predecessors of this block. If one of them has no fall
1629 // throughs, move this block right after it.
1630 for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1631 // Analyze the branch at the end of the pred.
1632 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1633 SmallVector<MachineOperand, 4> PredCond;
1634 if (PredBB != MBB && !PredBB->canFallThrough() &&
1635 !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
1636 (!CurFallsThru || !CurTBB || !CurFBB) &&
1637 (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1638 // If the current block doesn't fall through, just move it.
1639 // If the current block can fall through and does not end with a
1640 // conditional branch, we need to append an unconditional jump to
1641 // the (current) next block. To avoid a possible compile-time
1642 // infinite loop, move blocks only backward in this case.
1643 // Also, if there are already 2 branches here, we cannot add a third;
1644 // this means we have the case
1649 MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
1651 TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1653 MBB->moveAfter(PredBB);
1655 goto ReoptimizeBlock;
1660 if (!CurFallsThru) {
1661 // Check all successors to see if we can move this block before it.
1662 for (MachineBasicBlock *SuccBB : MBB->successors()) {
1663 // Analyze the branch at the end of the block before the succ.
1664 MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1666 // If this block doesn't already fall-through to that successor, and if
1667 // the succ doesn't already have a block that can fall through into it,
1668 // and if the successor isn't an EH destination, we can arrange for the
1669 // fallthrough to happen.
1670 if (SuccBB != MBB && &*SuccPrev != MBB &&
1671 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1672 !SuccBB->isEHPad()) {
1673 MBB->moveBefore(SuccBB);
1675 goto ReoptimizeBlock;
1679 // Okay, there is no really great place to put this block. If, however,
1680 // the block before this one would be a fall-through if this block were
1681 // removed, move this block to the end of the function. There is no real
1682 // advantage in "falling through" to an EH block, so we don't want to
1683 // perform this transformation for that case.
1685 // Also, Windows EH introduced the possibility of an arbitrary number of
1686 // successors to a given block. The analyzeBranch call does not consider
1687 // exception handling and so we can get in a state where a block
1688 // containing a call is followed by multiple EH blocks that would be
1689 // rotated infinitely at the end of the function if the transformation
1690 // below were performed for EH "FallThrough" blocks. Therefore, even if
1691 // that appears not to be happening anymore, we should assume that it is
1692 // possible and not remove the "!FallThrough()->isEHPad" condition below.
1693 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1694 SmallVector<MachineOperand, 4> PrevCond;
1695 if (FallThrough != MF.end() &&
1696 !FallThrough->isEHPad() &&
1697 !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1698 PrevBB.isSuccessor(&*FallThrough)) {
1699 MBB->moveAfter(&MF.back());
1709 //===----------------------------------------------------------------------===//
1710 // Hoist Common Code
1711 //===----------------------------------------------------------------------===//
1713 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1714 bool MadeChange = false;
1715 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1716 MachineBasicBlock *MBB = &*I++;
1717 MadeChange |= HoistCommonCodeInSuccs(MBB);
1723 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1724 /// its 'true' successor.
1725 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1726 MachineBasicBlock *TrueBB) {
1727 for (MachineBasicBlock *SuccBB : BB->successors())
1728 if (SuccBB != TrueBB)
1733 template <class Container>
1734 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1736 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1737 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1744 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1745 /// in successors to. The location is usually just before the terminator,
1746 /// however if the terminator is a conditional branch and its previous
1747 /// instruction is the flag setting instruction, the previous instruction is
1748 /// the preferred location. This function also gathers uses and defs of the
1749 /// instructions from the insertion point to the end of the block. The data is
1750 /// used by HoistCommonCodeInSuccs to ensure safety.
1752 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1753 const TargetInstrInfo *TII,
1754 const TargetRegisterInfo *TRI,
1755 SmallSet<unsigned,4> &Uses,
1756 SmallSet<unsigned,4> &Defs) {
1757 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1758 if (!TII->isUnpredicatedTerminator(*Loc))
1761 for (const MachineOperand &MO : Loc->operands()) {
1764 unsigned Reg = MO.getReg();
1768 addRegAndItsAliases(Reg, TRI, Uses);
1771 // Don't try to hoist code in the rare case the terminator defines a
1772 // register that is later used.
1775 // If the terminator defines a register, make sure we don't hoist
1776 // the instruction whose def might be clobbered by the terminator.
1777 addRegAndItsAliases(Reg, TRI, Defs);
1783 if (Loc == MBB->begin())
1786 // The terminator is probably a conditional branch, try not to separate the
1787 // branch from condition setting instruction.
1788 MachineBasicBlock::iterator PI =
1789 skipDebugInstructionsBackward(std::prev(Loc), MBB->begin());
1792 for (const MachineOperand &MO : PI->operands()) {
1793 // If PI has a regmask operand, it is probably a call. Separate away.
1796 if (!MO.isReg() || MO.isUse())
1798 unsigned Reg = MO.getReg();
1801 if (Uses.count(Reg)) {
1807 // The condition setting instruction is not just before the conditional
1811 // Be conservative, don't insert instruction above something that may have
1812 // side-effects. And since it's potentially bad to separate flag setting
1813 // instruction from the conditional branch, just abort the optimization
1815 // Also avoid moving code above predicated instruction since it's hard to
1816 // reason about register liveness with predicated instruction.
1817 bool DontMoveAcrossStore = true;
1818 if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
1822 // Find out what registers are live. Note this routine is ignoring other live
1823 // registers which are only used by instructions in successor blocks.
1824 for (const MachineOperand &MO : PI->operands()) {
1827 unsigned Reg = MO.getReg();
1831 addRegAndItsAliases(Reg, TRI, Uses);
1833 if (Uses.erase(Reg)) {
1834 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1835 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1836 Uses.erase(*SubRegs); // Use sub-registers to be conservative
1839 addRegAndItsAliases(Reg, TRI, Defs);
1846 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1847 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1848 SmallVector<MachineOperand, 4> Cond;
1849 if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1852 if (!FBB) FBB = findFalseBlock(MBB, TBB);
1854 // Malformed bcc? True and false blocks are the same?
1857 // Restrict the optimization to cases where MBB is the only predecessor,
1858 // it is an obvious win.
1859 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1862 // Find a suitable position to hoist the common instructions to. Also figure
1863 // out which registers are used or defined by instructions from the insertion
1864 // point to the end of the block.
1865 SmallSet<unsigned, 4> Uses, Defs;
1866 MachineBasicBlock::iterator Loc =
1867 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1868 if (Loc == MBB->end())
1871 bool HasDups = false;
1872 SmallVector<unsigned, 4> LocalDefs, LocalKills;
1873 SmallSet<unsigned, 4> ActiveDefsSet, AllDefsSet;
1874 MachineBasicBlock::iterator TIB = TBB->begin();
1875 MachineBasicBlock::iterator FIB = FBB->begin();
1876 MachineBasicBlock::iterator TIE = TBB->end();
1877 MachineBasicBlock::iterator FIE = FBB->end();
1878 while (TIB != TIE && FIB != FIE) {
1879 // Skip dbg_value instructions. These do not count.
1880 TIB = skipDebugInstructionsForward(TIB, TIE);
1881 FIB = skipDebugInstructionsForward(FIB, FIE);
1882 if (TIB == TIE || FIB == FIE)
1885 if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
1888 if (TII->isPredicated(*TIB))
1889 // Hard to reason about register liveness with predicated instruction.
1893 for (MachineOperand &MO : TIB->operands()) {
1894 // Don't attempt to hoist instructions with register masks.
1895 if (MO.isRegMask()) {
1901 unsigned Reg = MO.getReg();
1905 if (Uses.count(Reg)) {
1906 // Avoid clobbering a register that's used by the instruction at
1907 // the point of insertion.
1912 if (Defs.count(Reg) && !MO.isDead()) {
1913 // Don't hoist the instruction if the def would be clobber by the
1914 // instruction at the point insertion. FIXME: This is overly
1915 // conservative. It should be possible to hoist the instructions
1916 // in BB2 in the following example:
1918 // r1, eflag = op1 r2, r3
1927 } else if (!ActiveDefsSet.count(Reg)) {
1928 if (Defs.count(Reg)) {
1929 // Use is defined by the instruction at the point of insertion.
1934 if (MO.isKill() && Uses.count(Reg))
1935 // Kills a register that's read by the instruction at the point of
1936 // insertion. Remove the kill marker.
1937 MO.setIsKill(false);
1943 bool DontMoveAcrossStore = true;
1944 if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
1947 // Remove kills from ActiveDefsSet, these registers had short live ranges.
1948 for (const MachineOperand &MO : TIB->operands()) {
1949 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1951 unsigned Reg = MO.getReg();
1954 if (!AllDefsSet.count(Reg)) {
1955 LocalKills.push_back(Reg);
1958 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1959 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1960 ActiveDefsSet.erase(*AI);
1962 ActiveDefsSet.erase(Reg);
1966 // Track local defs so we can update liveins.
1967 for (const MachineOperand &MO : TIB->operands()) {
1968 if (!MO.isReg() || !MO.isDef() || MO.isDead())
1970 unsigned Reg = MO.getReg();
1971 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg))
1973 LocalDefs.push_back(Reg);
1974 addRegAndItsAliases(Reg, TRI, ActiveDefsSet);
1975 addRegAndItsAliases(Reg, TRI, AllDefsSet);
1986 MBB->splice(Loc, TBB, TBB->begin(), TIB);
1987 FBB->erase(FBB->begin(), FIB);
1990 bool ChangedLiveIns = false;
1991 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1992 unsigned Def = LocalDefs[i];
1993 if (ActiveDefsSet.count(Def)) {
1994 TBB->addLiveIn(Def);
1995 FBB->addLiveIn(Def);
1996 ChangedLiveIns = true;
1999 for (unsigned K : LocalKills) {
2000 TBB->removeLiveIn(K);
2001 FBB->removeLiveIn(K);
2002 ChangedLiveIns = true;
2005 if (ChangedLiveIns) {
2006 TBB->sortUniqueLiveIns();
2007 FBB->sortUniqueLiveIns();