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