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