1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // it then removes.
13 //
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
16 // ISA (e.g. NVPTX).
17 //
18 //===----------------------------------------------------------------------===//
19 
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/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include <algorithm>
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "branchfolding"
47 
48 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
49 STATISTIC(NumBranchOpts, "Number of branches optimized");
50 STATISTIC(NumTailMerge , "Number of block tails merged");
51 STATISTIC(NumHoist     , "Number of times common instructions are hoisted");
52 STATISTIC(NumTailCalls,  "Number of tail calls optimized");
53 
54 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
55                               cl::init(cl::BOU_UNSET), cl::Hidden);
56 
57 // Throttle for huge numbers of predecessors (compile speed problems)
58 static cl::opt<unsigned>
59 TailMergeThreshold("tail-merge-threshold",
60           cl::desc("Max number of predecessors to consider tail merging"),
61           cl::init(150), cl::Hidden);
62 
63 // Heuristic for tail merging (and, inversely, tail duplication).
64 // TODO: This should be replaced with a target query.
65 static cl::opt<unsigned>
66 TailMergeSize("tail-merge-size",
67           cl::desc("Min number of instructions to consider tail merging"),
68                               cl::init(3), cl::Hidden);
69 
70 namespace {
71   /// BranchFolderPass - Wrap branch folder in a machine function pass.
72   class BranchFolderPass : public MachineFunctionPass {
73   public:
74     static char ID;
75     explicit BranchFolderPass(): MachineFunctionPass(ID) {}
76 
77     bool runOnMachineFunction(MachineFunction &MF) override;
78 
79     void getAnalysisUsage(AnalysisUsage &AU) const override {
80       AU.addRequired<MachineBlockFrequencyInfo>();
81       AU.addRequired<MachineBranchProbabilityInfo>();
82       AU.addRequired<TargetPassConfig>();
83       MachineFunctionPass::getAnalysisUsage(AU);
84     }
85   };
86 }
87 
88 char BranchFolderPass::ID = 0;
89 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
90 
91 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
92                 "Control Flow Optimizer", false, false)
93 
94 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
95   if (skipFunction(*MF.getFunction()))
96     return false;
97 
98   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
99   // TailMerge can create jump into if branches that make CFG irreducible for
100   // HW that requires structurized CFG.
101   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
102                          PassConfig->getEnableTailMerge();
103   BranchFolder::MBFIWrapper MBBFreqInfo(
104       getAnalysis<MachineBlockFrequencyInfo>());
105   BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
106                       getAnalysis<MachineBranchProbabilityInfo>());
107   return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
108                                  MF.getSubtarget().getRegisterInfo(),
109                                  getAnalysisIfAvailable<MachineModuleInfo>());
110 }
111 
112 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
113                            MBFIWrapper &FreqInfo,
114                            const MachineBranchProbabilityInfo &ProbInfo,
115                            unsigned MinTailLength)
116     : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
117       MBBFreqInfo(FreqInfo), MBPI(ProbInfo) {
118   if (MinCommonTailLength == 0)
119     MinCommonTailLength = TailMergeSize;
120   switch (FlagEnableTailMerge) {
121   case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
122   case cl::BOU_TRUE: EnableTailMerge = true; break;
123   case cl::BOU_FALSE: EnableTailMerge = false; break;
124   }
125 }
126 
127 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
128 /// function, updating the CFG.
129 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
130   assert(MBB->pred_empty() && "MBB must be dead!");
131   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
132 
133   MachineFunction *MF = MBB->getParent();
134   // drop all successors.
135   while (!MBB->succ_empty())
136     MBB->removeSuccessor(MBB->succ_end()-1);
137 
138   // Avoid matching if this pointer gets reused.
139   TriedMerging.erase(MBB);
140 
141   // Remove the block.
142   MF->erase(MBB);
143   FuncletMembership.erase(MBB);
144   if (MLI)
145     MLI->removeBlock(MBB);
146 }
147 
148 /// OptimizeFunction - Perhaps branch folding, tail merging and other
149 /// CFG optimizations on the given function.  Block placement changes the layout
150 /// and may create new tail merging opportunities.
151 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
152                                     const TargetInstrInfo *tii,
153                                     const TargetRegisterInfo *tri,
154                                     MachineModuleInfo *mmi,
155                                     MachineLoopInfo *mli, bool AfterPlacement) {
156   if (!tii) return false;
157 
158   TriedMerging.clear();
159 
160   AfterBlockPlacement = AfterPlacement;
161   TII = tii;
162   TRI = tri;
163   MMI = mmi;
164   MLI = mli;
165 
166   MachineRegisterInfo &MRI = MF.getRegInfo();
167   UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
168   if (!UpdateLiveIns)
169     MRI.invalidateLiveness();
170 
171   // Fix CFG.  The later algorithms expect it to be right.
172   bool MadeChange = false;
173   for (MachineBasicBlock &MBB : MF) {
174     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
175     SmallVector<MachineOperand, 4> Cond;
176     if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true))
177       MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
178   }
179 
180   // Recalculate funclet membership.
181   FuncletMembership = getFuncletMembership(MF);
182 
183   bool MadeChangeThisIteration = true;
184   while (MadeChangeThisIteration) {
185     MadeChangeThisIteration    = TailMergeBlocks(MF);
186     // No need to clean up if tail merging does not change anything after the
187     // block placement.
188     if (!AfterBlockPlacement || MadeChangeThisIteration)
189       MadeChangeThisIteration |= OptimizeBranches(MF);
190     if (EnableHoistCommonCode)
191       MadeChangeThisIteration |= HoistCommonCode(MF);
192     MadeChange |= MadeChangeThisIteration;
193   }
194 
195   // See if any jump tables have become dead as the code generator
196   // did its thing.
197   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
198   if (!JTI)
199     return MadeChange;
200 
201   // Walk the function to find jump tables that are live.
202   BitVector JTIsLive(JTI->getJumpTables().size());
203   for (const MachineBasicBlock &BB : MF) {
204     for (const MachineInstr &I : BB)
205       for (const MachineOperand &Op : I.operands()) {
206         if (!Op.isJTI()) continue;
207 
208         // Remember that this JT is live.
209         JTIsLive.set(Op.getIndex());
210       }
211   }
212 
213   // Finally, remove dead jump tables.  This happens when the
214   // indirect jump was unreachable (and thus deleted).
215   for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
216     if (!JTIsLive.test(i)) {
217       JTI->RemoveJumpTable(i);
218       MadeChange = true;
219     }
220 
221   return MadeChange;
222 }
223 
224 //===----------------------------------------------------------------------===//
225 //  Tail Merging of Blocks
226 //===----------------------------------------------------------------------===//
227 
228 /// HashMachineInstr - Compute a hash value for MI and its operands.
229 static unsigned HashMachineInstr(const MachineInstr &MI) {
230   unsigned Hash = MI.getOpcode();
231   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
232     const MachineOperand &Op = MI.getOperand(i);
233 
234     // Merge in bits from the operand if easy. We can't use MachineOperand's
235     // hash_code here because it's not deterministic and we sort by hash value
236     // later.
237     unsigned OperandHash = 0;
238     switch (Op.getType()) {
239     case MachineOperand::MO_Register:
240       OperandHash = Op.getReg();
241       break;
242     case MachineOperand::MO_Immediate:
243       OperandHash = Op.getImm();
244       break;
245     case MachineOperand::MO_MachineBasicBlock:
246       OperandHash = Op.getMBB()->getNumber();
247       break;
248     case MachineOperand::MO_FrameIndex:
249     case MachineOperand::MO_ConstantPoolIndex:
250     case MachineOperand::MO_JumpTableIndex:
251       OperandHash = Op.getIndex();
252       break;
253     case MachineOperand::MO_GlobalAddress:
254     case MachineOperand::MO_ExternalSymbol:
255       // Global address / external symbol are too hard, don't bother, but do
256       // pull in the offset.
257       OperandHash = Op.getOffset();
258       break;
259     default:
260       break;
261     }
262 
263     Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
264   }
265   return Hash;
266 }
267 
268 /// HashEndOfMBB - Hash the last instruction in the MBB.
269 static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
270   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
271   if (I == MBB.end())
272     return 0;
273 
274   return HashMachineInstr(*I);
275 }
276 
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) {
284   I1 = MBB1->end();
285   I2 = MBB2->end();
286 
287   unsigned TailLen = 0;
288   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
289     --I1; --I2;
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
296             return TailLen;
297           --I2;
298         }
299         ++I2;
300         // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
301         return TailLen;
302       }
303       --I1;
304     }
305     // I1==first (untested) non-DBG preceding known match
306     while (I2->isDebugValue()) {
307       if (I2==MBB2->begin()) {
308         ++I1;
309         // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
310         return TailLen;
311       }
312       --I2;
313     }
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
320         // directives.
321         I1->isInlineAsm()) {
322       ++I1; ++I2;
323       break;
324     }
325     ++TailLen;
326   }
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()) {
332     --I2;
333     while (I2->isDebugValue()) {
334       if (I2 == MBB2->begin())
335         return TailLen;
336       --I2;
337     }
338     ++I2;
339   }
340   if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
341     --I1;
342     while (I1->isDebugValue()) {
343       if (I1 == MBB1->begin())
344         return TailLen;
345       --I1;
346     }
347     ++I1;
348   }
349   return TailLen;
350 }
351 
352 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
353 /// after it, replacing it with an unconditional branch to NewDest.
354 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
355                                            MachineBasicBlock *NewDest) {
356   TII->ReplaceTailWithBranchTo(OldInst, NewDest);
357 
358   if (UpdateLiveIns) {
359     NewDest->clearLiveIns();
360     computeLiveIns(LiveRegs, *TRI, *NewDest);
361   }
362 
363   ++NumTailMerge;
364 }
365 
366 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
367 /// MBB so that the part before the iterator falls into the part starting at the
368 /// iterator.  This returns the new MBB.
369 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
370                                             MachineBasicBlock::iterator BBI1,
371                                             const BasicBlock *BB) {
372   if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
373     return nullptr;
374 
375   MachineFunction &MF = *CurMBB.getParent();
376 
377   // Create the fall-through block.
378   MachineFunction::iterator MBBI = CurMBB.getIterator();
379   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
380   CurMBB.getParent()->insert(++MBBI, NewMBB);
381 
382   // Move all the successors of this block to the specified block.
383   NewMBB->transferSuccessors(&CurMBB);
384 
385   // Add an edge from CurMBB to NewMBB for the fall-through.
386   CurMBB.addSuccessor(NewMBB);
387 
388   // Splice the code over.
389   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
390 
391   // NewMBB belongs to the same loop as CurMBB.
392   if (MLI)
393     if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
394       ML->addBasicBlockToLoop(NewMBB, MLI->getBase());
395 
396   // NewMBB inherits CurMBB's block frequency.
397   MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
398 
399   if (UpdateLiveIns)
400     computeLiveIns(LiveRegs, *TRI, *NewMBB);
401 
402   // Add the new block to the funclet.
403   const auto &FuncletI = FuncletMembership.find(&CurMBB);
404   if (FuncletI != FuncletMembership.end()) {
405     auto n = FuncletI->second;
406     FuncletMembership[NewMBB] = n;
407   }
408 
409   return NewMBB;
410 }
411 
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) {
416   unsigned Time = 0;
417   for (; I != E; ++I) {
418     if (I->isDebugValue())
419       continue;
420     if (I->isCall())
421       Time += 10;
422     else if (I->mayLoad() || I->mayStore())
423       Time += 2;
424     else
425       ++Time;
426   }
427   return Time;
428 }
429 
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 = CurMBB->findBranchDebugLoc();
441   if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
442     MachineBasicBlock *NextBB = &*I;
443     if (TBB == NextBB && !Cond.empty() && !FBB) {
444       if (!TII->reverseBranchCondition(Cond)) {
445         TII->removeBranch(*CurMBB);
446         TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
447         return;
448       }
449     }
450   }
451   TII->insertBranch(*CurMBB, SuccBB, nullptr,
452                     SmallVector<MachineOperand, 0>(), dl);
453 }
454 
455 bool
456 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
457   if (getHash() < o.getHash())
458     return true;
459   if (getHash() > o.getHash())
460     return false;
461   if (getBlock()->getNumber() < o.getBlock()->getNumber())
462     return true;
463   if (getBlock()->getNumber() > o.getBlock()->getNumber())
464     return false;
465   // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
466   // an object with itself.
467 #ifndef _GLIBCXX_DEBUG
468   llvm_unreachable("Predecessor appears twice");
469 #else
470   return false;
471 #endif
472 }
473 
474 BlockFrequency
475 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
476   auto I = MergedBBFreq.find(MBB);
477 
478   if (I != MergedBBFreq.end())
479     return I->second;
480 
481   return MBFI.getBlockFreq(MBB);
482 }
483 
484 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
485                                              BlockFrequency F) {
486   MergedBBFreq[MBB] = F;
487 }
488 
489 raw_ostream &
490 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
491                                           const MachineBasicBlock *MBB) const {
492   return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
493 }
494 
495 raw_ostream &
496 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
497                                           const BlockFrequency Freq) const {
498   return MBFI.printBlockFreq(OS, Freq);
499 }
500 
501 void BranchFolder::MBFIWrapper::view(const Twine &Name, bool isSimple) {
502   MBFI.view(Name, isSimple);
503 }
504 
505 uint64_t
506 BranchFolder::MBFIWrapper::getEntryFreq() const {
507   return MBFI.getEntryFreq();
508 }
509 
510 /// CountTerminators - Count the number of terminators in the given
511 /// block and set I to the position of the first non-terminator, if there
512 /// is one, or MBB->end() otherwise.
513 static unsigned CountTerminators(MachineBasicBlock *MBB,
514                                  MachineBasicBlock::iterator &I) {
515   I = MBB->end();
516   unsigned NumTerms = 0;
517   for (;;) {
518     if (I == MBB->begin()) {
519       I = MBB->end();
520       break;
521     }
522     --I;
523     if (!I->isTerminator()) break;
524     ++NumTerms;
525   }
526   return NumTerms;
527 }
528 
529 /// A no successor, non-return block probably ends in unreachable and is cold.
530 /// Also consider a block that ends in an indirect branch to be a return block,
531 /// since many targets use plain indirect branches to return.
532 static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
533   if (!MBB->succ_empty())
534     return false;
535   if (MBB->empty())
536     return true;
537   return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
538 }
539 
540 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
541 /// and decide if it would be profitable to merge those tails.  Return the
542 /// length of the common tail and iterators to the first common instruction
543 /// in each block.
544 /// MBB1, MBB2      The blocks to check
545 /// MinCommonTailLength  Minimum size of tail block to be merged.
546 /// CommonTailLen   Out parameter to record the size of the shared tail between
547 ///                 MBB1 and MBB2
548 /// I1, I2          Iterator references that will be changed to point to the first
549 ///                 instruction in the common tail shared by MBB1,MBB2
550 /// SuccBB          A common successor of MBB1, MBB2 which are in a canonical form
551 ///                 relative to SuccBB
552 /// PredBB          The layout predecessor of SuccBB, if any.
553 /// FuncletMembership  map from block to funclet #.
554 /// AfterPlacement  True if we are merging blocks after layout. Stricter
555 ///                 thresholds apply to prevent undoing tail-duplication.
556 static bool
557 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
558                   unsigned MinCommonTailLength, unsigned &CommonTailLen,
559                   MachineBasicBlock::iterator &I1,
560                   MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
561                   MachineBasicBlock *PredBB,
562                   DenseMap<const MachineBasicBlock *, int> &FuncletMembership,
563                   bool AfterPlacement) {
564   // It is never profitable to tail-merge blocks from two different funclets.
565   if (!FuncletMembership.empty()) {
566     auto Funclet1 = FuncletMembership.find(MBB1);
567     assert(Funclet1 != FuncletMembership.end());
568     auto Funclet2 = FuncletMembership.find(MBB2);
569     assert(Funclet2 != FuncletMembership.end());
570     if (Funclet1->second != Funclet2->second)
571       return false;
572   }
573 
574   CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
575   if (CommonTailLen == 0)
576     return false;
577   DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
578                << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
579                << '\n');
580 
581   // It's almost always profitable to merge any number of non-terminator
582   // instructions with the block that falls through into the common successor.
583   // This is true only for a single successor. For multiple successors, we are
584   // trading a conditional branch for an unconditional one.
585   // TODO: Re-visit successor size for non-layout tail merging.
586   if ((MBB1 == PredBB || MBB2 == PredBB) &&
587       (!AfterPlacement || MBB1->succ_size() == 1)) {
588     MachineBasicBlock::iterator I;
589     unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
590     if (CommonTailLen > NumTerms)
591       return true;
592   }
593 
594   // If these are identical non-return blocks with no successors, merge them.
595   // Such blocks are typically cold calls to noreturn functions like abort, and
596   // are unlikely to become a fallthrough target after machine block placement.
597   // Tail merging these blocks is unlikely to create additional unconditional
598   // branches, and will reduce the size of this cold code.
599   if (I1 == MBB1->begin() && I2 == MBB2->begin() &&
600       blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2))
601     return true;
602 
603   // If one of the blocks can be completely merged and happens to be in
604   // a position where the other could fall through into it, merge any number
605   // of instructions, because it can be done without a branch.
606   // TODO: If the blocks are not adjacent, move one of them so that they are?
607   if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
608     return true;
609   if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
610     return true;
611 
612   // If both blocks have an unconditional branch temporarily stripped out,
613   // count that as an additional common instruction for the following
614   // heuristics. This heuristic is only accurate for single-succ blocks, so to
615   // make sure that during layout merging and duplicating don't crash, we check
616   // for that when merging during layout.
617   unsigned EffectiveTailLen = CommonTailLen;
618   if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
619       (MBB1->succ_size() == 1 || !AfterPlacement) &&
620       !MBB1->back().isBarrier() &&
621       !MBB2->back().isBarrier())
622     ++EffectiveTailLen;
623 
624   // Check if the common tail is long enough to be worthwhile.
625   if (EffectiveTailLen >= MinCommonTailLength)
626     return true;
627 
628   // If we are optimizing for code size, 2 instructions in common is enough if
629   // we don't have to split a block.  At worst we will be introducing 1 new
630   // branch instruction, which is likely to be smaller than the 2
631   // instructions that would be deleted in the merge.
632   MachineFunction *MF = MBB1->getParent();
633   return EffectiveTailLen >= 2 && MF->getFunction()->optForSize() &&
634          (I1 == MBB1->begin() || I2 == MBB2->begin());
635 }
636 
637 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
638 /// hash CurHash (guaranteed to match the last element).  Build the vector
639 /// SameTails of all those that have the (same) largest number of instructions
640 /// in common of any pair of these blocks.  SameTails entries contain an
641 /// iterator into MergePotentials (from which the MachineBasicBlock can be
642 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
643 /// instruction where the matching code sequence begins.
644 /// Order of elements in SameTails is the reverse of the order in which
645 /// those blocks appear in MergePotentials (where they are not necessarily
646 /// consecutive).
647 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
648                                         unsigned MinCommonTailLength,
649                                         MachineBasicBlock *SuccBB,
650                                         MachineBasicBlock *PredBB) {
651   unsigned maxCommonTailLength = 0U;
652   SameTails.clear();
653   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
654   MPIterator HighestMPIter = std::prev(MergePotentials.end());
655   for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
656                   B = MergePotentials.begin();
657        CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
658     for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
659       unsigned CommonTailLen;
660       if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
661                             MinCommonTailLength,
662                             CommonTailLen, TrialBBI1, TrialBBI2,
663                             SuccBB, PredBB,
664                             FuncletMembership,
665                             AfterBlockPlacement)) {
666         if (CommonTailLen > maxCommonTailLength) {
667           SameTails.clear();
668           maxCommonTailLength = CommonTailLen;
669           HighestMPIter = CurMPIter;
670           SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
671         }
672         if (HighestMPIter == CurMPIter &&
673             CommonTailLen == maxCommonTailLength)
674           SameTails.push_back(SameTailElt(I, TrialBBI2));
675       }
676       if (I == B)
677         break;
678     }
679   }
680   return maxCommonTailLength;
681 }
682 
683 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
684 /// MergePotentials, restoring branches at ends of blocks as appropriate.
685 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
686                                         MachineBasicBlock *SuccBB,
687                                         MachineBasicBlock *PredBB) {
688   MPIterator CurMPIter, B;
689   for (CurMPIter = std::prev(MergePotentials.end()),
690       B = MergePotentials.begin();
691        CurMPIter->getHash() == CurHash; --CurMPIter) {
692     // Put the unconditional branch back, if we need one.
693     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
694     if (SuccBB && CurMBB != PredBB)
695       FixTail(CurMBB, SuccBB, TII);
696     if (CurMPIter == B)
697       break;
698   }
699   if (CurMPIter->getHash() != CurHash)
700     CurMPIter++;
701   MergePotentials.erase(CurMPIter, MergePotentials.end());
702 }
703 
704 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
705 /// only of the common tail.  Create a block that does by splitting one.
706 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
707                                              MachineBasicBlock *SuccBB,
708                                              unsigned maxCommonTailLength,
709                                              unsigned &commonTailIndex) {
710   commonTailIndex = 0;
711   unsigned TimeEstimate = ~0U;
712   for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
713     // Use PredBB if possible; that doesn't require a new branch.
714     if (SameTails[i].getBlock() == PredBB) {
715       commonTailIndex = i;
716       break;
717     }
718     // Otherwise, make a (fairly bogus) choice based on estimate of
719     // how long it will take the various blocks to execute.
720     unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
721                                  SameTails[i].getTailStartPos());
722     if (t <= TimeEstimate) {
723       TimeEstimate = t;
724       commonTailIndex = i;
725     }
726   }
727 
728   MachineBasicBlock::iterator BBI =
729     SameTails[commonTailIndex].getTailStartPos();
730   MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
731 
732   DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
733                << maxCommonTailLength);
734 
735   // If the split block unconditionally falls-thru to SuccBB, it will be
736   // merged. In control flow terms it should then take SuccBB's name. e.g. If
737   // SuccBB is an inner loop, the common tail is still part of the inner loop.
738   const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
739     SuccBB->getBasicBlock() : MBB->getBasicBlock();
740   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
741   if (!newMBB) {
742     DEBUG(dbgs() << "... failed!");
743     return false;
744   }
745 
746   SameTails[commonTailIndex].setBlock(newMBB);
747   SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
748 
749   // If we split PredBB, newMBB is the new predecessor.
750   if (PredBB == MBB)
751     PredBB = newMBB;
752 
753   return true;
754 }
755 
756 static void
757 mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
758                 MachineBasicBlock &MBBCommon) {
759   MachineBasicBlock *MBB = MBBIStartPos->getParent();
760   // Note CommonTailLen does not necessarily matches the size of
761   // the common BB nor all its instructions because of debug
762   // instructions differences.
763   unsigned CommonTailLen = 0;
764   for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
765     ++CommonTailLen;
766 
767   MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
768   MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
769   MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
770   MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
771 
772   while (CommonTailLen--) {
773     assert(MBBI != MBBIE && "Reached BB end within common tail length!");
774     (void)MBBIE;
775 
776     if (MBBI->isDebugValue()) {
777       ++MBBI;
778       continue;
779     }
780 
781     while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
782       ++MBBICommon;
783 
784     assert(MBBICommon != MBBIECommon &&
785            "Reached BB end within common tail length!");
786     assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
787 
788     // Merge MMOs from memory operations in the common block.
789     if (MBBICommon->mayLoad() || MBBICommon->mayStore())
790       MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI));
791     // Drop undef flags if they aren't present in all merged instructions.
792     for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
793       MachineOperand &MO = MBBICommon->getOperand(I);
794       if (MO.isReg() && MO.isUndef()) {
795         const MachineOperand &OtherMO = MBBI->getOperand(I);
796         if (!OtherMO.isUndef())
797           MO.setIsUndef(false);
798       }
799     }
800 
801     ++MBBI;
802     ++MBBICommon;
803   }
804 }
805 
806 // See if any of the blocks in MergePotentials (which all have SuccBB as a
807 // successor, or all have no successor if it is null) can be tail-merged.
808 // If there is a successor, any blocks in MergePotentials that are not
809 // tail-merged and are not immediately before Succ must have an unconditional
810 // branch to Succ added (but the predecessor/successor lists need no
811 // adjustment). The lone predecessor of Succ that falls through into Succ,
812 // if any, is given in PredBB.
813 // MinCommonTailLength - Except for the special cases below, tail-merge if
814 // there are at least this many instructions in common.
815 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
816                                       MachineBasicBlock *PredBB,
817                                       unsigned MinCommonTailLength) {
818   bool MadeChange = false;
819 
820   DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
821         for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
822           dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
823                  << (i == e-1 ? "" : ", ");
824         dbgs() << "\n";
825         if (SuccBB) {
826           dbgs() << "  with successor BB#" << SuccBB->getNumber() << '\n';
827           if (PredBB)
828             dbgs() << "  which has fall-through from BB#"
829                    << PredBB->getNumber() << "\n";
830         }
831         dbgs() << "Looking for common tails of at least "
832                << MinCommonTailLength << " instruction"
833                << (MinCommonTailLength == 1 ? "" : "s") << '\n';
834        );
835 
836   // Sort by hash value so that blocks with identical end sequences sort
837   // together.
838   array_pod_sort(MergePotentials.begin(), MergePotentials.end());
839 
840   // Walk through equivalence sets looking for actual exact matches.
841   while (MergePotentials.size() > 1) {
842     unsigned CurHash = MergePotentials.back().getHash();
843 
844     // Build SameTails, identifying the set of blocks with this hash code
845     // and with the maximum number of instructions in common.
846     unsigned maxCommonTailLength = ComputeSameTails(CurHash,
847                                                     MinCommonTailLength,
848                                                     SuccBB, PredBB);
849 
850     // If we didn't find any pair that has at least MinCommonTailLength
851     // instructions in common, remove all blocks with this hash code and retry.
852     if (SameTails.empty()) {
853       RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
854       continue;
855     }
856 
857     // If one of the blocks is the entire common tail (and not the entry
858     // block, which we can't jump to), we can treat all blocks with this same
859     // tail at once.  Use PredBB if that is one of the possibilities, as that
860     // will not introduce any extra branches.
861     MachineBasicBlock *EntryBB =
862         &MergePotentials.front().getBlock()->getParent()->front();
863     unsigned commonTailIndex = SameTails.size();
864     // If there are two blocks, check to see if one can be made to fall through
865     // into the other.
866     if (SameTails.size() == 2 &&
867         SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
868         SameTails[1].tailIsWholeBlock())
869       commonTailIndex = 1;
870     else if (SameTails.size() == 2 &&
871              SameTails[1].getBlock()->isLayoutSuccessor(
872                                                      SameTails[0].getBlock()) &&
873              SameTails[0].tailIsWholeBlock())
874       commonTailIndex = 0;
875     else {
876       // Otherwise just pick one, favoring the fall-through predecessor if
877       // there is one.
878       for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
879         MachineBasicBlock *MBB = SameTails[i].getBlock();
880         if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
881           continue;
882         if (MBB == PredBB) {
883           commonTailIndex = i;
884           break;
885         }
886         if (SameTails[i].tailIsWholeBlock())
887           commonTailIndex = i;
888       }
889     }
890 
891     if (commonTailIndex == SameTails.size() ||
892         (SameTails[commonTailIndex].getBlock() == PredBB &&
893          !SameTails[commonTailIndex].tailIsWholeBlock())) {
894       // None of the blocks consist entirely of the common tail.
895       // Split a block so that one does.
896       if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
897                                      maxCommonTailLength, commonTailIndex)) {
898         RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
899         continue;
900       }
901     }
902 
903     MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
904 
905     // Recompute common tail MBB's edge weights and block frequency.
906     setCommonTailEdgeWeights(*MBB);
907 
908     // Remove the original debug location from the common tail.
909     for (auto &MI : *MBB)
910       if (!MI.isDebugValue())
911         MI.setDebugLoc(DebugLoc());
912 
913     // MBB is common tail.  Adjust all other BB's to jump to this one.
914     // Traversal must be forwards so erases work.
915     DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
916                  << " for ");
917     for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
918       if (commonTailIndex == i)
919         continue;
920       DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
921                    << (i == e-1 ? "" : ", "));
922       // Merge operations (MMOs, undef flags)
923       mergeOperations(SameTails[i].getTailStartPos(), *MBB);
924       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
925       ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
926       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
927       MergePotentials.erase(SameTails[i].getMPIter());
928     }
929     DEBUG(dbgs() << "\n");
930     // We leave commonTailIndex in the worklist in case there are other blocks
931     // that match it with a smaller number of instructions.
932     MadeChange = true;
933   }
934   return MadeChange;
935 }
936 
937 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
938   bool MadeChange = false;
939   if (!EnableTailMerge) return MadeChange;
940 
941   // First find blocks with no successors.
942   // Block placement does not create new tail merging opportunities for these
943   // blocks.
944   if (!AfterBlockPlacement) {
945     MergePotentials.clear();
946     for (MachineBasicBlock &MBB : MF) {
947       if (MergePotentials.size() == TailMergeThreshold)
948         break;
949       if (!TriedMerging.count(&MBB) && MBB.succ_empty())
950         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
951     }
952 
953     // If this is a large problem, avoid visiting the same basic blocks
954     // multiple times.
955     if (MergePotentials.size() == TailMergeThreshold)
956       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
957         TriedMerging.insert(MergePotentials[i].getBlock());
958 
959     // See if we can do any tail merging on those.
960     if (MergePotentials.size() >= 2)
961       MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
962   }
963 
964   // Look at blocks (IBB) with multiple predecessors (PBB).
965   // We change each predecessor to a canonical form, by
966   // (1) temporarily removing any unconditional branch from the predecessor
967   // to IBB, and
968   // (2) alter conditional branches so they branch to the other block
969   // not IBB; this may require adding back an unconditional branch to IBB
970   // later, where there wasn't one coming in.  E.g.
971   //   Bcc IBB
972   //   fallthrough to QBB
973   // here becomes
974   //   Bncc QBB
975   // with a conceptual B to IBB after that, which never actually exists.
976   // With those changes, we see whether the predecessors' tails match,
977   // and merge them if so.  We change things out of canonical form and
978   // back to the way they were later in the process.  (OptimizeBranches
979   // would undo some of this, but we can't use it, because we'd get into
980   // a compile-time infinite loop repeatedly doing and undoing the same
981   // transformations.)
982 
983   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
984        I != E; ++I) {
985     if (I->pred_size() < 2) continue;
986     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
987     MachineBasicBlock *IBB = &*I;
988     MachineBasicBlock *PredBB = &*std::prev(I);
989     MergePotentials.clear();
990     MachineLoop *ML;
991 
992     // Bail if merging after placement and IBB is the loop header because
993     // -- If merging predecessors that belong to the same loop as IBB, the
994     // common tail of merged predecessors may become the loop top if block
995     // placement is called again and the predecessors may branch to this common
996     // tail and require more branches. This can be relaxed if
997     // MachineBlockPlacement::findBestLoopTop is more flexible.
998     // --If merging predecessors that do not belong to the same loop as IBB, the
999     // loop info of IBB's loop and the other loops may be affected. Calling the
1000     // block placement again may make big change to the layout and eliminate the
1001     // reason to do tail merging here.
1002     if (AfterBlockPlacement && MLI) {
1003       ML = MLI->getLoopFor(IBB);
1004       if (ML && IBB == ML->getHeader())
1005         continue;
1006     }
1007 
1008     for (MachineBasicBlock *PBB : I->predecessors()) {
1009       if (MergePotentials.size() == TailMergeThreshold)
1010         break;
1011 
1012       if (TriedMerging.count(PBB))
1013         continue;
1014 
1015       // Skip blocks that loop to themselves, can't tail merge these.
1016       if (PBB == IBB)
1017         continue;
1018 
1019       // Visit each predecessor only once.
1020       if (!UniquePreds.insert(PBB).second)
1021         continue;
1022 
1023       // Skip blocks which may jump to a landing pad. Can't tail merge these.
1024       if (PBB->hasEHPadSuccessor())
1025         continue;
1026 
1027       // After block placement, only consider predecessors that belong to the
1028       // same loop as IBB.  The reason is the same as above when skipping loop
1029       // header.
1030       if (AfterBlockPlacement && MLI)
1031         if (ML != MLI->getLoopFor(PBB))
1032           continue;
1033 
1034       MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1035       SmallVector<MachineOperand, 4> Cond;
1036       if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1037         // Failing case: IBB is the target of a cbr, and we cannot reverse the
1038         // branch.
1039         SmallVector<MachineOperand, 4> NewCond(Cond);
1040         if (!Cond.empty() && TBB == IBB) {
1041           if (TII->reverseBranchCondition(NewCond))
1042             continue;
1043           // This is the QBB case described above
1044           if (!FBB) {
1045             auto Next = ++PBB->getIterator();
1046             if (Next != MF.end())
1047               FBB = &*Next;
1048           }
1049         }
1050 
1051         // Failing case: the only way IBB can be reached from PBB is via
1052         // exception handling.  Happens for landing pads.  Would be nice to have
1053         // a bit in the edge so we didn't have to do all this.
1054         if (IBB->isEHPad()) {
1055           MachineFunction::iterator IP = ++PBB->getIterator();
1056           MachineBasicBlock *PredNextBB = nullptr;
1057           if (IP != MF.end())
1058             PredNextBB = &*IP;
1059           if (!TBB) {
1060             if (IBB != PredNextBB)      // fallthrough
1061               continue;
1062           } else if (FBB) {
1063             if (TBB != IBB && FBB != IBB)   // cbr then ubr
1064               continue;
1065           } else if (Cond.empty()) {
1066             if (TBB != IBB)               // ubr
1067               continue;
1068           } else {
1069             if (TBB != IBB && IBB != PredNextBB)  // cbr
1070               continue;
1071           }
1072         }
1073 
1074         // Remove the unconditional branch at the end, if any.
1075         if (TBB && (Cond.empty() || FBB)) {
1076           DebugLoc dl = PBB->findBranchDebugLoc();
1077           TII->removeBranch(*PBB);
1078           if (!Cond.empty())
1079             // reinsert conditional branch only, for now
1080             TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1081                               NewCond, dl);
1082         }
1083 
1084         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
1085       }
1086     }
1087 
1088     // If this is a large problem, avoid visiting the same basic blocks multiple
1089     // times.
1090     if (MergePotentials.size() == TailMergeThreshold)
1091       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1092         TriedMerging.insert(MergePotentials[i].getBlock());
1093 
1094     if (MergePotentials.size() >= 2)
1095       MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1096 
1097     // Reinsert an unconditional branch if needed. The 1 below can occur as a
1098     // result of removing blocks in TryTailMergeBlocks.
1099     PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
1100     if (MergePotentials.size() == 1 &&
1101         MergePotentials.begin()->getBlock() != PredBB)
1102       FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1103   }
1104 
1105   return MadeChange;
1106 }
1107 
1108 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1109   SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1110   BlockFrequency AccumulatedMBBFreq;
1111 
1112   // Aggregate edge frequency of successor edge j:
1113   //  edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1114   //  where bb is a basic block that is in SameTails.
1115   for (const auto &Src : SameTails) {
1116     const MachineBasicBlock *SrcMBB = Src.getBlock();
1117     BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1118     AccumulatedMBBFreq += BlockFreq;
1119 
1120     // It is not necessary to recompute edge weights if TailBB has less than two
1121     // successors.
1122     if (TailMBB.succ_size() <= 1)
1123       continue;
1124 
1125     auto EdgeFreq = EdgeFreqLs.begin();
1126 
1127     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1128          SuccI != SuccE; ++SuccI, ++EdgeFreq)
1129       *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1130   }
1131 
1132   MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1133 
1134   if (TailMBB.succ_size() <= 1)
1135     return;
1136 
1137   auto SumEdgeFreq =
1138       std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1139           .getFrequency();
1140   auto EdgeFreq = EdgeFreqLs.begin();
1141 
1142   if (SumEdgeFreq > 0) {
1143     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1144          SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1145       auto Prob = BranchProbability::getBranchProbability(
1146           EdgeFreq->getFrequency(), SumEdgeFreq);
1147       TailMBB.setSuccProbability(SuccI, Prob);
1148     }
1149   }
1150 }
1151 
1152 //===----------------------------------------------------------------------===//
1153 //  Branch Optimization
1154 //===----------------------------------------------------------------------===//
1155 
1156 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1157   bool MadeChange = false;
1158 
1159   // Make sure blocks are numbered in order
1160   MF.RenumberBlocks();
1161   // Renumbering blocks alters funclet membership, recalculate it.
1162   FuncletMembership = getFuncletMembership(MF);
1163 
1164   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1165        I != E; ) {
1166     MachineBasicBlock *MBB = &*I++;
1167     MadeChange |= OptimizeBlock(MBB);
1168 
1169     // If it is dead, remove it.
1170     if (MBB->pred_empty()) {
1171       RemoveDeadBlock(MBB);
1172       MadeChange = true;
1173       ++NumDeadBlocks;
1174     }
1175   }
1176 
1177   return MadeChange;
1178 }
1179 
1180 // Blocks should be considered empty if they contain only debug info;
1181 // else the debug info would affect codegen.
1182 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1183   return MBB->getFirstNonDebugInstr() == MBB->end();
1184 }
1185 
1186 // Blocks with only debug info and branches should be considered the same
1187 // as blocks with only branches.
1188 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1189   MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1190   assert(I != MBB->end() && "empty block!");
1191   return I->isBranch();
1192 }
1193 
1194 /// IsBetterFallthrough - Return true if it would be clearly better to
1195 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
1196 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1197 /// result in infinite loops.
1198 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1199                                 MachineBasicBlock *MBB2) {
1200   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
1201   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
1202   // optimize branches that branch to either a return block or an assert block
1203   // into a fallthrough to the return.
1204   MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1205   MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1206   if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1207     return false;
1208 
1209   // If there is a clear successor ordering we make sure that one block
1210   // will fall through to the next
1211   if (MBB1->isSuccessor(MBB2)) return true;
1212   if (MBB2->isSuccessor(MBB1)) return false;
1213 
1214   return MBB2I->isCall() && !MBB1I->isCall();
1215 }
1216 
1217 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1218 /// instructions on the block.
1219 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1220   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1221   if (I != MBB.end() && I->isBranch())
1222     return I->getDebugLoc();
1223   return DebugLoc();
1224 }
1225 
1226 /// OptimizeBlock - Analyze and optimize control flow related to the specified
1227 /// block.  This is never called on the entry block.
1228 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1229   bool MadeChange = false;
1230   MachineFunction &MF = *MBB->getParent();
1231 ReoptimizeBlock:
1232 
1233   MachineFunction::iterator FallThrough = MBB->getIterator();
1234   ++FallThrough;
1235 
1236   // Make sure MBB and FallThrough belong to the same funclet.
1237   bool SameFunclet = true;
1238   if (!FuncletMembership.empty() && FallThrough != MF.end()) {
1239     auto MBBFunclet = FuncletMembership.find(MBB);
1240     assert(MBBFunclet != FuncletMembership.end());
1241     auto FallThroughFunclet = FuncletMembership.find(&*FallThrough);
1242     assert(FallThroughFunclet != FuncletMembership.end());
1243     SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1244   }
1245 
1246   // If this block is empty, make everyone use its fall-through, not the block
1247   // explicitly.  Landing pads should not do this since the landing-pad table
1248   // points to this block.  Blocks with their addresses taken shouldn't be
1249   // optimized away.
1250   if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1251       SameFunclet) {
1252     // Dead block?  Leave for cleanup later.
1253     if (MBB->pred_empty()) return MadeChange;
1254 
1255     if (FallThrough == MF.end()) {
1256       // TODO: Simplify preds to not branch here if possible!
1257     } else if (FallThrough->isEHPad()) {
1258       // Don't rewrite to a landing pad fallthough.  That could lead to the case
1259       // where a BB jumps to more than one landing pad.
1260       // TODO: Is it ever worth rewriting predecessors which don't already
1261       // jump to a landing pad, and so can safely jump to the fallthrough?
1262     } else if (MBB->isSuccessor(&*FallThrough)) {
1263       // Rewrite all predecessors of the old block to go to the fallthrough
1264       // instead.
1265       while (!MBB->pred_empty()) {
1266         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1267         Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
1268       }
1269       // If MBB was the target of a jump table, update jump tables to go to the
1270       // fallthrough instead.
1271       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1272         MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1273       MadeChange = true;
1274     }
1275     return MadeChange;
1276   }
1277 
1278   // Check to see if we can simplify the terminator of the block before this
1279   // one.
1280   MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1281 
1282   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1283   SmallVector<MachineOperand, 4> PriorCond;
1284   bool PriorUnAnalyzable =
1285       TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1286   if (!PriorUnAnalyzable) {
1287     // If the CFG for the prior block has extra edges, remove them.
1288     MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1289                                               !PriorCond.empty());
1290 
1291     // If the previous branch is conditional and both conditions go to the same
1292     // destination, remove the branch, replacing it with an unconditional one or
1293     // a fall-through.
1294     if (PriorTBB && PriorTBB == PriorFBB) {
1295       DebugLoc dl = getBranchDebugLoc(PrevBB);
1296       TII->removeBranch(PrevBB);
1297       PriorCond.clear();
1298       if (PriorTBB != MBB)
1299         TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1300       MadeChange = true;
1301       ++NumBranchOpts;
1302       goto ReoptimizeBlock;
1303     }
1304 
1305     // If the previous block unconditionally falls through to this block and
1306     // this block has no other predecessors, move the contents of this block
1307     // into the prior block. This doesn't usually happen when SimplifyCFG
1308     // has been used, but it can happen if tail merging splits a fall-through
1309     // predecessor of a block.
1310     // This has to check PrevBB->succ_size() because EH edges are ignored by
1311     // AnalyzeBranch.
1312     if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1313         PrevBB.succ_size() == 1 &&
1314         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1315       DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1316                    << "From MBB: " << *MBB);
1317       // Remove redundant DBG_VALUEs first.
1318       if (PrevBB.begin() != PrevBB.end()) {
1319         MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1320         --PrevBBIter;
1321         MachineBasicBlock::iterator MBBIter = MBB->begin();
1322         // Check if DBG_VALUE at the end of PrevBB is identical to the
1323         // DBG_VALUE at the beginning of MBB.
1324         while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1325                && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1326           if (!MBBIter->isIdenticalTo(*PrevBBIter))
1327             break;
1328           MachineInstr &DuplicateDbg = *MBBIter;
1329           ++MBBIter; -- PrevBBIter;
1330           DuplicateDbg.eraseFromParent();
1331         }
1332       }
1333       PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1334       PrevBB.removeSuccessor(PrevBB.succ_begin());
1335       assert(PrevBB.succ_empty());
1336       PrevBB.transferSuccessors(MBB);
1337       MadeChange = true;
1338       return MadeChange;
1339     }
1340 
1341     // If the previous branch *only* branches to *this* block (conditional or
1342     // not) remove the branch.
1343     if (PriorTBB == MBB && !PriorFBB) {
1344       TII->removeBranch(PrevBB);
1345       MadeChange = true;
1346       ++NumBranchOpts;
1347       goto ReoptimizeBlock;
1348     }
1349 
1350     // If the prior block branches somewhere else on the condition and here if
1351     // the condition is false, remove the uncond second branch.
1352     if (PriorFBB == MBB) {
1353       DebugLoc dl = getBranchDebugLoc(PrevBB);
1354       TII->removeBranch(PrevBB);
1355       TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1356       MadeChange = true;
1357       ++NumBranchOpts;
1358       goto ReoptimizeBlock;
1359     }
1360 
1361     // If the prior block branches here on true and somewhere else on false, and
1362     // if the branch condition is reversible, reverse the branch to create a
1363     // fall-through.
1364     if (PriorTBB == MBB) {
1365       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1366       if (!TII->reverseBranchCondition(NewPriorCond)) {
1367         DebugLoc dl = getBranchDebugLoc(PrevBB);
1368         TII->removeBranch(PrevBB);
1369         TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1370         MadeChange = true;
1371         ++NumBranchOpts;
1372         goto ReoptimizeBlock;
1373       }
1374     }
1375 
1376     // If this block has no successors (e.g. it is a return block or ends with
1377     // a call to a no-return function like abort or __cxa_throw) and if the pred
1378     // falls through into this block, and if it would otherwise fall through
1379     // into the block after this, move this block to the end of the function.
1380     //
1381     // We consider it more likely that execution will stay in the function (e.g.
1382     // due to loops) than it is to exit it.  This asserts in loops etc, moving
1383     // the assert condition out of the loop body.
1384     if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1385         MachineFunction::iterator(PriorTBB) == FallThrough &&
1386         !MBB->canFallThrough()) {
1387       bool DoTransform = true;
1388 
1389       // We have to be careful that the succs of PredBB aren't both no-successor
1390       // blocks.  If neither have successors and if PredBB is the second from
1391       // last block in the function, we'd just keep swapping the two blocks for
1392       // last.  Only do the swap if one is clearly better to fall through than
1393       // the other.
1394       if (FallThrough == --MF.end() &&
1395           !IsBetterFallthrough(PriorTBB, MBB))
1396         DoTransform = false;
1397 
1398       if (DoTransform) {
1399         // Reverse the branch so we will fall through on the previous true cond.
1400         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1401         if (!TII->reverseBranchCondition(NewPriorCond)) {
1402           DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1403                        << "To make fallthrough to: " << *PriorTBB << "\n");
1404 
1405           DebugLoc dl = getBranchDebugLoc(PrevBB);
1406           TII->removeBranch(PrevBB);
1407           TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1408 
1409           // Move this block to the end of the function.
1410           MBB->moveAfter(&MF.back());
1411           MadeChange = true;
1412           ++NumBranchOpts;
1413           return MadeChange;
1414         }
1415       }
1416     }
1417   }
1418 
1419   if (!IsEmptyBlock(MBB) && MBB->pred_size() == 1 &&
1420       MF.getFunction()->optForSize()) {
1421     // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch
1422     // direction, thereby defeating careful block placement and regressing
1423     // performance. Therefore, only consider this for optsize functions.
1424     MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
1425     if (TII->isUnconditionalTailCall(TailCall)) {
1426       MachineBasicBlock *Pred = *MBB->pred_begin();
1427       MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1428       SmallVector<MachineOperand, 4> PredCond;
1429       bool PredAnalyzable =
1430           !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
1431 
1432       if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB) {
1433         // The predecessor has a conditional branch to this block which consists
1434         // of only a tail call. Try to fold the tail call into the conditional
1435         // branch.
1436         if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
1437           // TODO: It would be nice if analyzeBranch() could provide a pointer
1438           // to the branch insturction so replaceBranchWithTailCall() doesn't
1439           // have to search for it.
1440           TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
1441           ++NumTailCalls;
1442           Pred->removeSuccessor(MBB);
1443           MadeChange = true;
1444           return MadeChange;
1445         }
1446       }
1447       // If the predecessor is falling through to this block, we could reverse
1448       // the branch condition and fold the tail call into that. However, after
1449       // that we might have to re-arrange the CFG to fall through to the other
1450       // block and there is a high risk of regressing code size rather than
1451       // improving it.
1452     }
1453   }
1454 
1455   // Analyze the branch in the current block.
1456   MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1457   SmallVector<MachineOperand, 4> CurCond;
1458   bool CurUnAnalyzable =
1459       TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1460   if (!CurUnAnalyzable) {
1461     // If the CFG for the prior block has extra edges, remove them.
1462     MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1463 
1464     // If this is a two-way branch, and the FBB branches to this block, reverse
1465     // the condition so the single-basic-block loop is faster.  Instead of:
1466     //    Loop: xxx; jcc Out; jmp Loop
1467     // we want:
1468     //    Loop: xxx; jncc Loop; jmp Out
1469     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1470       SmallVector<MachineOperand, 4> NewCond(CurCond);
1471       if (!TII->reverseBranchCondition(NewCond)) {
1472         DebugLoc dl = getBranchDebugLoc(*MBB);
1473         TII->removeBranch(*MBB);
1474         TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1475         MadeChange = true;
1476         ++NumBranchOpts;
1477         goto ReoptimizeBlock;
1478       }
1479     }
1480 
1481     // If this branch is the only thing in its block, see if we can forward
1482     // other blocks across it.
1483     if (CurTBB && CurCond.empty() && !CurFBB &&
1484         IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1485         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1486       DebugLoc dl = getBranchDebugLoc(*MBB);
1487       // This block may contain just an unconditional branch.  Because there can
1488       // be 'non-branch terminators' in the block, try removing the branch and
1489       // then seeing if the block is empty.
1490       TII->removeBranch(*MBB);
1491       // If the only things remaining in the block are debug info, remove these
1492       // as well, so this will behave the same as an empty block in non-debug
1493       // mode.
1494       if (IsEmptyBlock(MBB)) {
1495         // Make the block empty, losing the debug info (we could probably
1496         // improve this in some cases.)
1497         MBB->erase(MBB->begin(), MBB->end());
1498       }
1499       // If this block is just an unconditional branch to CurTBB, we can
1500       // usually completely eliminate the block.  The only case we cannot
1501       // completely eliminate the block is when the block before this one
1502       // falls through into MBB and we can't understand the prior block's branch
1503       // condition.
1504       if (MBB->empty()) {
1505         bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1506         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1507             !PrevBB.isSuccessor(MBB)) {
1508           // If the prior block falls through into us, turn it into an
1509           // explicit branch to us to make updates simpler.
1510           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1511               PriorTBB != MBB && PriorFBB != MBB) {
1512             if (!PriorTBB) {
1513               assert(PriorCond.empty() && !PriorFBB &&
1514                      "Bad branch analysis");
1515               PriorTBB = MBB;
1516             } else {
1517               assert(!PriorFBB && "Machine CFG out of date!");
1518               PriorFBB = MBB;
1519             }
1520             DebugLoc pdl = getBranchDebugLoc(PrevBB);
1521             TII->removeBranch(PrevBB);
1522             TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1523           }
1524 
1525           // Iterate through all the predecessors, revectoring each in-turn.
1526           size_t PI = 0;
1527           bool DidChange = false;
1528           bool HasBranchToSelf = false;
1529           while(PI != MBB->pred_size()) {
1530             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1531             if (PMBB == MBB) {
1532               // If this block has an uncond branch to itself, leave it.
1533               ++PI;
1534               HasBranchToSelf = true;
1535             } else {
1536               DidChange = true;
1537               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1538               // If this change resulted in PMBB ending in a conditional
1539               // branch where both conditions go to the same destination,
1540               // change this to an unconditional branch (and fix the CFG).
1541               MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1542               SmallVector<MachineOperand, 4> NewCurCond;
1543               bool NewCurUnAnalyzable = TII->analyzeBranch(
1544                   *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
1545               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1546                 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1547                 TII->removeBranch(*PMBB);
1548                 NewCurCond.clear();
1549                 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1550                 MadeChange = true;
1551                 ++NumBranchOpts;
1552                 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1553               }
1554             }
1555           }
1556 
1557           // Change any jumptables to go to the new MBB.
1558           if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1559             MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1560           if (DidChange) {
1561             ++NumBranchOpts;
1562             MadeChange = true;
1563             if (!HasBranchToSelf) return MadeChange;
1564           }
1565         }
1566       }
1567 
1568       // Add the branch back if the block is more than just an uncond branch.
1569       TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1570     }
1571   }
1572 
1573   // If the prior block doesn't fall through into this block, and if this
1574   // block doesn't fall through into some other block, see if we can find a
1575   // place to move this block where a fall-through will happen.
1576   if (!PrevBB.canFallThrough()) {
1577 
1578     // Now we know that there was no fall-through into this block, check to
1579     // see if it has a fall-through into its successor.
1580     bool CurFallsThru = MBB->canFallThrough();
1581 
1582     if (!MBB->isEHPad()) {
1583       // Check all the predecessors of this block.  If one of them has no fall
1584       // throughs, move this block right after it.
1585       for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1586         // Analyze the branch at the end of the pred.
1587         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1588         SmallVector<MachineOperand, 4> PredCond;
1589         if (PredBB != MBB && !PredBB->canFallThrough() &&
1590             !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
1591             (!CurFallsThru || !CurTBB || !CurFBB) &&
1592             (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1593           // If the current block doesn't fall through, just move it.
1594           // If the current block can fall through and does not end with a
1595           // conditional branch, we need to append an unconditional jump to
1596           // the (current) next block.  To avoid a possible compile-time
1597           // infinite loop, move blocks only backward in this case.
1598           // Also, if there are already 2 branches here, we cannot add a third;
1599           // this means we have the case
1600           // Bcc next
1601           // B elsewhere
1602           // next:
1603           if (CurFallsThru) {
1604             MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
1605             CurCond.clear();
1606             TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1607           }
1608           MBB->moveAfter(PredBB);
1609           MadeChange = true;
1610           goto ReoptimizeBlock;
1611         }
1612       }
1613     }
1614 
1615     if (!CurFallsThru) {
1616       // Check all successors to see if we can move this block before it.
1617       for (MachineBasicBlock *SuccBB : MBB->successors()) {
1618         // Analyze the branch at the end of the block before the succ.
1619         MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1620 
1621         // If this block doesn't already fall-through to that successor, and if
1622         // the succ doesn't already have a block that can fall through into it,
1623         // and if the successor isn't an EH destination, we can arrange for the
1624         // fallthrough to happen.
1625         if (SuccBB != MBB && &*SuccPrev != MBB &&
1626             !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1627             !SuccBB->isEHPad()) {
1628           MBB->moveBefore(SuccBB);
1629           MadeChange = true;
1630           goto ReoptimizeBlock;
1631         }
1632       }
1633 
1634       // Okay, there is no really great place to put this block.  If, however,
1635       // the block before this one would be a fall-through if this block were
1636       // removed, move this block to the end of the function. There is no real
1637       // advantage in "falling through" to an EH block, so we don't want to
1638       // perform this transformation for that case.
1639       //
1640       // Also, Windows EH introduced the possibility of an arbitrary number of
1641       // successors to a given block.  The analyzeBranch call does not consider
1642       // exception handling and so we can get in a state where a block
1643       // containing a call is followed by multiple EH blocks that would be
1644       // rotated infinitely at the end of the function if the transformation
1645       // below were performed for EH "FallThrough" blocks.  Therefore, even if
1646       // that appears not to be happening anymore, we should assume that it is
1647       // possible and not remove the "!FallThrough()->isEHPad" condition below.
1648       MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1649       SmallVector<MachineOperand, 4> PrevCond;
1650       if (FallThrough != MF.end() &&
1651           !FallThrough->isEHPad() &&
1652           !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1653           PrevBB.isSuccessor(&*FallThrough)) {
1654         MBB->moveAfter(&MF.back());
1655         MadeChange = true;
1656         return MadeChange;
1657       }
1658     }
1659   }
1660 
1661   return MadeChange;
1662 }
1663 
1664 //===----------------------------------------------------------------------===//
1665 //  Hoist Common Code
1666 //===----------------------------------------------------------------------===//
1667 
1668 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1669 /// blocks to their common predecessor.
1670 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1671   bool MadeChange = false;
1672   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1673     MachineBasicBlock *MBB = &*I++;
1674     MadeChange |= HoistCommonCodeInSuccs(MBB);
1675   }
1676 
1677   return MadeChange;
1678 }
1679 
1680 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1681 /// its 'true' successor.
1682 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1683                                          MachineBasicBlock *TrueBB) {
1684   for (MachineBasicBlock *SuccBB : BB->successors())
1685     if (SuccBB != TrueBB)
1686       return SuccBB;
1687   return nullptr;
1688 }
1689 
1690 template <class Container>
1691 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1692                                 Container &Set) {
1693   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1694     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1695       Set.insert(*AI);
1696   } else {
1697     Set.insert(Reg);
1698   }
1699 }
1700 
1701 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1702 /// in successors to. The location is usually just before the terminator,
1703 /// however if the terminator is a conditional branch and its previous
1704 /// instruction is the flag setting instruction, the previous instruction is
1705 /// the preferred location. This function also gathers uses and defs of the
1706 /// instructions from the insertion point to the end of the block. The data is
1707 /// used by HoistCommonCodeInSuccs to ensure safety.
1708 static
1709 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1710                                                   const TargetInstrInfo *TII,
1711                                                   const TargetRegisterInfo *TRI,
1712                                                   SmallSet<unsigned,4> &Uses,
1713                                                   SmallSet<unsigned,4> &Defs) {
1714   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1715   if (!TII->isUnpredicatedTerminator(*Loc))
1716     return MBB->end();
1717 
1718   for (const MachineOperand &MO : Loc->operands()) {
1719     if (!MO.isReg())
1720       continue;
1721     unsigned Reg = MO.getReg();
1722     if (!Reg)
1723       continue;
1724     if (MO.isUse()) {
1725       addRegAndItsAliases(Reg, TRI, Uses);
1726     } else {
1727       if (!MO.isDead())
1728         // Don't try to hoist code in the rare case the terminator defines a
1729         // register that is later used.
1730         return MBB->end();
1731 
1732       // If the terminator defines a register, make sure we don't hoist
1733       // the instruction whose def might be clobbered by the terminator.
1734       addRegAndItsAliases(Reg, TRI, Defs);
1735     }
1736   }
1737 
1738   if (Uses.empty())
1739     return Loc;
1740   if (Loc == MBB->begin())
1741     return MBB->end();
1742 
1743   // The terminator is probably a conditional branch, try not to separate the
1744   // branch from condition setting instruction.
1745   MachineBasicBlock::iterator PI =
1746     skipDebugInstructionsBackward(std::prev(Loc), MBB->begin());
1747 
1748   bool IsDef = false;
1749   for (const MachineOperand &MO : PI->operands()) {
1750     // If PI has a regmask operand, it is probably a call. Separate away.
1751     if (MO.isRegMask())
1752       return Loc;
1753     if (!MO.isReg() || MO.isUse())
1754       continue;
1755     unsigned Reg = MO.getReg();
1756     if (!Reg)
1757       continue;
1758     if (Uses.count(Reg)) {
1759       IsDef = true;
1760       break;
1761     }
1762   }
1763   if (!IsDef)
1764     // The condition setting instruction is not just before the conditional
1765     // branch.
1766     return Loc;
1767 
1768   // Be conservative, don't insert instruction above something that may have
1769   // side-effects. And since it's potentially bad to separate flag setting
1770   // instruction from the conditional branch, just abort the optimization
1771   // completely.
1772   // Also avoid moving code above predicated instruction since it's hard to
1773   // reason about register liveness with predicated instruction.
1774   bool DontMoveAcrossStore = true;
1775   if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
1776     return MBB->end();
1777 
1778 
1779   // Find out what registers are live. Note this routine is ignoring other live
1780   // registers which are only used by instructions in successor blocks.
1781   for (const MachineOperand &MO : PI->operands()) {
1782     if (!MO.isReg())
1783       continue;
1784     unsigned Reg = MO.getReg();
1785     if (!Reg)
1786       continue;
1787     if (MO.isUse()) {
1788       addRegAndItsAliases(Reg, TRI, Uses);
1789     } else {
1790       if (Uses.erase(Reg)) {
1791         if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1792           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1793             Uses.erase(*SubRegs); // Use sub-registers to be conservative
1794         }
1795       }
1796       addRegAndItsAliases(Reg, TRI, Defs);
1797     }
1798   }
1799 
1800   return PI;
1801 }
1802 
1803 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1804 /// sequence at the start of the function, move the instructions before MBB
1805 /// terminator if it's legal.
1806 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1807   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1808   SmallVector<MachineOperand, 4> Cond;
1809   if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1810     return false;
1811 
1812   if (!FBB) FBB = findFalseBlock(MBB, TBB);
1813   if (!FBB)
1814     // Malformed bcc? True and false blocks are the same?
1815     return false;
1816 
1817   // Restrict the optimization to cases where MBB is the only predecessor,
1818   // it is an obvious win.
1819   if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1820     return false;
1821 
1822   // Find a suitable position to hoist the common instructions to. Also figure
1823   // out which registers are used or defined by instructions from the insertion
1824   // point to the end of the block.
1825   SmallSet<unsigned, 4> Uses, Defs;
1826   MachineBasicBlock::iterator Loc =
1827     findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1828   if (Loc == MBB->end())
1829     return false;
1830 
1831   bool HasDups = false;
1832   SmallVector<unsigned, 4> LocalDefs;
1833   SmallSet<unsigned, 4> LocalDefsSet;
1834   MachineBasicBlock::iterator TIB = TBB->begin();
1835   MachineBasicBlock::iterator FIB = FBB->begin();
1836   MachineBasicBlock::iterator TIE = TBB->end();
1837   MachineBasicBlock::iterator FIE = FBB->end();
1838   while (TIB != TIE && FIB != FIE) {
1839     // Skip dbg_value instructions. These do not count.
1840     TIB = skipDebugInstructionsForward(TIB, TIE);
1841     FIB = skipDebugInstructionsForward(FIB, FIE);
1842     if (TIB == TIE || FIB == FIE)
1843       break;
1844 
1845     if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
1846       break;
1847 
1848     if (TII->isPredicated(*TIB))
1849       // Hard to reason about register liveness with predicated instruction.
1850       break;
1851 
1852     bool IsSafe = true;
1853     for (MachineOperand &MO : TIB->operands()) {
1854       // Don't attempt to hoist instructions with register masks.
1855       if (MO.isRegMask()) {
1856         IsSafe = false;
1857         break;
1858       }
1859       if (!MO.isReg())
1860         continue;
1861       unsigned Reg = MO.getReg();
1862       if (!Reg)
1863         continue;
1864       if (MO.isDef()) {
1865         if (Uses.count(Reg)) {
1866           // Avoid clobbering a register that's used by the instruction at
1867           // the point of insertion.
1868           IsSafe = false;
1869           break;
1870         }
1871 
1872         if (Defs.count(Reg) && !MO.isDead()) {
1873           // Don't hoist the instruction if the def would be clobber by the
1874           // instruction at the point insertion. FIXME: This is overly
1875           // conservative. It should be possible to hoist the instructions
1876           // in BB2 in the following example:
1877           // BB1:
1878           // r1, eflag = op1 r2, r3
1879           // brcc eflag
1880           //
1881           // BB2:
1882           // r1 = op2, ...
1883           //    = op3, r1<kill>
1884           IsSafe = false;
1885           break;
1886         }
1887       } else if (!LocalDefsSet.count(Reg)) {
1888         if (Defs.count(Reg)) {
1889           // Use is defined by the instruction at the point of insertion.
1890           IsSafe = false;
1891           break;
1892         }
1893 
1894         if (MO.isKill() && Uses.count(Reg))
1895           // Kills a register that's read by the instruction at the point of
1896           // insertion. Remove the kill marker.
1897           MO.setIsKill(false);
1898       }
1899     }
1900     if (!IsSafe)
1901       break;
1902 
1903     bool DontMoveAcrossStore = true;
1904     if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
1905       break;
1906 
1907     // Remove kills from LocalDefsSet, these registers had short live ranges.
1908     for (const MachineOperand &MO : TIB->operands()) {
1909       if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1910         continue;
1911       unsigned Reg = MO.getReg();
1912       if (!Reg || !LocalDefsSet.count(Reg))
1913         continue;
1914       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1915         for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1916           LocalDefsSet.erase(*AI);
1917       } else {
1918         LocalDefsSet.erase(Reg);
1919       }
1920     }
1921 
1922     // Track local defs so we can update liveins.
1923     for (const MachineOperand &MO : TIB->operands()) {
1924       if (!MO.isReg() || !MO.isDef() || MO.isDead())
1925         continue;
1926       unsigned Reg = MO.getReg();
1927       if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg))
1928         continue;
1929       LocalDefs.push_back(Reg);
1930       addRegAndItsAliases(Reg, TRI, LocalDefsSet);
1931     }
1932 
1933     HasDups = true;
1934     ++TIB;
1935     ++FIB;
1936   }
1937 
1938   if (!HasDups)
1939     return false;
1940 
1941   MBB->splice(Loc, TBB, TBB->begin(), TIB);
1942   FBB->erase(FBB->begin(), FIB);
1943 
1944   // Update livein's.
1945   bool AddedLiveIns = false;
1946   for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1947     unsigned Def = LocalDefs[i];
1948     if (LocalDefsSet.count(Def)) {
1949       TBB->addLiveIn(Def);
1950       FBB->addLiveIn(Def);
1951       AddedLiveIns = true;
1952     }
1953   }
1954 
1955   if (AddedLiveIns) {
1956     TBB->sortUniqueLiveIns();
1957     FBB->sortUniqueLiveIns();
1958   }
1959 
1960   ++NumHoist;
1961   return true;
1962 }
1963