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