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
17 //===----------------------------------------------------------------------===//
19 #include "BranchFolding.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "branchfolding"
45 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
46 STATISTIC(NumBranchOpts, "Number of branches optimized");
47 STATISTIC(NumTailMerge , "Number of block tails merged");
48 STATISTIC(NumHoist , "Number of times common instructions are hoisted");
50 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
51 cl::init(cl::BOU_UNSET), cl::Hidden);
53 // Throttle for huge numbers of predecessors (compile speed problems)
54 static cl::opt<unsigned>
55 TailMergeThreshold("tail-merge-threshold",
56 cl::desc("Max number of predecessors to consider tail merging"),
57 cl::init(150), cl::Hidden);
59 // Heuristic for tail merging (and, inversely, tail duplication).
60 // TODO: This should be replaced with a target query.
61 static cl::opt<unsigned>
62 TailMergeSize("tail-merge-size",
63 cl::desc("Min number of instructions to consider tail merging"),
64 cl::init(3), cl::Hidden);
67 /// BranchFolderPass - Wrap branch folder in a machine function pass.
68 class BranchFolderPass : public MachineFunctionPass {
71 explicit BranchFolderPass(): MachineFunctionPass(ID) {}
73 bool runOnMachineFunction(MachineFunction &MF) override;
75 void getAnalysisUsage(AnalysisUsage &AU) const override {
76 AU.addRequired<MachineBlockFrequencyInfo>();
77 AU.addRequired<MachineBranchProbabilityInfo>();
78 AU.addRequired<TargetPassConfig>();
79 MachineFunctionPass::getAnalysisUsage(AU);
84 char BranchFolderPass::ID = 0;
85 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
87 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
88 "Control Flow Optimizer", false, false)
90 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
91 if (skipOptnoneFunction(*MF.getFunction()))
94 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
95 // TailMerge can create jump into if branches that make CFG irreducible for
96 // HW that requires structurized CFG.
97 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
98 PassConfig->getEnableTailMerge();
99 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true,
100 getAnalysis<MachineBlockFrequencyInfo>(),
101 getAnalysis<MachineBranchProbabilityInfo>());
102 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
103 MF.getSubtarget().getRegisterInfo(),
104 getAnalysisIfAvailable<MachineModuleInfo>());
107 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
108 const MachineBlockFrequencyInfo &FreqInfo,
109 const MachineBranchProbabilityInfo &ProbInfo)
110 : EnableHoistCommonCode(CommonHoist), MBBFreqInfo(FreqInfo),
112 switch (FlagEnableTailMerge) {
113 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
114 case cl::BOU_TRUE: EnableTailMerge = true; break;
115 case cl::BOU_FALSE: EnableTailMerge = false; break;
119 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
120 /// function, updating the CFG.
121 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
122 assert(MBB->pred_empty() && "MBB must be dead!");
123 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
125 MachineFunction *MF = MBB->getParent();
126 // drop all successors.
127 while (!MBB->succ_empty())
128 MBB->removeSuccessor(MBB->succ_end()-1);
130 // Avoid matching if this pointer gets reused.
131 TriedMerging.erase(MBB);
137 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
138 /// followed by terminators, and if the implicitly defined registers are not
139 /// used by the terminators, remove those implicit_def's. e.g.
141 /// r0 = implicit_def
142 /// r1 = implicit_def
144 /// This block can be optimized away later if the implicit instructions are
146 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
147 SmallSet<unsigned, 4> ImpDefRegs;
148 MachineBasicBlock::iterator I = MBB->begin();
149 while (I != MBB->end()) {
150 if (!I->isImplicitDef())
152 unsigned Reg = I->getOperand(0).getReg();
153 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
154 SubRegs.isValid(); ++SubRegs)
155 ImpDefRegs.insert(*SubRegs);
158 if (ImpDefRegs.empty())
161 MachineBasicBlock::iterator FirstTerm = I;
162 while (I != MBB->end()) {
163 if (!TII->isUnpredicatedTerminator(I))
165 // See if it uses any of the implicitly defined registers.
166 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
167 MachineOperand &MO = I->getOperand(i);
168 if (!MO.isReg() || !MO.isUse())
170 unsigned Reg = MO.getReg();
171 if (ImpDefRegs.count(Reg))
178 while (I != FirstTerm) {
179 MachineInstr *ImpDefMI = &*I;
181 MBB->erase(ImpDefMI);
187 /// OptimizeFunction - Perhaps branch folding, tail merging and other
188 /// CFG optimizations on the given function.
189 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
190 const TargetInstrInfo *tii,
191 const TargetRegisterInfo *tri,
192 MachineModuleInfo *mmi) {
193 if (!tii) return false;
195 TriedMerging.clear();
202 // Use a RegScavenger to help update liveness when required.
203 MachineRegisterInfo &MRI = MF.getRegInfo();
204 if (MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
205 RS = new RegScavenger();
207 MRI.invalidateLiveness();
209 // Fix CFG. The later algorithms expect it to be right.
210 bool MadeChange = false;
211 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
212 MachineBasicBlock *MBB = I, *TBB = nullptr, *FBB = nullptr;
213 SmallVector<MachineOperand, 4> Cond;
214 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
215 MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
216 MadeChange |= OptimizeImpDefsBlock(MBB);
219 bool MadeChangeThisIteration = true;
220 while (MadeChangeThisIteration) {
221 MadeChangeThisIteration = TailMergeBlocks(MF);
222 MadeChangeThisIteration |= OptimizeBranches(MF);
223 if (EnableHoistCommonCode)
224 MadeChangeThisIteration |= HoistCommonCode(MF);
225 MadeChange |= MadeChangeThisIteration;
228 // See if any jump tables have become dead as the code generator
230 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
236 // Walk the function to find jump tables that are live.
237 BitVector JTIsLive(JTI->getJumpTables().size());
238 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
240 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
242 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
243 MachineOperand &Op = I->getOperand(op);
244 if (!Op.isJTI()) continue;
246 // Remember that this JT is live.
247 JTIsLive.set(Op.getIndex());
251 // Finally, remove dead jump tables. This happens when the
252 // indirect jump was unreachable (and thus deleted).
253 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
254 if (!JTIsLive.test(i)) {
255 JTI->RemoveJumpTable(i);
263 //===----------------------------------------------------------------------===//
264 // Tail Merging of Blocks
265 //===----------------------------------------------------------------------===//
267 /// HashEndOfMBB - Hash the last instruction in the MBB.
268 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
269 auto LastInst = MBB->getLastNonDebugInstr();
270 if (LastInst == MBB->end())
272 // Hash the instruction and all operands. MachineInstrExpressionTrait ignores
273 // vreg defs when computing the hash but we're post-regalloc here.
274 return MachineInstrExpressionTrait::getHashValue(LastInst);
277 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
278 /// of instructions they actually have in common together at their end. Return
279 /// iterators for the first shared instruction in each block.
280 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
281 MachineBasicBlock *MBB2,
282 MachineBasicBlock::iterator &I1,
283 MachineBasicBlock::iterator &I2) {
287 unsigned TailLen = 0;
288 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
290 // Skip debugging pseudos; necessary to avoid changing the code.
291 while (I1->isDebugValue()) {
292 if (I1==MBB1->begin()) {
293 while (I2->isDebugValue()) {
294 if (I2==MBB2->begin())
295 // I1==DBG at begin; I2==DBG at begin
300 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
305 // I1==first (untested) non-DBG preceding known match
306 while (I2->isDebugValue()) {
307 if (I2==MBB2->begin()) {
309 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
314 // I1, I2==first (untested) non-DBGs preceding known match
315 if (!I1->isIdenticalTo(I2) ||
316 // FIXME: This check is dubious. It's used to get around a problem where
317 // people incorrectly expect inline asm directives to remain in the same
318 // relative order. This is untenable because normal compiler
319 // optimizations (like this one) may reorder and/or merge these
327 // Back past possible debugging pseudos at beginning of block. This matters
328 // when one block differs from the other only by whether debugging pseudos
329 // are present at the beginning. (This way, the various checks later for
330 // I1==MBB1->begin() work as expected.)
331 if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
333 while (I2->isDebugValue()) {
334 if (I2 == MBB2->begin())
340 if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
342 while (I1->isDebugValue()) {
343 if (I1 == MBB1->begin())
352 void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
353 MachineBasicBlock *NewMBB) {
355 RS->enterBasicBlock(CurMBB);
356 if (!CurMBB->empty())
357 RS->forward(std::prev(CurMBB->end()));
358 for (unsigned int i = 1, e = TRI->getNumRegs(); i != e; i++)
359 if (RS->isRegUsed(i, false))
360 NewMBB->addLiveIn(i);
364 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
365 /// after it, replacing it with an unconditional branch to NewDest.
366 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
367 MachineBasicBlock *NewDest) {
368 MachineBasicBlock *CurMBB = OldInst->getParent();
370 TII->ReplaceTailWithBranchTo(OldInst, NewDest);
372 // For targets that use the register scavenger, we must maintain LiveIns.
373 MaintainLiveIns(CurMBB, NewDest);
378 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
379 /// MBB so that the part before the iterator falls into the part starting at the
380 /// iterator. This returns the new MBB.
381 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
382 MachineBasicBlock::iterator BBI1,
383 const BasicBlock *BB) {
384 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
387 MachineFunction &MF = *CurMBB.getParent();
389 // Create the fall-through block.
390 MachineFunction::iterator MBBI = &CurMBB;
391 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
392 CurMBB.getParent()->insert(++MBBI, NewMBB);
394 // Move all the successors of this block to the specified block.
395 NewMBB->transferSuccessors(&CurMBB);
397 // Add an edge from CurMBB to NewMBB for the fall-through.
398 CurMBB.addSuccessor(NewMBB);
400 // Splice the code over.
401 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
403 // NewMBB inherits CurMBB's block frequency.
404 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
406 // For targets that use the register scavenger, we must maintain LiveIns.
407 MaintainLiveIns(&CurMBB, NewMBB);
412 /// EstimateRuntime - Make a rough estimate for how long it will take to run
413 /// the specified code.
414 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
415 MachineBasicBlock::iterator E) {
417 for (; I != E; ++I) {
418 if (I->isDebugValue())
422 else if (I->mayLoad() || I->mayStore())
430 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
431 // branches temporarily for tail merging). In the case where CurMBB ends
432 // with a conditional branch to the next block, optimize by reversing the
433 // test and conditionally branching to SuccMBB instead.
434 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
435 const TargetInstrInfo *TII) {
436 MachineFunction *MF = CurMBB->getParent();
437 MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
438 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
439 SmallVector<MachineOperand, 4> Cond;
440 DebugLoc dl; // FIXME: this is nowhere
441 if (I != MF->end() &&
442 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
443 MachineBasicBlock *NextBB = I;
444 if (TBB == NextBB && !Cond.empty() && !FBB) {
445 if (!TII->ReverseBranchCondition(Cond)) {
446 TII->RemoveBranch(*CurMBB);
447 TII->InsertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
452 TII->InsertBranch(*CurMBB, SuccBB, nullptr,
453 SmallVector<MachineOperand, 0>(), dl);
457 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
458 if (getHash() < o.getHash())
460 if (getHash() > o.getHash())
462 if (getBlock()->getNumber() < o.getBlock()->getNumber())
464 if (getBlock()->getNumber() > o.getBlock()->getNumber())
466 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
467 // an object with itself.
468 #ifndef _GLIBCXX_DEBUG
469 llvm_unreachable("Predecessor appears twice");
476 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
477 auto I = MergedBBFreq.find(MBB);
479 if (I != MergedBBFreq.end())
482 return MBFI.getBlockFreq(MBB);
485 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
487 MergedBBFreq[MBB] = F;
490 /// CountTerminators - Count the number of terminators in the given
491 /// block and set I to the position of the first non-terminator, if there
492 /// is one, or MBB->end() otherwise.
493 static unsigned CountTerminators(MachineBasicBlock *MBB,
494 MachineBasicBlock::iterator &I) {
496 unsigned NumTerms = 0;
498 if (I == MBB->begin()) {
503 if (!I->isTerminator()) break;
509 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
510 /// and decide if it would be profitable to merge those tails. Return the
511 /// length of the common tail and iterators to the first common instruction
513 static bool ProfitableToMerge(MachineBasicBlock *MBB1,
514 MachineBasicBlock *MBB2,
515 unsigned minCommonTailLength,
516 unsigned &CommonTailLen,
517 MachineBasicBlock::iterator &I1,
518 MachineBasicBlock::iterator &I2,
519 MachineBasicBlock *SuccBB,
520 MachineBasicBlock *PredBB) {
521 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
522 if (CommonTailLen == 0)
524 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
525 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
528 // It's almost always profitable to merge any number of non-terminator
529 // instructions with the block that falls through into the common successor.
530 if (MBB1 == PredBB || MBB2 == PredBB) {
531 MachineBasicBlock::iterator I;
532 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
533 if (CommonTailLen > NumTerms)
537 // If one of the blocks can be completely merged and happens to be in
538 // a position where the other could fall through into it, merge any number
539 // of instructions, because it can be done without a branch.
540 // TODO: If the blocks are not adjacent, move one of them so that they are?
541 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
543 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
546 // If both blocks have an unconditional branch temporarily stripped out,
547 // count that as an additional common instruction for the following
549 unsigned EffectiveTailLen = CommonTailLen;
550 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
551 !MBB1->back().isBarrier() &&
552 !MBB2->back().isBarrier())
555 // Check if the common tail is long enough to be worthwhile.
556 if (EffectiveTailLen >= minCommonTailLength)
559 // If we are optimizing for code size, 2 instructions in common is enough if
560 // we don't have to split a block. At worst we will be introducing 1 new
561 // branch instruction, which is likely to be smaller than the 2
562 // instructions that would be deleted in the merge.
563 MachineFunction *MF = MBB1->getParent();
564 if (EffectiveTailLen >= 2 &&
565 MF->getFunction()->hasFnAttribute(Attribute::OptimizeForSize) &&
566 (I1 == MBB1->begin() || I2 == MBB2->begin()))
572 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
573 /// hash CurHash (guaranteed to match the last element). Build the vector
574 /// SameTails of all those that have the (same) largest number of instructions
575 /// in common of any pair of these blocks. SameTails entries contain an
576 /// iterator into MergePotentials (from which the MachineBasicBlock can be
577 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
578 /// instruction where the matching code sequence begins.
579 /// Order of elements in SameTails is the reverse of the order in which
580 /// those blocks appear in MergePotentials (where they are not necessarily
582 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
583 unsigned minCommonTailLength,
584 MachineBasicBlock *SuccBB,
585 MachineBasicBlock *PredBB) {
586 unsigned maxCommonTailLength = 0U;
588 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
589 MPIterator HighestMPIter = std::prev(MergePotentials.end());
590 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
591 B = MergePotentials.begin();
592 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
593 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
594 unsigned CommonTailLen;
595 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
597 CommonTailLen, TrialBBI1, TrialBBI2,
599 if (CommonTailLen > maxCommonTailLength) {
601 maxCommonTailLength = CommonTailLen;
602 HighestMPIter = CurMPIter;
603 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
605 if (HighestMPIter == CurMPIter &&
606 CommonTailLen == maxCommonTailLength)
607 SameTails.push_back(SameTailElt(I, TrialBBI2));
613 return maxCommonTailLength;
616 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
617 /// MergePotentials, restoring branches at ends of blocks as appropriate.
618 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
619 MachineBasicBlock *SuccBB,
620 MachineBasicBlock *PredBB) {
621 MPIterator CurMPIter, B;
622 for (CurMPIter = std::prev(MergePotentials.end()),
623 B = MergePotentials.begin();
624 CurMPIter->getHash() == CurHash; --CurMPIter) {
625 // Put the unconditional branch back, if we need one.
626 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
627 if (SuccBB && CurMBB != PredBB)
628 FixTail(CurMBB, SuccBB, TII);
632 if (CurMPIter->getHash() != CurHash)
634 MergePotentials.erase(CurMPIter, MergePotentials.end());
637 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
638 /// only of the common tail. Create a block that does by splitting one.
639 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
640 MachineBasicBlock *SuccBB,
641 unsigned maxCommonTailLength,
642 unsigned &commonTailIndex) {
644 unsigned TimeEstimate = ~0U;
645 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
646 // Use PredBB if possible; that doesn't require a new branch.
647 if (SameTails[i].getBlock() == PredBB) {
651 // Otherwise, make a (fairly bogus) choice based on estimate of
652 // how long it will take the various blocks to execute.
653 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
654 SameTails[i].getTailStartPos());
655 if (t <= TimeEstimate) {
661 MachineBasicBlock::iterator BBI =
662 SameTails[commonTailIndex].getTailStartPos();
663 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
665 // If the common tail includes any debug info we will take it pretty
666 // randomly from one of the inputs. Might be better to remove it?
667 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
668 << maxCommonTailLength);
670 // If the split block unconditionally falls-thru to SuccBB, it will be
671 // merged. In control flow terms it should then take SuccBB's name. e.g. If
672 // SuccBB is an inner loop, the common tail is still part of the inner loop.
673 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
674 SuccBB->getBasicBlock() : MBB->getBasicBlock();
675 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
677 DEBUG(dbgs() << "... failed!");
681 SameTails[commonTailIndex].setBlock(newMBB);
682 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
684 // If we split PredBB, newMBB is the new predecessor.
691 static bool hasIdenticalMMOs(const MachineInstr *MI1, const MachineInstr *MI2) {
692 auto I1 = MI1->memoperands_begin(), E1 = MI1->memoperands_end();
693 auto I2 = MI2->memoperands_begin(), E2 = MI2->memoperands_end();
694 if ((E1 - I1) != (E2 - I2))
696 for (; I1 != E1; ++I1, ++I2) {
704 removeMMOsFromMemoryOperations(MachineBasicBlock::iterator MBBIStartPos,
705 MachineBasicBlock &MBBCommon) {
706 // Remove MMOs from memory operations in the common block
707 // when they do not match the ones from the block being tail-merged.
708 // This ensures later passes conservatively compute dependencies.
709 MachineBasicBlock *MBB = MBBIStartPos->getParent();
710 // Note CommonTailLen does not necessarily matches the size of
711 // the common BB nor all its instructions because of debug
712 // instructions differences.
713 unsigned CommonTailLen = 0;
714 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
717 MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
718 MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
719 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
720 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
722 while (CommonTailLen--) {
723 assert(MBBI != MBBIE && "Reached BB end within common tail length!");
726 if (MBBI->isDebugValue()) {
731 while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
734 assert(MBBICommon != MBBIECommon &&
735 "Reached BB end within common tail length!");
736 assert(MBBICommon->isIdenticalTo(&*MBBI) && "Expected matching MIIs!");
738 if (MBBICommon->mayLoad() || MBBICommon->mayStore())
739 if (!hasIdenticalMMOs(&*MBBI, &*MBBICommon))
740 MBBICommon->clearMemRefs();
747 // See if any of the blocks in MergePotentials (which all have a common single
748 // successor, or all have no successor) can be tail-merged. If there is a
749 // successor, any blocks in MergePotentials that are not tail-merged and
750 // are not immediately before Succ must have an unconditional branch to
751 // Succ added (but the predecessor/successor lists need no adjustment).
752 // The lone predecessor of Succ that falls through into Succ,
753 // if any, is given in PredBB.
755 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
756 MachineBasicBlock *PredBB) {
757 bool MadeChange = false;
759 // Except for the special cases below, tail-merge if there are at least
760 // this many instructions in common.
761 unsigned minCommonTailLength = TailMergeSize;
763 DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
764 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
765 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
766 << (i == e-1 ? "" : ", ");
769 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
771 dbgs() << " which has fall-through from BB#"
772 << PredBB->getNumber() << "\n";
774 dbgs() << "Looking for common tails of at least "
775 << minCommonTailLength << " instruction"
776 << (minCommonTailLength == 1 ? "" : "s") << '\n';
779 // Sort by hash value so that blocks with identical end sequences sort
781 array_pod_sort(MergePotentials.begin(), MergePotentials.end());
783 // Walk through equivalence sets looking for actual exact matches.
784 while (MergePotentials.size() > 1) {
785 unsigned CurHash = MergePotentials.back().getHash();
787 // Build SameTails, identifying the set of blocks with this hash code
788 // and with the maximum number of instructions in common.
789 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
793 // If we didn't find any pair that has at least minCommonTailLength
794 // instructions in common, remove all blocks with this hash code and retry.
795 if (SameTails.empty()) {
796 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
800 // If one of the blocks is the entire common tail (and not the entry
801 // block, which we can't jump to), we can treat all blocks with this same
802 // tail at once. Use PredBB if that is one of the possibilities, as that
803 // will not introduce any extra branches.
804 MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
805 getParent()->begin();
806 unsigned commonTailIndex = SameTails.size();
807 // If there are two blocks, check to see if one can be made to fall through
809 if (SameTails.size() == 2 &&
810 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
811 SameTails[1].tailIsWholeBlock())
813 else if (SameTails.size() == 2 &&
814 SameTails[1].getBlock()->isLayoutSuccessor(
815 SameTails[0].getBlock()) &&
816 SameTails[0].tailIsWholeBlock())
819 // Otherwise just pick one, favoring the fall-through predecessor if
821 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
822 MachineBasicBlock *MBB = SameTails[i].getBlock();
823 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
829 if (SameTails[i].tailIsWholeBlock())
834 if (commonTailIndex == SameTails.size() ||
835 (SameTails[commonTailIndex].getBlock() == PredBB &&
836 !SameTails[commonTailIndex].tailIsWholeBlock())) {
837 // None of the blocks consist entirely of the common tail.
838 // Split a block so that one does.
839 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
840 maxCommonTailLength, commonTailIndex)) {
841 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
846 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
848 // Recompute commont tail MBB's edge weights and block frequency.
849 setCommonTailEdgeWeights(*MBB);
851 // MBB is common tail. Adjust all other BB's to jump to this one.
852 // Traversal must be forwards so erases work.
853 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
855 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
856 if (commonTailIndex == i)
858 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
859 << (i == e-1 ? "" : ", "));
860 // Remove MMOs from memory operations as needed.
861 removeMMOsFromMemoryOperations(SameTails[i].getTailStartPos(), *MBB);
862 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
863 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
864 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
865 MergePotentials.erase(SameTails[i].getMPIter());
867 DEBUG(dbgs() << "\n");
868 // We leave commonTailIndex in the worklist in case there are other blocks
869 // that match it with a smaller number of instructions.
875 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
876 bool MadeChange = false;
877 if (!EnableTailMerge) return MadeChange;
879 // First find blocks with no successors.
880 MergePotentials.clear();
881 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
882 I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
883 if (TriedMerging.count(I))
886 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
889 // If this is a large problem, avoid visiting the same basic blocks
891 if (MergePotentials.size() == TailMergeThreshold)
892 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
893 TriedMerging.insert(MergePotentials[i].getBlock());
895 // See if we can do any tail merging on those.
896 if (MergePotentials.size() >= 2)
897 MadeChange |= TryTailMergeBlocks(nullptr, nullptr);
899 // Look at blocks (IBB) with multiple predecessors (PBB).
900 // We change each predecessor to a canonical form, by
901 // (1) temporarily removing any unconditional branch from the predecessor
903 // (2) alter conditional branches so they branch to the other block
904 // not IBB; this may require adding back an unconditional branch to IBB
905 // later, where there wasn't one coming in. E.g.
907 // fallthrough to QBB
910 // with a conceptual B to IBB after that, which never actually exists.
911 // With those changes, we see whether the predecessors' tails match,
912 // and merge them if so. We change things out of canonical form and
913 // back to the way they were later in the process. (OptimizeBranches
914 // would undo some of this, but we can't use it, because we'd get into
915 // a compile-time infinite loop repeatedly doing and undoing the same
918 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
920 if (I->pred_size() < 2) continue;
921 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
922 MachineBasicBlock *IBB = I;
923 MachineBasicBlock *PredBB = std::prev(I);
924 MergePotentials.clear();
925 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
927 P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) {
928 MachineBasicBlock *PBB = *P;
929 if (TriedMerging.count(PBB))
932 // Skip blocks that loop to themselves, can't tail merge these.
936 // Visit each predecessor only once.
937 if (!UniquePreds.insert(PBB).second)
940 // Skip blocks which may jump to a landing pad. Can't tail merge these.
941 if (PBB->getLandingPadSuccessor())
944 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
945 SmallVector<MachineOperand, 4> Cond;
946 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
947 // Failing case: IBB is the target of a cbr, and we cannot reverse the
949 SmallVector<MachineOperand, 4> NewCond(Cond);
950 if (!Cond.empty() && TBB == IBB) {
951 if (TII->ReverseBranchCondition(NewCond))
953 // This is the QBB case described above
955 FBB = std::next(MachineFunction::iterator(PBB));
958 // Failing case: the only way IBB can be reached from PBB is via
959 // exception handling. Happens for landing pads. Would be nice to have
960 // a bit in the edge so we didn't have to do all this.
961 if (IBB->isLandingPad()) {
962 MachineFunction::iterator IP = PBB; IP++;
963 MachineBasicBlock *PredNextBB = nullptr;
967 if (IBB != PredNextBB) // fallthrough
970 if (TBB != IBB && FBB != IBB) // cbr then ubr
972 } else if (Cond.empty()) {
973 if (TBB != IBB) // ubr
976 if (TBB != IBB && IBB != PredNextBB) // cbr
981 // Remove the unconditional branch at the end, if any.
982 if (TBB && (Cond.empty() || FBB)) {
983 DebugLoc dl; // FIXME: this is nowhere
984 TII->RemoveBranch(*PBB);
986 // reinsert conditional branch only, for now
987 TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
991 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
995 // If this is a large problem, avoid visiting the same basic blocks multiple
997 if (MergePotentials.size() == TailMergeThreshold)
998 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
999 TriedMerging.insert(MergePotentials[i].getBlock());
1001 if (MergePotentials.size() >= 2)
1002 MadeChange |= TryTailMergeBlocks(IBB, PredBB);
1004 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1005 // result of removing blocks in TryTailMergeBlocks.
1006 PredBB = std::prev(I); // this may have been changed in TryTailMergeBlocks
1007 if (MergePotentials.size() == 1 &&
1008 MergePotentials.begin()->getBlock() != PredBB)
1009 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1015 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1016 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1017 BlockFrequency AccumulatedMBBFreq;
1019 // Aggregate edge frequency of successor edge j:
1020 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1021 // where bb is a basic block that is in SameTails.
1022 for (const auto &Src : SameTails) {
1023 const MachineBasicBlock *SrcMBB = Src.getBlock();
1024 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1025 AccumulatedMBBFreq += BlockFreq;
1027 // It is not necessary to recompute edge weights if TailBB has less than two
1029 if (TailMBB.succ_size() <= 1)
1032 auto EdgeFreq = EdgeFreqLs.begin();
1034 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1035 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1036 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1039 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1041 if (TailMBB.succ_size() <= 1)
1044 auto MaxEdgeFreq = *std::max_element(EdgeFreqLs.begin(), EdgeFreqLs.end());
1045 uint64_t Scale = MaxEdgeFreq.getFrequency() / UINT32_MAX + 1;
1046 auto EdgeFreq = EdgeFreqLs.begin();
1048 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1049 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1050 TailMBB.setSuccWeight(SuccI, EdgeFreq->getFrequency() / Scale);
1053 //===----------------------------------------------------------------------===//
1054 // Branch Optimization
1055 //===----------------------------------------------------------------------===//
1057 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1058 bool MadeChange = false;
1060 // Make sure blocks are numbered in order
1061 MF.RenumberBlocks();
1063 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1065 MachineBasicBlock *MBB = I++;
1066 MadeChange |= OptimizeBlock(MBB);
1068 // If it is dead, remove it.
1069 if (MBB->pred_empty()) {
1070 RemoveDeadBlock(MBB);
1078 // Blocks should be considered empty if they contain only debug info;
1079 // else the debug info would affect codegen.
1080 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1083 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
1084 MBBI!=MBBE; ++MBBI) {
1085 if (!MBBI->isDebugValue())
1091 // Blocks with only debug info and branches should be considered the same
1092 // as blocks with only branches.
1093 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1094 MachineBasicBlock::iterator MBBI, MBBE;
1095 for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
1096 if (!MBBI->isDebugValue())
1099 return (MBBI->isBranch());
1102 /// IsBetterFallthrough - Return true if it would be clearly better to
1103 /// fall-through to MBB1 than to fall through into MBB2. This has to return
1104 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1105 /// result in infinite loops.
1106 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1107 MachineBasicBlock *MBB2) {
1108 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1109 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1110 // optimize branches that branch to either a return block or an assert block
1111 // into a fallthrough to the return.
1112 if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
1114 // If there is a clear successor ordering we make sure that one block
1115 // will fall through to the next
1116 if (MBB1->isSuccessor(MBB2)) return true;
1117 if (MBB2->isSuccessor(MBB1)) return false;
1119 // Neither block consists entirely of debug info (per IsEmptyBlock check),
1120 // so we needn't test for falling off the beginning here.
1121 MachineBasicBlock::iterator MBB1I = --MBB1->end();
1122 while (MBB1I->isDebugValue())
1124 MachineBasicBlock::iterator MBB2I = --MBB2->end();
1125 while (MBB2I->isDebugValue())
1127 return MBB2I->isCall() && !MBB1I->isCall();
1130 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1131 /// instructions on the block. Always use the DebugLoc of the first
1132 /// branching instruction found unless its absent, in which case use the
1133 /// DebugLoc of the second if present.
1134 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1135 MachineBasicBlock::iterator I = MBB.end();
1136 if (I == MBB.begin())
1139 while (I->isDebugValue() && I != MBB.begin())
1142 return I->getDebugLoc();
1146 /// OptimizeBlock - Analyze and optimize control flow related to the specified
1147 /// block. This is never called on the entry block.
1148 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1149 bool MadeChange = false;
1150 MachineFunction &MF = *MBB->getParent();
1153 MachineFunction::iterator FallThrough = MBB;
1156 // If this block is empty, make everyone use its fall-through, not the block
1157 // explicitly. Landing pads should not do this since the landing-pad table
1158 // points to this block. Blocks with their addresses taken shouldn't be
1160 if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
1161 // Dead block? Leave for cleanup later.
1162 if (MBB->pred_empty()) return MadeChange;
1164 if (FallThrough == MF.end()) {
1165 // TODO: Simplify preds to not branch here if possible!
1166 } else if (FallThrough->isLandingPad()) {
1167 // Don't rewrite to a landing pad fallthough. That could lead to the case
1168 // where a BB jumps to more than one landing pad.
1169 // TODO: Is it ever worth rewriting predecessors which don't already
1170 // jump to a landing pad, and so can safely jump to the fallthrough?
1172 // Rewrite all predecessors of the old block to go to the fallthrough
1174 while (!MBB->pred_empty()) {
1175 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1176 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
1178 // If MBB was the target of a jump table, update jump tables to go to the
1179 // fallthrough instead.
1180 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1181 MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
1187 // Check to see if we can simplify the terminator of the block before this
1189 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1191 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1192 SmallVector<MachineOperand, 4> PriorCond;
1193 bool PriorUnAnalyzable =
1194 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1195 if (!PriorUnAnalyzable) {
1196 // If the CFG for the prior block has extra edges, remove them.
1197 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1198 !PriorCond.empty());
1200 // If the previous branch is conditional and both conditions go to the same
1201 // destination, remove the branch, replacing it with an unconditional one or
1203 if (PriorTBB && PriorTBB == PriorFBB) {
1204 DebugLoc dl = getBranchDebugLoc(PrevBB);
1205 TII->RemoveBranch(PrevBB);
1207 if (PriorTBB != MBB)
1208 TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1211 goto ReoptimizeBlock;
1214 // If the previous block unconditionally falls through to this block and
1215 // this block has no other predecessors, move the contents of this block
1216 // into the prior block. This doesn't usually happen when SimplifyCFG
1217 // has been used, but it can happen if tail merging splits a fall-through
1218 // predecessor of a block.
1219 // This has to check PrevBB->succ_size() because EH edges are ignored by
1221 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1222 PrevBB.succ_size() == 1 &&
1223 !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
1224 DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1225 << "From MBB: " << *MBB);
1226 // Remove redundant DBG_VALUEs first.
1227 if (PrevBB.begin() != PrevBB.end()) {
1228 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1230 MachineBasicBlock::iterator MBBIter = MBB->begin();
1231 // Check if DBG_VALUE at the end of PrevBB is identical to the
1232 // DBG_VALUE at the beginning of MBB.
1233 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1234 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1235 if (!MBBIter->isIdenticalTo(PrevBBIter))
1237 MachineInstr *DuplicateDbg = MBBIter;
1238 ++MBBIter; -- PrevBBIter;
1239 DuplicateDbg->eraseFromParent();
1242 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1243 PrevBB.removeSuccessor(PrevBB.succ_begin());
1244 assert(PrevBB.succ_empty());
1245 PrevBB.transferSuccessors(MBB);
1250 // If the previous branch *only* branches to *this* block (conditional or
1251 // not) remove the branch.
1252 if (PriorTBB == MBB && !PriorFBB) {
1253 TII->RemoveBranch(PrevBB);
1256 goto ReoptimizeBlock;
1259 // If the prior block branches somewhere else on the condition and here if
1260 // the condition is false, remove the uncond second branch.
1261 if (PriorFBB == MBB) {
1262 DebugLoc dl = getBranchDebugLoc(PrevBB);
1263 TII->RemoveBranch(PrevBB);
1264 TII->InsertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1267 goto ReoptimizeBlock;
1270 // If the prior block branches here on true and somewhere else on false, and
1271 // if the branch condition is reversible, reverse the branch to create a
1273 if (PriorTBB == MBB) {
1274 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1275 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1276 DebugLoc dl = getBranchDebugLoc(PrevBB);
1277 TII->RemoveBranch(PrevBB);
1278 TII->InsertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1281 goto ReoptimizeBlock;
1285 // If this block has no successors (e.g. it is a return block or ends with
1286 // a call to a no-return function like abort or __cxa_throw) and if the pred
1287 // falls through into this block, and if it would otherwise fall through
1288 // into the block after this, move this block to the end of the function.
1290 // We consider it more likely that execution will stay in the function (e.g.
1291 // due to loops) than it is to exit it. This asserts in loops etc, moving
1292 // the assert condition out of the loop body.
1293 if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1294 MachineFunction::iterator(PriorTBB) == FallThrough &&
1295 !MBB->canFallThrough()) {
1296 bool DoTransform = true;
1298 // We have to be careful that the succs of PredBB aren't both no-successor
1299 // blocks. If neither have successors and if PredBB is the second from
1300 // last block in the function, we'd just keep swapping the two blocks for
1301 // last. Only do the swap if one is clearly better to fall through than
1303 if (FallThrough == --MF.end() &&
1304 !IsBetterFallthrough(PriorTBB, MBB))
1305 DoTransform = false;
1308 // Reverse the branch so we will fall through on the previous true cond.
1309 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1310 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1311 DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1312 << "To make fallthrough to: " << *PriorTBB << "\n");
1314 DebugLoc dl = getBranchDebugLoc(PrevBB);
1315 TII->RemoveBranch(PrevBB);
1316 TII->InsertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1318 // Move this block to the end of the function.
1319 MBB->moveAfter(--MF.end());
1328 // Analyze the branch in the current block.
1329 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1330 SmallVector<MachineOperand, 4> CurCond;
1331 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1332 if (!CurUnAnalyzable) {
1333 // If the CFG for the prior block has extra edges, remove them.
1334 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1336 // If this is a two-way branch, and the FBB branches to this block, reverse
1337 // the condition so the single-basic-block loop is faster. Instead of:
1338 // Loop: xxx; jcc Out; jmp Loop
1340 // Loop: xxx; jncc Loop; jmp Out
1341 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1342 SmallVector<MachineOperand, 4> NewCond(CurCond);
1343 if (!TII->ReverseBranchCondition(NewCond)) {
1344 DebugLoc dl = getBranchDebugLoc(*MBB);
1345 TII->RemoveBranch(*MBB);
1346 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1349 goto ReoptimizeBlock;
1353 // If this branch is the only thing in its block, see if we can forward
1354 // other blocks across it.
1355 if (CurTBB && CurCond.empty() && !CurFBB &&
1356 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1357 !MBB->hasAddressTaken()) {
1358 DebugLoc dl = getBranchDebugLoc(*MBB);
1359 // This block may contain just an unconditional branch. Because there can
1360 // be 'non-branch terminators' in the block, try removing the branch and
1361 // then seeing if the block is empty.
1362 TII->RemoveBranch(*MBB);
1363 // If the only things remaining in the block are debug info, remove these
1364 // as well, so this will behave the same as an empty block in non-debug
1366 if (!MBB->empty()) {
1367 bool NonDebugInfoFound = false;
1368 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1370 if (!I->isDebugValue()) {
1371 NonDebugInfoFound = true;
1375 if (!NonDebugInfoFound)
1376 // Make the block empty, losing the debug info (we could probably
1377 // improve this in some cases.)
1378 MBB->erase(MBB->begin(), MBB->end());
1380 // If this block is just an unconditional branch to CurTBB, we can
1381 // usually completely eliminate the block. The only case we cannot
1382 // completely eliminate the block is when the block before this one
1383 // falls through into MBB and we can't understand the prior block's branch
1386 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1387 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1388 !PrevBB.isSuccessor(MBB)) {
1389 // If the prior block falls through into us, turn it into an
1390 // explicit branch to us to make updates simpler.
1391 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1392 PriorTBB != MBB && PriorFBB != MBB) {
1394 assert(PriorCond.empty() && !PriorFBB &&
1395 "Bad branch analysis");
1398 assert(!PriorFBB && "Machine CFG out of date!");
1401 DebugLoc pdl = getBranchDebugLoc(PrevBB);
1402 TII->RemoveBranch(PrevBB);
1403 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1406 // Iterate through all the predecessors, revectoring each in-turn.
1408 bool DidChange = false;
1409 bool HasBranchToSelf = false;
1410 while(PI != MBB->pred_size()) {
1411 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1413 // If this block has an uncond branch to itself, leave it.
1415 HasBranchToSelf = true;
1418 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1419 // If this change resulted in PMBB ending in a conditional
1420 // branch where both conditions go to the same destination,
1421 // change this to an unconditional branch (and fix the CFG).
1422 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1423 SmallVector<MachineOperand, 4> NewCurCond;
1424 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1425 NewCurFBB, NewCurCond, true);
1426 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1427 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1428 TII->RemoveBranch(*PMBB);
1430 TII->InsertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1433 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1438 // Change any jumptables to go to the new MBB.
1439 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1440 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1444 if (!HasBranchToSelf) return MadeChange;
1449 // Add the branch back if the block is more than just an uncond branch.
1450 TII->InsertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1454 // If the prior block doesn't fall through into this block, and if this
1455 // block doesn't fall through into some other block, see if we can find a
1456 // place to move this block where a fall-through will happen.
1457 if (!PrevBB.canFallThrough()) {
1459 // Now we know that there was no fall-through into this block, check to
1460 // see if it has a fall-through into its successor.
1461 bool CurFallsThru = MBB->canFallThrough();
1463 if (!MBB->isLandingPad()) {
1464 // Check all the predecessors of this block. If one of them has no fall
1465 // throughs, move this block right after it.
1466 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1467 E = MBB->pred_end(); PI != E; ++PI) {
1468 // Analyze the branch at the end of the pred.
1469 MachineBasicBlock *PredBB = *PI;
1470 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1471 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1472 SmallVector<MachineOperand, 4> PredCond;
1473 if (PredBB != MBB && !PredBB->canFallThrough() &&
1474 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
1475 && (!CurFallsThru || !CurTBB || !CurFBB)
1476 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1477 // If the current block doesn't fall through, just move it.
1478 // If the current block can fall through and does not end with a
1479 // conditional branch, we need to append an unconditional jump to
1480 // the (current) next block. To avoid a possible compile-time
1481 // infinite loop, move blocks only backward in this case.
1482 // Also, if there are already 2 branches here, we cannot add a third;
1483 // this means we have the case
1488 MachineBasicBlock *NextBB =
1489 std::next(MachineFunction::iterator(MBB));
1491 TII->InsertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1493 MBB->moveAfter(PredBB);
1495 goto ReoptimizeBlock;
1500 if (!CurFallsThru) {
1501 // Check all successors to see if we can move this block before it.
1502 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1503 E = MBB->succ_end(); SI != E; ++SI) {
1504 // Analyze the branch at the end of the block before the succ.
1505 MachineBasicBlock *SuccBB = *SI;
1506 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1508 // If this block doesn't already fall-through to that successor, and if
1509 // the succ doesn't already have a block that can fall through into it,
1510 // and if the successor isn't an EH destination, we can arrange for the
1511 // fallthrough to happen.
1512 if (SuccBB != MBB && &*SuccPrev != MBB &&
1513 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1514 !SuccBB->isLandingPad()) {
1515 MBB->moveBefore(SuccBB);
1517 goto ReoptimizeBlock;
1521 // Okay, there is no really great place to put this block. If, however,
1522 // the block before this one would be a fall-through if this block were
1523 // removed, move this block to the end of the function.
1524 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1525 SmallVector<MachineOperand, 4> PrevCond;
1526 if (FallThrough != MF.end() &&
1527 !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1528 PrevBB.isSuccessor(FallThrough)) {
1529 MBB->moveAfter(--MF.end());
1539 //===----------------------------------------------------------------------===//
1540 // Hoist Common Code
1541 //===----------------------------------------------------------------------===//
1543 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1544 /// blocks to their common predecessor.
1545 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1546 bool MadeChange = false;
1547 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1548 MachineBasicBlock *MBB = I++;
1549 MadeChange |= HoistCommonCodeInSuccs(MBB);
1555 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1556 /// its 'true' successor.
1557 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1558 MachineBasicBlock *TrueBB) {
1559 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1560 E = BB->succ_end(); SI != E; ++SI) {
1561 MachineBasicBlock *SuccBB = *SI;
1562 if (SuccBB != TrueBB)
1568 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1569 /// in successors to. The location is usually just before the terminator,
1570 /// however if the terminator is a conditional branch and its previous
1571 /// instruction is the flag setting instruction, the previous instruction is
1572 /// the preferred location. This function also gathers uses and defs of the
1573 /// instructions from the insertion point to the end of the block. The data is
1574 /// used by HoistCommonCodeInSuccs to ensure safety.
1576 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1577 const TargetInstrInfo *TII,
1578 const TargetRegisterInfo *TRI,
1579 SmallSet<unsigned,4> &Uses,
1580 SmallSet<unsigned,4> &Defs) {
1581 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1582 if (!TII->isUnpredicatedTerminator(Loc))
1585 for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
1586 const MachineOperand &MO = Loc->getOperand(i);
1589 unsigned Reg = MO.getReg();
1593 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1597 // Don't try to hoist code in the rare case the terminator defines a
1598 // register that is later used.
1601 // If the terminator defines a register, make sure we don't hoist
1602 // the instruction whose def might be clobbered by the terminator.
1603 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1610 if (Loc == MBB->begin())
1613 // The terminator is probably a conditional branch, try not to separate the
1614 // branch from condition setting instruction.
1615 MachineBasicBlock::iterator PI = Loc;
1617 while (PI != MBB->begin() && PI->isDebugValue())
1621 for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
1622 const MachineOperand &MO = PI->getOperand(i);
1623 // If PI has a regmask operand, it is probably a call. Separate away.
1626 if (!MO.isReg() || MO.isUse())
1628 unsigned Reg = MO.getReg();
1631 if (Uses.count(Reg))
1635 // The condition setting instruction is not just before the conditional
1639 // Be conservative, don't insert instruction above something that may have
1640 // side-effects. And since it's potentially bad to separate flag setting
1641 // instruction from the conditional branch, just abort the optimization
1643 // Also avoid moving code above predicated instruction since it's hard to
1644 // reason about register liveness with predicated instruction.
1645 bool DontMoveAcrossStore = true;
1646 if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(PI))
1650 // Find out what registers are live. Note this routine is ignoring other live
1651 // registers which are only used by instructions in successor blocks.
1652 for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
1653 const MachineOperand &MO = PI->getOperand(i);
1656 unsigned Reg = MO.getReg();
1660 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1663 if (Uses.erase(Reg)) {
1664 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1665 Uses.erase(*SubRegs); // Use sub-registers to be conservative
1667 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1675 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1676 /// sequence at the start of the function, move the instructions before MBB
1677 /// terminator if it's legal.
1678 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1679 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1680 SmallVector<MachineOperand, 4> Cond;
1681 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1684 if (!FBB) FBB = findFalseBlock(MBB, TBB);
1686 // Malformed bcc? True and false blocks are the same?
1689 // Restrict the optimization to cases where MBB is the only predecessor,
1690 // it is an obvious win.
1691 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1694 // Find a suitable position to hoist the common instructions to. Also figure
1695 // out which registers are used or defined by instructions from the insertion
1696 // point to the end of the block.
1697 SmallSet<unsigned, 4> Uses, Defs;
1698 MachineBasicBlock::iterator Loc =
1699 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1700 if (Loc == MBB->end())
1703 bool HasDups = false;
1704 SmallVector<unsigned, 4> LocalDefs;
1705 SmallSet<unsigned, 4> LocalDefsSet;
1706 MachineBasicBlock::iterator TIB = TBB->begin();
1707 MachineBasicBlock::iterator FIB = FBB->begin();
1708 MachineBasicBlock::iterator TIE = TBB->end();
1709 MachineBasicBlock::iterator FIE = FBB->end();
1710 while (TIB != TIE && FIB != FIE) {
1711 // Skip dbg_value instructions. These do not count.
1712 if (TIB->isDebugValue()) {
1713 while (TIB != TIE && TIB->isDebugValue())
1718 if (FIB->isDebugValue()) {
1719 while (FIB != FIE && FIB->isDebugValue())
1724 if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
1727 if (TII->isPredicated(TIB))
1728 // Hard to reason about register liveness with predicated instruction.
1732 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1733 MachineOperand &MO = TIB->getOperand(i);
1734 // Don't attempt to hoist instructions with register masks.
1735 if (MO.isRegMask()) {
1741 unsigned Reg = MO.getReg();
1745 if (Uses.count(Reg)) {
1746 // Avoid clobbering a register that's used by the instruction at
1747 // the point of insertion.
1752 if (Defs.count(Reg) && !MO.isDead()) {
1753 // Don't hoist the instruction if the def would be clobber by the
1754 // instruction at the point insertion. FIXME: This is overly
1755 // conservative. It should be possible to hoist the instructions
1756 // in BB2 in the following example:
1758 // r1, eflag = op1 r2, r3
1767 } else if (!LocalDefsSet.count(Reg)) {
1768 if (Defs.count(Reg)) {
1769 // Use is defined by the instruction at the point of insertion.
1774 if (MO.isKill() && Uses.count(Reg))
1775 // Kills a register that's read by the instruction at the point of
1776 // insertion. Remove the kill marker.
1777 MO.setIsKill(false);
1783 bool DontMoveAcrossStore = true;
1784 if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
1787 // Remove kills from LocalDefsSet, these registers had short live ranges.
1788 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1789 MachineOperand &MO = TIB->getOperand(i);
1790 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1792 unsigned Reg = MO.getReg();
1793 if (!Reg || !LocalDefsSet.count(Reg))
1795 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1796 LocalDefsSet.erase(*AI);
1799 // Track local defs so we can update liveins.
1800 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1801 MachineOperand &MO = TIB->getOperand(i);
1802 if (!MO.isReg() || !MO.isDef() || MO.isDead())
1804 unsigned Reg = MO.getReg();
1807 LocalDefs.push_back(Reg);
1808 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1809 LocalDefsSet.insert(*AI);
1820 MBB->splice(Loc, TBB, TBB->begin(), TIB);
1821 FBB->erase(FBB->begin(), FIB);
1824 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1825 unsigned Def = LocalDefs[i];
1826 if (LocalDefsSet.count(Def)) {
1827 TBB->addLiveIn(Def);
1828 FBB->addLiveIn(Def);