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/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/RegisterScavenging.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "branchfolding"
47 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
48 STATISTIC(NumBranchOpts, "Number of branches optimized");
49 STATISTIC(NumTailMerge , "Number of block tails merged");
50 STATISTIC(NumHoist , "Number of times common instructions are hoisted");
52 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
53 cl::init(cl::BOU_UNSET), cl::Hidden);
55 // Throttle for huge numbers of predecessors (compile speed problems)
56 static cl::opt<unsigned>
57 TailMergeThreshold("tail-merge-threshold",
58 cl::desc("Max number of predecessors to consider tail merging"),
59 cl::init(150), cl::Hidden);
61 // Heuristic for tail merging (and, inversely, tail duplication).
62 // TODO: This should be replaced with a target query.
63 static cl::opt<unsigned>
64 TailMergeSize("tail-merge-size",
65 cl::desc("Min number of instructions to consider tail merging"),
66 cl::init(3), cl::Hidden);
69 /// BranchFolderPass - Wrap branch folder in a machine function pass.
70 class BranchFolderPass : public MachineFunctionPass {
73 explicit BranchFolderPass(): MachineFunctionPass(ID) {}
75 bool runOnMachineFunction(MachineFunction &MF) override;
77 void getAnalysisUsage(AnalysisUsage &AU) const override {
78 AU.addRequired<MachineBlockFrequencyInfo>();
79 AU.addRequired<MachineBranchProbabilityInfo>();
80 AU.addRequired<TargetPassConfig>();
81 MachineFunctionPass::getAnalysisUsage(AU);
86 char BranchFolderPass::ID = 0;
87 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
89 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
90 "Control Flow Optimizer", false, false)
92 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
93 if (skipOptnoneFunction(*MF.getFunction()))
96 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
97 // TailMerge can create jump into if branches that make CFG irreducible for
98 // HW that requires structurized CFG.
99 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
100 PassConfig->getEnableTailMerge();
101 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true,
102 getAnalysis<MachineBlockFrequencyInfo>(),
103 getAnalysis<MachineBranchProbabilityInfo>());
104 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
105 MF.getSubtarget().getRegisterInfo(),
106 getAnalysisIfAvailable<MachineModuleInfo>());
109 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
110 const MachineBlockFrequencyInfo &FreqInfo,
111 const MachineBranchProbabilityInfo &ProbInfo)
112 : EnableHoistCommonCode(CommonHoist), MBBFreqInfo(FreqInfo),
114 switch (FlagEnableTailMerge) {
115 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
116 case cl::BOU_TRUE: EnableTailMerge = true; break;
117 case cl::BOU_FALSE: EnableTailMerge = false; break;
121 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
122 /// function, updating the CFG.
123 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
124 assert(MBB->pred_empty() && "MBB must be dead!");
125 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
127 MachineFunction *MF = MBB->getParent();
128 // drop all successors.
129 while (!MBB->succ_empty())
130 MBB->removeSuccessor(MBB->succ_end()-1);
132 // Avoid matching if this pointer gets reused.
133 TriedMerging.erase(MBB);
137 FuncletMembership.erase(MBB);
140 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
141 /// followed by terminators, and if the implicitly defined registers are not
142 /// used by the terminators, remove those implicit_def's. e.g.
144 /// r0 = implicit_def
145 /// r1 = implicit_def
147 /// This block can be optimized away later if the implicit instructions are
149 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
150 SmallSet<unsigned, 4> ImpDefRegs;
151 MachineBasicBlock::iterator I = MBB->begin();
152 while (I != MBB->end()) {
153 if (!I->isImplicitDef())
155 unsigned Reg = I->getOperand(0).getReg();
156 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
157 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
158 SubRegs.isValid(); ++SubRegs)
159 ImpDefRegs.insert(*SubRegs);
161 ImpDefRegs.insert(Reg);
165 if (ImpDefRegs.empty())
168 MachineBasicBlock::iterator FirstTerm = I;
169 while (I != MBB->end()) {
170 if (!TII->isUnpredicatedTerminator(I))
172 // See if it uses any of the implicitly defined registers.
173 for (const MachineOperand &MO : I->operands()) {
174 if (!MO.isReg() || !MO.isUse())
176 unsigned Reg = MO.getReg();
177 if (ImpDefRegs.count(Reg))
184 while (I != FirstTerm) {
185 MachineInstr *ImpDefMI = &*I;
187 MBB->erase(ImpDefMI);
193 /// OptimizeFunction - Perhaps branch folding, tail merging and other
194 /// CFG optimizations on the given function.
195 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
196 const TargetInstrInfo *tii,
197 const TargetRegisterInfo *tri,
198 MachineModuleInfo *mmi) {
199 if (!tii) return false;
201 TriedMerging.clear();
208 // Use a RegScavenger to help update liveness when required.
209 MachineRegisterInfo &MRI = MF.getRegInfo();
210 if (MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
211 RS = new RegScavenger();
213 MRI.invalidateLiveness();
215 // Fix CFG. The later algorithms expect it to be right.
216 bool MadeChange = false;
217 for (MachineBasicBlock &MBB : MF) {
218 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
219 SmallVector<MachineOperand, 4> Cond;
220 if (!TII->AnalyzeBranch(MBB, TBB, FBB, Cond, true))
221 MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
222 MadeChange |= OptimizeImpDefsBlock(&MBB);
225 // Recalculate funclet membership.
226 FuncletMembership = getFuncletMembership(MF);
228 bool MadeChangeThisIteration = true;
229 while (MadeChangeThisIteration) {
230 MadeChangeThisIteration = TailMergeBlocks(MF);
231 MadeChangeThisIteration |= OptimizeBranches(MF);
232 if (EnableHoistCommonCode)
233 MadeChangeThisIteration |= HoistCommonCode(MF);
234 MadeChange |= MadeChangeThisIteration;
237 // See if any jump tables have become dead as the code generator
239 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
245 // Walk the function to find jump tables that are live.
246 BitVector JTIsLive(JTI->getJumpTables().size());
247 for (const MachineBasicBlock &BB : MF) {
248 for (const MachineInstr &I : BB)
249 for (const MachineOperand &Op : I.operands()) {
250 if (!Op.isJTI()) continue;
252 // Remember that this JT is live.
253 JTIsLive.set(Op.getIndex());
257 // Finally, remove dead jump tables. This happens when the
258 // indirect jump was unreachable (and thus deleted).
259 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
260 if (!JTIsLive.test(i)) {
261 JTI->RemoveJumpTable(i);
269 //===----------------------------------------------------------------------===//
270 // Tail Merging of Blocks
271 //===----------------------------------------------------------------------===//
273 /// HashMachineInstr - Compute a hash value for MI and its operands.
274 static unsigned HashMachineInstr(const MachineInstr *MI) {
275 unsigned Hash = MI->getOpcode();
276 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
277 const MachineOperand &Op = MI->getOperand(i);
279 // Merge in bits from the operand if easy. We can't use MachineOperand's
280 // hash_code here because it's not deterministic and we sort by hash value
282 unsigned OperandHash = 0;
283 switch (Op.getType()) {
284 case MachineOperand::MO_Register:
285 OperandHash = Op.getReg();
287 case MachineOperand::MO_Immediate:
288 OperandHash = Op.getImm();
290 case MachineOperand::MO_MachineBasicBlock:
291 OperandHash = Op.getMBB()->getNumber();
293 case MachineOperand::MO_FrameIndex:
294 case MachineOperand::MO_ConstantPoolIndex:
295 case MachineOperand::MO_JumpTableIndex:
296 OperandHash = Op.getIndex();
298 case MachineOperand::MO_GlobalAddress:
299 case MachineOperand::MO_ExternalSymbol:
300 // Global address / external symbol are too hard, don't bother, but do
301 // pull in the offset.
302 OperandHash = Op.getOffset();
308 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
313 /// HashEndOfMBB - Hash the last instruction in the MBB.
314 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
315 MachineBasicBlock::const_iterator I = MBB->getLastNonDebugInstr();
319 return HashMachineInstr(I);
322 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
323 /// of instructions they actually have in common together at their end. Return
324 /// iterators for the first shared instruction in each block.
325 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
326 MachineBasicBlock *MBB2,
327 MachineBasicBlock::iterator &I1,
328 MachineBasicBlock::iterator &I2) {
332 unsigned TailLen = 0;
333 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
335 // Skip debugging pseudos; necessary to avoid changing the code.
336 while (I1->isDebugValue()) {
337 if (I1==MBB1->begin()) {
338 while (I2->isDebugValue()) {
339 if (I2==MBB2->begin())
340 // I1==DBG at begin; I2==DBG at begin
345 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
350 // I1==first (untested) non-DBG preceding known match
351 while (I2->isDebugValue()) {
352 if (I2==MBB2->begin()) {
354 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
359 // I1, I2==first (untested) non-DBGs preceding known match
360 if (!I1->isIdenticalTo(I2) ||
361 // FIXME: This check is dubious. It's used to get around a problem where
362 // people incorrectly expect inline asm directives to remain in the same
363 // relative order. This is untenable because normal compiler
364 // optimizations (like this one) may reorder and/or merge these
372 // Back past possible debugging pseudos at beginning of block. This matters
373 // when one block differs from the other only by whether debugging pseudos
374 // are present at the beginning. (This way, the various checks later for
375 // I1==MBB1->begin() work as expected.)
376 if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
378 while (I2->isDebugValue()) {
379 if (I2 == MBB2->begin())
385 if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
387 while (I1->isDebugValue()) {
388 if (I1 == MBB1->begin())
397 void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
398 MachineBasicBlock *NewMBB) {
400 RS->enterBasicBlock(CurMBB);
401 if (!CurMBB->empty())
402 RS->forward(std::prev(CurMBB->end()));
403 for (unsigned int i = 1, e = TRI->getNumRegs(); i != e; i++)
404 if (RS->isRegUsed(i, false))
405 NewMBB->addLiveIn(i);
409 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
410 /// after it, replacing it with an unconditional branch to NewDest.
411 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
412 MachineBasicBlock *NewDest) {
413 MachineBasicBlock *CurMBB = OldInst->getParent();
415 TII->ReplaceTailWithBranchTo(OldInst, NewDest);
417 // For targets that use the register scavenger, we must maintain LiveIns.
418 MaintainLiveIns(CurMBB, NewDest);
423 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
424 /// MBB so that the part before the iterator falls into the part starting at the
425 /// iterator. This returns the new MBB.
426 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
427 MachineBasicBlock::iterator BBI1,
428 const BasicBlock *BB) {
429 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
432 MachineFunction &MF = *CurMBB.getParent();
434 // Create the fall-through block.
435 MachineFunction::iterator MBBI = &CurMBB;
436 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
437 CurMBB.getParent()->insert(++MBBI, NewMBB);
439 // Move all the successors of this block to the specified block.
440 NewMBB->transferSuccessors(&CurMBB);
442 // Add an edge from CurMBB to NewMBB for the fall-through.
443 CurMBB.addSuccessor(NewMBB);
445 // Splice the code over.
446 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
448 // NewMBB inherits CurMBB's block frequency.
449 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
451 // For targets that use the register scavenger, we must maintain LiveIns.
452 MaintainLiveIns(&CurMBB, NewMBB);
454 // Add the new block to the funclet.
455 const auto &FuncletI = FuncletMembership.find(&CurMBB);
456 if (FuncletI != FuncletMembership.end())
457 FuncletMembership[NewMBB] = FuncletI->second;
462 /// EstimateRuntime - Make a rough estimate for how long it will take to run
463 /// the specified code.
464 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
465 MachineBasicBlock::iterator E) {
467 for (; I != E; ++I) {
468 if (I->isDebugValue())
472 else if (I->mayLoad() || I->mayStore())
480 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
481 // branches temporarily for tail merging). In the case where CurMBB ends
482 // with a conditional branch to the next block, optimize by reversing the
483 // test and conditionally branching to SuccMBB instead.
484 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
485 const TargetInstrInfo *TII) {
486 MachineFunction *MF = CurMBB->getParent();
487 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
488 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
489 SmallVector<MachineOperand, 4> Cond;
490 DebugLoc dl; // FIXME: this is nowhere
491 if (I != MF->end() &&
492 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
493 MachineBasicBlock *NextBB = I;
494 if (TBB == NextBB && !Cond.empty() && !FBB) {
495 if (!TII->ReverseBranchCondition(Cond)) {
496 TII->RemoveBranch(*CurMBB);
497 TII->InsertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
502 TII->InsertBranch(*CurMBB, SuccBB, nullptr,
503 SmallVector<MachineOperand, 0>(), dl);
507 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
508 if (getHash() < o.getHash())
510 if (getHash() > o.getHash())
512 if (getBlock()->getNumber() < o.getBlock()->getNumber())
514 if (getBlock()->getNumber() > o.getBlock()->getNumber())
516 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
517 // an object with itself.
518 #ifndef _GLIBCXX_DEBUG
519 llvm_unreachable("Predecessor appears twice");
526 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
527 auto I = MergedBBFreq.find(MBB);
529 if (I != MergedBBFreq.end())
532 return MBFI.getBlockFreq(MBB);
535 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
537 MergedBBFreq[MBB] = F;
540 /// CountTerminators - Count the number of terminators in the given
541 /// block and set I to the position of the first non-terminator, if there
542 /// is one, or MBB->end() otherwise.
543 static unsigned CountTerminators(MachineBasicBlock *MBB,
544 MachineBasicBlock::iterator &I) {
546 unsigned NumTerms = 0;
548 if (I == MBB->begin()) {
553 if (!I->isTerminator()) break;
559 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
560 /// and decide if it would be profitable to merge those tails. Return the
561 /// length of the common tail and iterators to the first common instruction
564 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
565 unsigned minCommonTailLength, unsigned &CommonTailLen,
566 MachineBasicBlock::iterator &I1,
567 MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
568 MachineBasicBlock *PredBB,
569 DenseMap<const MachineBasicBlock *, int> &FuncletMembership) {
570 // It is never profitable to tail-merge blocks from two different funclets.
571 if (!FuncletMembership.empty()) {
572 auto Funclet1 = FuncletMembership.find(MBB1);
573 assert(Funclet1 != FuncletMembership.end());
574 auto Funclet2 = FuncletMembership.find(MBB2);
575 assert(Funclet2 != FuncletMembership.end());
576 if (Funclet1->second != Funclet2->second)
580 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
581 if (CommonTailLen == 0)
583 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
584 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
587 // It's almost always profitable to merge any number of non-terminator
588 // instructions with the block that falls through into the common successor.
589 if (MBB1 == PredBB || MBB2 == PredBB) {
590 MachineBasicBlock::iterator I;
591 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
592 if (CommonTailLen > NumTerms)
596 // If one of the blocks can be completely merged and happens to be in
597 // a position where the other could fall through into it, merge any number
598 // of instructions, because it can be done without a branch.
599 // TODO: If the blocks are not adjacent, move one of them so that they are?
600 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
602 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
605 // If both blocks have an unconditional branch temporarily stripped out,
606 // count that as an additional common instruction for the following
608 unsigned EffectiveTailLen = CommonTailLen;
609 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
610 !MBB1->back().isBarrier() &&
611 !MBB2->back().isBarrier())
614 // Check if the common tail is long enough to be worthwhile.
615 if (EffectiveTailLen >= minCommonTailLength)
618 // If we are optimizing for code size, 2 instructions in common is enough if
619 // we don't have to split a block. At worst we will be introducing 1 new
620 // branch instruction, which is likely to be smaller than the 2
621 // instructions that would be deleted in the merge.
622 MachineFunction *MF = MBB1->getParent();
623 if (EffectiveTailLen >= 2 && MF->getFunction()->optForSize() &&
624 (I1 == MBB1->begin() || I2 == MBB2->begin()))
630 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
631 /// hash CurHash (guaranteed to match the last element). Build the vector
632 /// SameTails of all those that have the (same) largest number of instructions
633 /// in common of any pair of these blocks. SameTails entries contain an
634 /// iterator into MergePotentials (from which the MachineBasicBlock can be
635 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
636 /// instruction where the matching code sequence begins.
637 /// Order of elements in SameTails is the reverse of the order in which
638 /// those blocks appear in MergePotentials (where they are not necessarily
640 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
641 unsigned minCommonTailLength,
642 MachineBasicBlock *SuccBB,
643 MachineBasicBlock *PredBB) {
644 unsigned maxCommonTailLength = 0U;
646 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
647 MPIterator HighestMPIter = std::prev(MergePotentials.end());
648 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
649 B = MergePotentials.begin();
650 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
651 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
652 unsigned CommonTailLen;
653 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
655 CommonTailLen, TrialBBI1, TrialBBI2,
657 FuncletMembership)) {
658 if (CommonTailLen > maxCommonTailLength) {
660 maxCommonTailLength = CommonTailLen;
661 HighestMPIter = CurMPIter;
662 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
664 if (HighestMPIter == CurMPIter &&
665 CommonTailLen == maxCommonTailLength)
666 SameTails.push_back(SameTailElt(I, TrialBBI2));
672 return maxCommonTailLength;
675 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
676 /// MergePotentials, restoring branches at ends of blocks as appropriate.
677 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
678 MachineBasicBlock *SuccBB,
679 MachineBasicBlock *PredBB) {
680 MPIterator CurMPIter, B;
681 for (CurMPIter = std::prev(MergePotentials.end()),
682 B = MergePotentials.begin();
683 CurMPIter->getHash() == CurHash; --CurMPIter) {
684 // Put the unconditional branch back, if we need one.
685 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
686 if (SuccBB && CurMBB != PredBB)
687 FixTail(CurMBB, SuccBB, TII);
691 if (CurMPIter->getHash() != CurHash)
693 MergePotentials.erase(CurMPIter, MergePotentials.end());
696 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
697 /// only of the common tail. Create a block that does by splitting one.
698 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
699 MachineBasicBlock *SuccBB,
700 unsigned maxCommonTailLength,
701 unsigned &commonTailIndex) {
703 unsigned TimeEstimate = ~0U;
704 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
705 // Use PredBB if possible; that doesn't require a new branch.
706 if (SameTails[i].getBlock() == PredBB) {
710 // Otherwise, make a (fairly bogus) choice based on estimate of
711 // how long it will take the various blocks to execute.
712 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
713 SameTails[i].getTailStartPos());
714 if (t <= TimeEstimate) {
720 MachineBasicBlock::iterator BBI =
721 SameTails[commonTailIndex].getTailStartPos();
722 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
724 // If the common tail includes any debug info we will take it pretty
725 // randomly from one of the inputs. Might be better to remove it?
726 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
727 << maxCommonTailLength);
729 // If the split block unconditionally falls-thru to SuccBB, it will be
730 // merged. In control flow terms it should then take SuccBB's name. e.g. If
731 // SuccBB is an inner loop, the common tail is still part of the inner loop.
732 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
733 SuccBB->getBasicBlock() : MBB->getBasicBlock();
734 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
736 DEBUG(dbgs() << "... failed!");
740 SameTails[commonTailIndex].setBlock(newMBB);
741 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
743 // If we split PredBB, newMBB is the new predecessor.
750 static bool hasIdenticalMMOs(const MachineInstr *MI1, const MachineInstr *MI2) {
751 auto I1 = MI1->memoperands_begin(), E1 = MI1->memoperands_end();
752 auto I2 = MI2->memoperands_begin(), E2 = MI2->memoperands_end();
753 if ((E1 - I1) != (E2 - I2))
755 for (; I1 != E1; ++I1, ++I2) {
763 removeMMOsFromMemoryOperations(MachineBasicBlock::iterator MBBIStartPos,
764 MachineBasicBlock &MBBCommon) {
765 // Remove MMOs from memory operations in the common block
766 // when they do not match the ones from the block being tail-merged.
767 // This ensures later passes conservatively compute dependencies.
768 MachineBasicBlock *MBB = MBBIStartPos->getParent();
769 // Note CommonTailLen does not necessarily matches the size of
770 // the common BB nor all its instructions because of debug
771 // instructions differences.
772 unsigned CommonTailLen = 0;
773 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
776 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
777 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
778 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
779 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
781 while (CommonTailLen--) {
782 assert(MBBI != MBBIE && "Reached BB end within common tail length!");
785 if (MBBI->isDebugValue()) {
790 while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
793 assert(MBBICommon != MBBIECommon &&
794 "Reached BB end within common tail length!");
795 assert(MBBICommon->isIdenticalTo(&*MBBI) && "Expected matching MIIs!");
797 if (MBBICommon->mayLoad() || MBBICommon->mayStore())
798 if (!hasIdenticalMMOs(&*MBBI, &*MBBICommon))
799 MBBICommon->clearMemRefs();
806 // See if any of the blocks in MergePotentials (which all have a common single
807 // successor, or all have no successor) can be tail-merged. If there is a
808 // successor, any blocks in MergePotentials that are not tail-merged and
809 // are not immediately before Succ must have an unconditional branch to
810 // Succ added (but the predecessor/successor lists need no adjustment).
811 // The lone predecessor of Succ that falls through into Succ,
812 // if any, is given in PredBB.
814 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
815 MachineBasicBlock *PredBB) {
816 bool MadeChange = false;
818 // Except for the special cases below, tail-merge if there are at least
819 // this many instructions in common.
820 unsigned minCommonTailLength = TailMergeSize;
822 DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
823 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
824 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
825 << (i == e-1 ? "" : ", ");
828 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
830 dbgs() << " which has fall-through from BB#"
831 << PredBB->getNumber() << "\n";
833 dbgs() << "Looking for common tails of at least "
834 << minCommonTailLength << " instruction"
835 << (minCommonTailLength == 1 ? "" : "s") << '\n';
838 // Sort by hash value so that blocks with identical end sequences sort
840 array_pod_sort(MergePotentials.begin(), MergePotentials.end());
842 // Walk through equivalence sets looking for actual exact matches.
843 while (MergePotentials.size() > 1) {
844 unsigned CurHash = MergePotentials.back().getHash();
846 // Build SameTails, identifying the set of blocks with this hash code
847 // and with the maximum number of instructions in common.
848 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
852 // If we didn't find any pair that has at least minCommonTailLength
853 // instructions in common, remove all blocks with this hash code and retry.
854 if (SameTails.empty()) {
855 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
859 // If one of the blocks is the entire common tail (and not the entry
860 // block, which we can't jump to), we can treat all blocks with this same
861 // tail at once. Use PredBB if that is one of the possibilities, as that
862 // will not introduce any extra branches.
863 MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
864 getParent()->begin();
865 unsigned commonTailIndex = SameTails.size();
866 // If there are two blocks, check to see if one can be made to fall through
868 if (SameTails.size() == 2 &&
869 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
870 SameTails[1].tailIsWholeBlock())
872 else if (SameTails.size() == 2 &&
873 SameTails[1].getBlock()->isLayoutSuccessor(
874 SameTails[0].getBlock()) &&
875 SameTails[0].tailIsWholeBlock())
878 // Otherwise just pick one, favoring the fall-through predecessor if
880 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
881 MachineBasicBlock *MBB = SameTails[i].getBlock();
882 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
888 if (SameTails[i].tailIsWholeBlock())
893 if (commonTailIndex == SameTails.size() ||
894 (SameTails[commonTailIndex].getBlock() == PredBB &&
895 !SameTails[commonTailIndex].tailIsWholeBlock())) {
896 // None of the blocks consist entirely of the common tail.
897 // Split a block so that one does.
898 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
899 maxCommonTailLength, commonTailIndex)) {
900 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
905 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
907 // Recompute commont tail MBB's edge weights and block frequency.
908 setCommonTailEdgeWeights(*MBB);
910 // MBB is common tail. Adjust all other BB's to jump to this one.
911 // Traversal must be forwards so erases work.
912 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
914 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
915 if (commonTailIndex == i)
917 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
918 << (i == e-1 ? "" : ", "));
919 // Remove MMOs from memory operations as needed.
920 removeMMOsFromMemoryOperations(SameTails[i].getTailStartPos(), *MBB);
921 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
922 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
923 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
924 MergePotentials.erase(SameTails[i].getMPIter());
926 DEBUG(dbgs() << "\n");
927 // We leave commonTailIndex in the worklist in case there are other blocks
928 // that match it with a smaller number of instructions.
934 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
935 bool MadeChange = false;
936 if (!EnableTailMerge) return MadeChange;
938 // First find blocks with no successors.
939 MergePotentials.clear();
940 for (MachineBasicBlock &MBB : MF) {
941 if (MergePotentials.size() == TailMergeThreshold)
943 if (!TriedMerging.count(&MBB) && MBB.succ_empty())
944 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(&MBB), &MBB));
947 // If this is a large problem, avoid visiting the same basic blocks
949 if (MergePotentials.size() == TailMergeThreshold)
950 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
951 TriedMerging.insert(MergePotentials[i].getBlock());
953 // See if we can do any tail merging on those.
954 if (MergePotentials.size() >= 2)
955 MadeChange |= TryTailMergeBlocks(nullptr, nullptr);
957 // Look at blocks (IBB) with multiple predecessors (PBB).
958 // We change each predecessor to a canonical form, by
959 // (1) temporarily removing any unconditional branch from the predecessor
961 // (2) alter conditional branches so they branch to the other block
962 // not IBB; this may require adding back an unconditional branch to IBB
963 // later, where there wasn't one coming in. E.g.
965 // fallthrough to QBB
968 // with a conceptual B to IBB after that, which never actually exists.
969 // With those changes, we see whether the predecessors' tails match,
970 // and merge them if so. We change things out of canonical form and
971 // back to the way they were later in the process. (OptimizeBranches
972 // would undo some of this, but we can't use it, because we'd get into
973 // a compile-time infinite loop repeatedly doing and undoing the same
976 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
978 if (I->pred_size() < 2) continue;
979 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
980 MachineBasicBlock *IBB = I;
981 MachineBasicBlock *PredBB = std::prev(I);
982 MergePotentials.clear();
983 for (MachineBasicBlock *PBB : I->predecessors()) {
984 if (MergePotentials.size() == TailMergeThreshold)
987 if (TriedMerging.count(PBB))
990 // Skip blocks that loop to themselves, can't tail merge these.
994 // Visit each predecessor only once.
995 if (!UniquePreds.insert(PBB).second)
998 // Skip blocks which may jump to a landing pad. Can't tail merge these.
999 if (PBB->hasEHPadSuccessor())
1002 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1003 SmallVector<MachineOperand, 4> Cond;
1004 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1005 // Failing case: IBB is the target of a cbr, and we cannot reverse the
1007 SmallVector<MachineOperand, 4> NewCond(Cond);
1008 if (!Cond.empty() && TBB == IBB) {
1009 if (TII->ReverseBranchCondition(NewCond))
1011 // This is the QBB case described above
1013 FBB = std::next(MachineFunction::iterator(PBB));
1016 // Failing case: the only way IBB can be reached from PBB is via
1017 // exception handling. Happens for landing pads. Would be nice to have
1018 // a bit in the edge so we didn't have to do all this.
1019 if (IBB->isEHPad()) {
1020 MachineFunction::iterator IP = PBB; IP++;
1021 MachineBasicBlock *PredNextBB = nullptr;
1025 if (IBB != PredNextBB) // fallthrough
1028 if (TBB != IBB && FBB != IBB) // cbr then ubr
1030 } else if (Cond.empty()) {
1031 if (TBB != IBB) // ubr
1034 if (TBB != IBB && IBB != PredNextBB) // cbr
1039 // Remove the unconditional branch at the end, if any.
1040 if (TBB && (Cond.empty() || FBB)) {
1041 DebugLoc dl; // FIXME: this is nowhere
1042 TII->RemoveBranch(*PBB);
1044 // reinsert conditional branch only, for now
1045 TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1049 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), PBB));
1053 // If this is a large problem, avoid visiting the same basic blocks multiple
1055 if (MergePotentials.size() == TailMergeThreshold)
1056 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1057 TriedMerging.insert(MergePotentials[i].getBlock());
1059 if (MergePotentials.size() >= 2)
1060 MadeChange |= TryTailMergeBlocks(IBB, PredBB);
1062 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1063 // result of removing blocks in TryTailMergeBlocks.
1064 PredBB = std::prev(I); // this may have been changed in TryTailMergeBlocks
1065 if (MergePotentials.size() == 1 &&
1066 MergePotentials.begin()->getBlock() != PredBB)
1067 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1073 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1074 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1075 BlockFrequency AccumulatedMBBFreq;
1077 // Aggregate edge frequency of successor edge j:
1078 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1079 // where bb is a basic block that is in SameTails.
1080 for (const auto &Src : SameTails) {
1081 const MachineBasicBlock *SrcMBB = Src.getBlock();
1082 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1083 AccumulatedMBBFreq += BlockFreq;
1085 // It is not necessary to recompute edge weights if TailBB has less than two
1087 if (TailMBB.succ_size() <= 1)
1090 auto EdgeFreq = EdgeFreqLs.begin();
1092 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1093 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1094 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1097 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1099 if (TailMBB.succ_size() <= 1)
1102 auto MaxEdgeFreq = *std::max_element(EdgeFreqLs.begin(), EdgeFreqLs.end());
1103 uint64_t Scale = MaxEdgeFreq.getFrequency() / UINT32_MAX + 1;
1104 auto EdgeFreq = EdgeFreqLs.begin();
1106 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1107 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1108 TailMBB.setSuccWeight(SuccI, EdgeFreq->getFrequency() / Scale);
1111 //===----------------------------------------------------------------------===//
1112 // Branch Optimization
1113 //===----------------------------------------------------------------------===//
1115 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1116 bool MadeChange = false;
1118 // Make sure blocks are numbered in order
1119 MF.RenumberBlocks();
1120 // Renumbering blocks alters funclet membership, recalculate it.
1121 FuncletMembership = getFuncletMembership(MF);
1123 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1125 MachineBasicBlock *MBB = I++;
1126 MadeChange |= OptimizeBlock(MBB);
1128 // If it is dead, remove it.
1129 if (MBB->pred_empty()) {
1130 RemoveDeadBlock(MBB);
1139 // Blocks should be considered empty if they contain only debug info;
1140 // else the debug info would affect codegen.
1141 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1142 return MBB->getFirstNonDebugInstr() == MBB->end();
1145 // Blocks with only debug info and branches should be considered the same
1146 // as blocks with only branches.
1147 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1148 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1149 assert(I != MBB->end() && "empty block!");
1150 return I->isBranch();
1153 /// IsBetterFallthrough - Return true if it would be clearly better to
1154 /// fall-through to MBB1 than to fall through into MBB2. This has to return
1155 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1156 /// result in infinite loops.
1157 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1158 MachineBasicBlock *MBB2) {
1159 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1160 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1161 // optimize branches that branch to either a return block or an assert block
1162 // into a fallthrough to the return.
1163 MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1164 MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1165 if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1168 // If there is a clear successor ordering we make sure that one block
1169 // will fall through to the next
1170 if (MBB1->isSuccessor(MBB2)) return true;
1171 if (MBB2->isSuccessor(MBB1)) return false;
1173 return MBB2I->isCall() && !MBB1I->isCall();
1176 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1177 /// instructions on the block.
1178 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1179 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1180 if (I != MBB.end() && I->isBranch())
1181 return I->getDebugLoc();
1185 /// OptimizeBlock - Analyze and optimize control flow related to the specified
1186 /// block. This is never called on the entry block.
1187 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1188 bool MadeChange = false;
1189 MachineFunction &MF = *MBB->getParent();
1192 MachineFunction::iterator FallThrough = MBB;
1195 // Make sure MBB and FallThrough belong to the same funclet.
1196 bool SameFunclet = true;
1197 if (!FuncletMembership.empty() && FallThrough != MF.end()) {
1198 auto MBBFunclet = FuncletMembership.find(MBB);
1199 assert(MBBFunclet != FuncletMembership.end());
1200 auto FallThroughFunclet = FuncletMembership.find(FallThrough);
1201 assert(FallThroughFunclet != FuncletMembership.end());
1202 SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1205 // If this block is empty, make everyone use its fall-through, not the block
1206 // explicitly. Landing pads should not do this since the landing-pad table
1207 // points to this block. Blocks with their addresses taken shouldn't be
1209 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1211 // Dead block? Leave for cleanup later.
1212 if (MBB->pred_empty()) return MadeChange;
1214 if (FallThrough == MF.end()) {
1215 // TODO: Simplify preds to not branch here if possible!
1216 } else if (FallThrough->isEHPad()) {
1217 // Don't rewrite to a landing pad fallthough. That could lead to the case
1218 // where a BB jumps to more than one landing pad.
1219 // TODO: Is it ever worth rewriting predecessors which don't already
1220 // jump to a landing pad, and so can safely jump to the fallthrough?
1222 // Rewrite all predecessors of the old block to go to the fallthrough
1224 while (!MBB->pred_empty()) {
1225 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1226 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
1228 // If MBB was the target of a jump table, update jump tables to go to the
1229 // fallthrough instead.
1230 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1231 MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
1237 // Check to see if we can simplify the terminator of the block before this
1239 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1241 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1242 SmallVector<MachineOperand, 4> PriorCond;
1243 bool PriorUnAnalyzable =
1244 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1245 if (!PriorUnAnalyzable) {
1246 // If the CFG for the prior block has extra edges, remove them.
1247 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1248 !PriorCond.empty());
1250 // If the previous branch is conditional and both conditions go to the same
1251 // destination, remove the branch, replacing it with an unconditional one or
1253 if (PriorTBB && PriorTBB == PriorFBB) {
1254 DebugLoc dl = getBranchDebugLoc(PrevBB);
1255 TII->RemoveBranch(PrevBB);
1257 if (PriorTBB != MBB)
1258 TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1261 goto ReoptimizeBlock;
1264 // If the previous block unconditionally falls through to this block and
1265 // this block has no other predecessors, move the contents of this block
1266 // into the prior block. This doesn't usually happen when SimplifyCFG
1267 // has been used, but it can happen if tail merging splits a fall-through
1268 // predecessor of a block.
1269 // This has to check PrevBB->succ_size() because EH edges are ignored by
1271 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1272 PrevBB.succ_size() == 1 &&
1273 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1274 DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1275 << "From MBB: " << *MBB);
1276 // Remove redundant DBG_VALUEs first.
1277 if (PrevBB.begin() != PrevBB.end()) {
1278 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1280 MachineBasicBlock::iterator MBBIter = MBB->begin();
1281 // Check if DBG_VALUE at the end of PrevBB is identical to the
1282 // DBG_VALUE at the beginning of MBB.
1283 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1284 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1285 if (!MBBIter->isIdenticalTo(PrevBBIter))
1287 MachineInstr *DuplicateDbg = MBBIter;
1288 ++MBBIter; -- PrevBBIter;
1289 DuplicateDbg->eraseFromParent();
1292 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1293 PrevBB.removeSuccessor(PrevBB.succ_begin());
1294 assert(PrevBB.succ_empty());
1295 PrevBB.transferSuccessors(MBB);
1300 // If the previous branch *only* branches to *this* block (conditional or
1301 // not) remove the branch.
1302 if (PriorTBB == MBB && !PriorFBB) {
1303 TII->RemoveBranch(PrevBB);
1306 goto ReoptimizeBlock;
1309 // If the prior block branches somewhere else on the condition and here if
1310 // the condition is false, remove the uncond second branch.
1311 if (PriorFBB == MBB) {
1312 DebugLoc dl = getBranchDebugLoc(PrevBB);
1313 TII->RemoveBranch(PrevBB);
1314 TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1317 goto ReoptimizeBlock;
1320 // If the prior block branches here on true and somewhere else on false, and
1321 // if the branch condition is reversible, reverse the branch to create a
1323 if (PriorTBB == MBB) {
1324 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1325 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1326 DebugLoc dl = getBranchDebugLoc(PrevBB);
1327 TII->RemoveBranch(PrevBB);
1328 TII->InsertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1331 goto ReoptimizeBlock;
1335 // If this block has no successors (e.g. it is a return block or ends with
1336 // a call to a no-return function like abort or __cxa_throw) and if the pred
1337 // falls through into this block, and if it would otherwise fall through
1338 // into the block after this, move this block to the end of the function.
1340 // We consider it more likely that execution will stay in the function (e.g.
1341 // due to loops) than it is to exit it. This asserts in loops etc, moving
1342 // the assert condition out of the loop body.
1343 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1344 MachineFunction::iterator(PriorTBB) == FallThrough &&
1345 !MBB->canFallThrough()) {
1346 bool DoTransform = true;
1348 // We have to be careful that the succs of PredBB aren't both no-successor
1349 // blocks. If neither have successors and if PredBB is the second from
1350 // last block in the function, we'd just keep swapping the two blocks for
1351 // last. Only do the swap if one is clearly better to fall through than
1353 if (FallThrough == --MF.end() &&
1354 !IsBetterFallthrough(PriorTBB, MBB))
1355 DoTransform = false;
1358 // Reverse the branch so we will fall through on the previous true cond.
1359 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1360 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1361 DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1362 << "To make fallthrough to: " << *PriorTBB << "\n");
1364 DebugLoc dl = getBranchDebugLoc(PrevBB);
1365 TII->RemoveBranch(PrevBB);
1366 TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1368 // Move this block to the end of the function.
1369 MBB->moveAfter(--MF.end());
1378 // Analyze the branch in the current block.
1379 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1380 SmallVector<MachineOperand, 4> CurCond;
1381 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1382 if (!CurUnAnalyzable) {
1383 // If the CFG for the prior block has extra edges, remove them.
1384 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1386 // If this is a two-way branch, and the FBB branches to this block, reverse
1387 // the condition so the single-basic-block loop is faster. Instead of:
1388 // Loop: xxx; jcc Out; jmp Loop
1390 // Loop: xxx; jncc Loop; jmp Out
1391 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1392 SmallVector<MachineOperand, 4> NewCond(CurCond);
1393 if (!TII->ReverseBranchCondition(NewCond)) {
1394 DebugLoc dl = getBranchDebugLoc(*MBB);
1395 TII->RemoveBranch(*MBB);
1396 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1399 goto ReoptimizeBlock;
1403 // If this branch is the only thing in its block, see if we can forward
1404 // other blocks across it.
1405 if (CurTBB && CurCond.empty() && !CurFBB &&
1406 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1407 !MBB->hasAddressTaken()) {
1408 DebugLoc dl = getBranchDebugLoc(*MBB);
1409 // This block may contain just an unconditional branch. Because there can
1410 // be 'non-branch terminators' in the block, try removing the branch and
1411 // then seeing if the block is empty.
1412 TII->RemoveBranch(*MBB);
1413 // If the only things remaining in the block are debug info, remove these
1414 // as well, so this will behave the same as an empty block in non-debug
1416 if (IsEmptyBlock(MBB)) {
1417 // Make the block empty, losing the debug info (we could probably
1418 // improve this in some cases.)
1419 MBB->erase(MBB->begin(), MBB->end());
1421 // If this block is just an unconditional branch to CurTBB, we can
1422 // usually completely eliminate the block. The only case we cannot
1423 // completely eliminate the block is when the block before this one
1424 // falls through into MBB and we can't understand the prior block's branch
1427 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1428 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1429 !PrevBB.isSuccessor(MBB)) {
1430 // If the prior block falls through into us, turn it into an
1431 // explicit branch to us to make updates simpler.
1432 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1433 PriorTBB != MBB && PriorFBB != MBB) {
1435 assert(PriorCond.empty() && !PriorFBB &&
1436 "Bad branch analysis");
1439 assert(!PriorFBB && "Machine CFG out of date!");
1442 DebugLoc pdl = getBranchDebugLoc(PrevBB);
1443 TII->RemoveBranch(PrevBB);
1444 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1447 // Iterate through all the predecessors, revectoring each in-turn.
1449 bool DidChange = false;
1450 bool HasBranchToSelf = false;
1451 while(PI != MBB->pred_size()) {
1452 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1454 // If this block has an uncond branch to itself, leave it.
1456 HasBranchToSelf = true;
1459 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1460 // If this change resulted in PMBB ending in a conditional
1461 // branch where both conditions go to the same destination,
1462 // change this to an unconditional branch (and fix the CFG).
1463 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1464 SmallVector<MachineOperand, 4> NewCurCond;
1465 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1466 NewCurFBB, NewCurCond, true);
1467 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1468 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1469 TII->RemoveBranch(*PMBB);
1471 TII->InsertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1474 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1479 // Change any jumptables to go to the new MBB.
1480 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1481 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1485 if (!HasBranchToSelf) return MadeChange;
1490 // Add the branch back if the block is more than just an uncond branch.
1491 TII->InsertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1495 // If the prior block doesn't fall through into this block, and if this
1496 // block doesn't fall through into some other block, see if we can find a
1497 // place to move this block where a fall-through will happen.
1498 if (!PrevBB.canFallThrough()) {
1500 // Now we know that there was no fall-through into this block, check to
1501 // see if it has a fall-through into its successor.
1502 bool CurFallsThru = MBB->canFallThrough();
1504 if (!MBB->isEHPad()) {
1505 // Check all the predecessors of this block. If one of them has no fall
1506 // throughs, move this block right after it.
1507 for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1508 // Analyze the branch at the end of the pred.
1509 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1510 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1511 SmallVector<MachineOperand, 4> PredCond;
1512 if (PredBB != MBB && !PredBB->canFallThrough() &&
1513 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
1514 && (!CurFallsThru || !CurTBB || !CurFBB)
1515 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1516 // If the current block doesn't fall through, just move it.
1517 // If the current block can fall through and does not end with a
1518 // conditional branch, we need to append an unconditional jump to
1519 // the (current) next block. To avoid a possible compile-time
1520 // infinite loop, move blocks only backward in this case.
1521 // Also, if there are already 2 branches here, we cannot add a third;
1522 // this means we have the case
1527 MachineBasicBlock *NextBB =
1528 std::next(MachineFunction::iterator(MBB));
1530 TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1532 MBB->moveAfter(PredBB);
1534 goto ReoptimizeBlock;
1539 if (!CurFallsThru) {
1540 // Check all successors to see if we can move this block before it.
1541 for (MachineBasicBlock *SuccBB : MBB->successors()) {
1542 // Analyze the branch at the end of the block before the succ.
1543 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1545 // If this block doesn't already fall-through to that successor, and if
1546 // the succ doesn't already have a block that can fall through into it,
1547 // and if the successor isn't an EH destination, we can arrange for the
1548 // fallthrough to happen.
1549 if (SuccBB != MBB && &*SuccPrev != MBB &&
1550 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1551 !SuccBB->isEHPad()) {
1552 MBB->moveBefore(SuccBB);
1554 goto ReoptimizeBlock;
1558 // Okay, there is no really great place to put this block. If, however,
1559 // the block before this one would be a fall-through if this block were
1560 // removed, move this block to the end of the function.
1561 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1562 SmallVector<MachineOperand, 4> PrevCond;
1563 if (FallThrough != MF.end() &&
1564 !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1565 PrevBB.isSuccessor(FallThrough)) {
1566 MBB->moveAfter(--MF.end());
1576 //===----------------------------------------------------------------------===//
1577 // Hoist Common Code
1578 //===----------------------------------------------------------------------===//
1580 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1581 /// blocks to their common predecessor.
1582 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1583 bool MadeChange = false;
1584 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1585 MachineBasicBlock *MBB = I++;
1586 MadeChange |= HoistCommonCodeInSuccs(MBB);
1592 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1593 /// its 'true' successor.
1594 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1595 MachineBasicBlock *TrueBB) {
1596 for (MachineBasicBlock *SuccBB : BB->successors())
1597 if (SuccBB != TrueBB)
1602 template <class Container>
1603 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1605 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1606 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1613 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1614 /// in successors to. The location is usually just before the terminator,
1615 /// however if the terminator is a conditional branch and its previous
1616 /// instruction is the flag setting instruction, the previous instruction is
1617 /// the preferred location. This function also gathers uses and defs of the
1618 /// instructions from the insertion point to the end of the block. The data is
1619 /// used by HoistCommonCodeInSuccs to ensure safety.
1621 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1622 const TargetInstrInfo *TII,
1623 const TargetRegisterInfo *TRI,
1624 SmallSet<unsigned,4> &Uses,
1625 SmallSet<unsigned,4> &Defs) {
1626 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1627 if (!TII->isUnpredicatedTerminator(Loc))
1630 for (const MachineOperand &MO : Loc->operands()) {
1633 unsigned Reg = MO.getReg();
1637 addRegAndItsAliases(Reg, TRI, Uses);
1640 // Don't try to hoist code in the rare case the terminator defines a
1641 // register that is later used.
1644 // If the terminator defines a register, make sure we don't hoist
1645 // the instruction whose def might be clobbered by the terminator.
1646 addRegAndItsAliases(Reg, TRI, Defs);
1652 if (Loc == MBB->begin())
1655 // The terminator is probably a conditional branch, try not to separate the
1656 // branch from condition setting instruction.
1657 MachineBasicBlock::iterator PI = Loc;
1659 while (PI != MBB->begin() && PI->isDebugValue())
1663 for (const MachineOperand &MO : PI->operands()) {
1664 // If PI has a regmask operand, it is probably a call. Separate away.
1667 if (!MO.isReg() || MO.isUse())
1669 unsigned Reg = MO.getReg();
1672 if (Uses.count(Reg)) {
1678 // The condition setting instruction is not just before the conditional
1682 // Be conservative, don't insert instruction above something that may have
1683 // side-effects. And since it's potentially bad to separate flag setting
1684 // instruction from the conditional branch, just abort the optimization
1686 // Also avoid moving code above predicated instruction since it's hard to
1687 // reason about register liveness with predicated instruction.
1688 bool DontMoveAcrossStore = true;
1689 if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(PI))
1693 // Find out what registers are live. Note this routine is ignoring other live
1694 // registers which are only used by instructions in successor blocks.
1695 for (const MachineOperand &MO : PI->operands()) {
1698 unsigned Reg = MO.getReg();
1702 addRegAndItsAliases(Reg, TRI, Uses);
1704 if (Uses.erase(Reg)) {
1705 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1706 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1707 Uses.erase(*SubRegs); // Use sub-registers to be conservative
1710 addRegAndItsAliases(Reg, TRI, Defs);
1717 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1718 /// sequence at the start of the function, move the instructions before MBB
1719 /// terminator if it's legal.
1720 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1721 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1722 SmallVector<MachineOperand, 4> Cond;
1723 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1726 if (!FBB) FBB = findFalseBlock(MBB, TBB);
1728 // Malformed bcc? True and false blocks are the same?
1731 // Restrict the optimization to cases where MBB is the only predecessor,
1732 // it is an obvious win.
1733 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1736 // Find a suitable position to hoist the common instructions to. Also figure
1737 // out which registers are used or defined by instructions from the insertion
1738 // point to the end of the block.
1739 SmallSet<unsigned, 4> Uses, Defs;
1740 MachineBasicBlock::iterator Loc =
1741 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1742 if (Loc == MBB->end())
1745 bool HasDups = false;
1746 SmallVector<unsigned, 4> LocalDefs;
1747 SmallSet<unsigned, 4> LocalDefsSet;
1748 MachineBasicBlock::iterator TIB = TBB->begin();
1749 MachineBasicBlock::iterator FIB = FBB->begin();
1750 MachineBasicBlock::iterator TIE = TBB->end();
1751 MachineBasicBlock::iterator FIE = FBB->end();
1752 while (TIB != TIE && FIB != FIE) {
1753 // Skip dbg_value instructions. These do not count.
1754 if (TIB->isDebugValue()) {
1755 while (TIB != TIE && TIB->isDebugValue())
1760 if (FIB->isDebugValue()) {
1761 while (FIB != FIE && FIB->isDebugValue())
1766 if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
1769 if (TII->isPredicated(TIB))
1770 // Hard to reason about register liveness with predicated instruction.
1774 for (MachineOperand &MO : TIB->operands()) {
1775 // Don't attempt to hoist instructions with register masks.
1776 if (MO.isRegMask()) {
1782 unsigned Reg = MO.getReg();
1786 if (Uses.count(Reg)) {
1787 // Avoid clobbering a register that's used by the instruction at
1788 // the point of insertion.
1793 if (Defs.count(Reg) && !MO.isDead()) {
1794 // Don't hoist the instruction if the def would be clobber by the
1795 // instruction at the point insertion. FIXME: This is overly
1796 // conservative. It should be possible to hoist the instructions
1797 // in BB2 in the following example:
1799 // r1, eflag = op1 r2, r3
1808 } else if (!LocalDefsSet.count(Reg)) {
1809 if (Defs.count(Reg)) {
1810 // Use is defined by the instruction at the point of insertion.
1815 if (MO.isKill() && Uses.count(Reg))
1816 // Kills a register that's read by the instruction at the point of
1817 // insertion. Remove the kill marker.
1818 MO.setIsKill(false);
1824 bool DontMoveAcrossStore = true;
1825 if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
1828 // Remove kills from LocalDefsSet, these registers had short live ranges.
1829 for (const MachineOperand &MO : TIB->operands()) {
1830 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1832 unsigned Reg = MO.getReg();
1833 if (!Reg || !LocalDefsSet.count(Reg))
1835 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1836 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1837 LocalDefsSet.erase(*AI);
1839 LocalDefsSet.erase(Reg);
1843 // Track local defs so we can update liveins.
1844 for (const MachineOperand &MO : TIB->operands()) {
1845 if (!MO.isReg() || !MO.isDef() || MO.isDead())
1847 unsigned Reg = MO.getReg();
1850 LocalDefs.push_back(Reg);
1851 addRegAndItsAliases(Reg, TRI, LocalDefsSet);
1862 MBB->splice(Loc, TBB, TBB->begin(), TIB);
1863 FBB->erase(FBB->begin(), FIB);
1866 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1867 unsigned Def = LocalDefs[i];
1868 if (LocalDefsSet.count(Def)) {
1869 TBB->addLiveIn(Def);
1870 FBB->addLiveIn(Def);