1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
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 file implements the machine instruction level if-conversion pass, which
11 // tries to convert conditional branches into predicated instructions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "BranchFolding.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/LivePhysRegs.h"
21 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
22 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/TargetSchedule.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include <algorithm>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "if-converter"
43 
44 // Hidden options for help debugging.
45 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
46 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
47 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
48 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
49                                    cl::init(false), cl::Hidden);
50 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
51                                     cl::init(false), cl::Hidden);
52 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
53                                      cl::init(false), cl::Hidden);
54 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
55                                       cl::init(false), cl::Hidden);
56 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
57                                       cl::init(false), cl::Hidden);
58 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
59                                        cl::init(false), cl::Hidden);
60 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
61                                     cl::init(false), cl::Hidden);
62 static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
63                                         cl::init(false), cl::Hidden);
64 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
65                                      cl::init(true), cl::Hidden);
66 
67 STATISTIC(NumSimple,       "Number of simple if-conversions performed");
68 STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
69 STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
70 STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
71 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
72 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
73 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
74 STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
75 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
76 STATISTIC(NumDupBBs,       "Number of duplicated blocks");
77 STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
78 
79 namespace {
80   class IfConverter : public MachineFunctionPass {
81     enum IfcvtKind {
82       ICNotClassfied,  // BB data valid, but not classified.
83       ICSimpleFalse,   // Same as ICSimple, but on the false path.
84       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
85       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
86       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
87       ICTriangleFalse, // Same as ICTriangle, but on the false path.
88       ICTriangle,      // BB is entry of a triangle sub-CFG.
89       ICDiamond,       // BB is entry of a diamond sub-CFG.
90       ICForkedDiamond  // BB is entry of an almost diamond sub-CFG, with a
91                        // common tail that can be shared.
92     };
93 
94     /// One per MachineBasicBlock, this is used to cache the result
95     /// if-conversion feasibility analysis. This includes results from
96     /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
97     /// classification, and common tail block of its successors (if it's a
98     /// diamond shape), its size, whether it's predicable, and whether any
99     /// instruction can clobber the 'would-be' predicate.
100     ///
101     /// IsDone          - True if BB is not to be considered for ifcvt.
102     /// IsBeingAnalyzed - True if BB is currently being analyzed.
103     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
104     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
105     /// IsBrAnalyzable  - True if analyzeBranch() returns false.
106     /// HasFallThrough  - True if BB may fallthrough to the following BB.
107     /// IsUnpredicable  - True if BB is known to be unpredicable.
108     /// ClobbersPred    - True if BB could modify predicates (e.g. has
109     ///                   cmp, call, etc.)
110     /// NonPredSize     - Number of non-predicated instructions.
111     /// ExtraCost       - Extra cost for multi-cycle instructions.
112     /// ExtraCost2      - Some instructions are slower when predicated
113     /// BB              - Corresponding MachineBasicBlock.
114     /// TrueBB / FalseBB- See analyzeBranch().
115     /// BrCond          - Conditions for end of block conditional branches.
116     /// Predicate       - Predicate used in the BB.
117     struct BBInfo {
118       bool IsDone          : 1;
119       bool IsBeingAnalyzed : 1;
120       bool IsAnalyzed      : 1;
121       bool IsEnqueued      : 1;
122       bool IsBrAnalyzable  : 1;
123       bool IsBrReversible  : 1;
124       bool HasFallThrough  : 1;
125       bool IsUnpredicable  : 1;
126       bool CannotBeCopied  : 1;
127       bool ClobbersPred    : 1;
128       unsigned NonPredSize;
129       unsigned ExtraCost;
130       unsigned ExtraCost2;
131       MachineBasicBlock *BB;
132       MachineBasicBlock *TrueBB;
133       MachineBasicBlock *FalseBB;
134       SmallVector<MachineOperand, 4> BrCond;
135       SmallVector<MachineOperand, 4> Predicate;
136       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
137                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
138                  IsBrReversible(false), HasFallThrough(false),
139                  IsUnpredicable(false), CannotBeCopied(false),
140                  ClobbersPred(false), NonPredSize(0), ExtraCost(0),
141                  ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
142                  FalseBB(nullptr) {}
143     };
144 
145     /// Record information about pending if-conversions to attempt:
146     /// BBI             - Corresponding BBInfo.
147     /// Kind            - Type of block. See IfcvtKind.
148     /// NeedSubsumption - True if the to-be-predicated BB has already been
149     ///                   predicated.
150     /// NumDups      - Number of instructions that would be duplicated due
151     ///                   to this if-conversion. (For diamonds, the number of
152     ///                   identical instructions at the beginnings of both
153     ///                   paths).
154     /// NumDups2     - For diamonds, the number of identical instructions
155     ///                   at the ends of both paths.
156     struct IfcvtToken {
157       BBInfo &BBI;
158       IfcvtKind Kind;
159       unsigned NumDups;
160       unsigned NumDups2;
161       bool NeedSubsumption : 1;
162       bool TClobbersPred : 1;
163       bool FClobbersPred : 1;
164       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
165                  bool tc = false, bool fc = false)
166         : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
167           TClobbersPred(tc), FClobbersPred(fc) {}
168     };
169 
170     /// Results of if-conversion feasibility analysis indexed by basic block
171     /// number.
172     std::vector<BBInfo> BBAnalysis;
173     TargetSchedModel SchedModel;
174 
175     const TargetLoweringBase *TLI;
176     const TargetInstrInfo *TII;
177     const TargetRegisterInfo *TRI;
178     const MachineBranchProbabilityInfo *MBPI;
179     MachineRegisterInfo *MRI;
180 
181     LivePhysRegs Redefs;
182 
183     bool PreRegAlloc;
184     bool MadeChange;
185     int FnNum;
186     std::function<bool(const MachineFunction &)> PredicateFtor;
187 
188   public:
189     static char ID;
190     IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
191         : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
192       initializeIfConverterPass(*PassRegistry::getPassRegistry());
193     }
194 
195     void getAnalysisUsage(AnalysisUsage &AU) const override {
196       AU.addRequired<MachineBlockFrequencyInfo>();
197       AU.addRequired<MachineBranchProbabilityInfo>();
198       MachineFunctionPass::getAnalysisUsage(AU);
199     }
200 
201     bool runOnMachineFunction(MachineFunction &MF) override;
202 
203     MachineFunctionProperties getRequiredProperties() const override {
204       return MachineFunctionProperties().set(
205           MachineFunctionProperties::Property::NoVRegs);
206     }
207 
208   private:
209     bool reverseBranchCondition(BBInfo &BBI) const;
210     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
211                      BranchProbability Prediction) const;
212     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
213                        bool FalseBranch, unsigned &Dups,
214                        BranchProbability Prediction) const;
215     bool CountDuplicatedInstructions(
216         MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
217         MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
218         unsigned &Dups1, unsigned &Dups2,
219         MachineBasicBlock &TBB, MachineBasicBlock &FBB,
220         bool SkipUnconditionalBranches) const;
221     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
222                       unsigned &Dups1, unsigned &Dups2,
223                       BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
224     bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
225                             unsigned &Dups1, unsigned &Dups2,
226                             BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
227     void AnalyzeBranches(BBInfo &BBI);
228     void ScanInstructions(BBInfo &BBI,
229                           MachineBasicBlock::iterator &Begin,
230                           MachineBasicBlock::iterator &End,
231                           bool BranchUnpredicable = false) const;
232     bool RescanInstructions(
233         MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
234         MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
235         BBInfo &TrueBBI, BBInfo &FalseBBI) const;
236     void AnalyzeBlock(MachineBasicBlock &MBB,
237                       std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
238     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
239                              bool isTriangle = false, bool RevBranch = false,
240                              bool hasCommonTail = false);
241     void AnalyzeBlocks(MachineFunction &MF,
242                        std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
243     void InvalidatePreds(MachineBasicBlock &MBB);
244     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
245     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
246     bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
247                                 unsigned NumDups1, unsigned NumDups2,
248                                 bool TClobbersPred, bool FClobbersPred,
249                                 bool RemoveBranch, bool MergeAddEdges);
250     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
251                           unsigned NumDups1, unsigned NumDups2,
252                           bool TClobbers, bool FClobbers);
253     bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
254                               unsigned NumDups1, unsigned NumDups2,
255                               bool TClobbers, bool FClobbers);
256     void PredicateBlock(BBInfo &BBI,
257                         MachineBasicBlock::iterator E,
258                         SmallVectorImpl<MachineOperand> &Cond,
259                         SmallSet<unsigned, 4> *LaterRedefs = nullptr);
260     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
261                                SmallVectorImpl<MachineOperand> &Cond,
262                                bool IgnoreBr = false);
263     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
264 
265     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
266                             unsigned Cycle, unsigned Extra,
267                             BranchProbability Prediction) const {
268       return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
269                                                    Prediction);
270     }
271 
272     bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
273                             unsigned TCycle, unsigned TExtra,
274                             MachineBasicBlock &FBB,
275                             unsigned FCycle, unsigned FExtra,
276                             BranchProbability Prediction) const {
277       return TCycle > 0 && FCycle > 0 &&
278         TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
279                                  Prediction);
280     }
281 
282     /// Returns true if Block ends without a terminator.
283     bool blockAlwaysFallThrough(BBInfo &BBI) const {
284       return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
285     }
286 
287     /// Used to sort if-conversion candidates.
288     static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
289                               const std::unique_ptr<IfcvtToken> &C2) {
290       int Incr1 = (C1->Kind == ICDiamond)
291         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
292       int Incr2 = (C2->Kind == ICDiamond)
293         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
294       if (Incr1 > Incr2)
295         return true;
296       else if (Incr1 == Incr2) {
297         // Favors subsumption.
298         if (!C1->NeedSubsumption && C2->NeedSubsumption)
299           return true;
300         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
301           // Favors diamond over triangle, etc.
302           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
303             return true;
304           else if (C1->Kind == C2->Kind)
305             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
306         }
307       }
308       return false;
309     }
310   };
311 
312   char IfConverter::ID = 0;
313 }
314 
315 char &llvm::IfConverterID = IfConverter::ID;
316 
317 INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
318 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
319 INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
320 
321 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
322   if (skipFunction(*MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
323     return false;
324 
325   const TargetSubtargetInfo &ST = MF.getSubtarget();
326   TLI = ST.getTargetLowering();
327   TII = ST.getInstrInfo();
328   TRI = ST.getRegisterInfo();
329   BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
330   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
331   MRI = &MF.getRegInfo();
332   SchedModel.init(ST.getSchedModel(), &ST, TII);
333 
334   if (!TII) return false;
335 
336   PreRegAlloc = MRI->isSSA();
337 
338   bool BFChange = false;
339   if (!PreRegAlloc) {
340     // Tail merge tend to expose more if-conversion opportunities.
341     BranchFolder BF(true, false, MBFI, *MBPI);
342     BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
343                                    getAnalysisIfAvailable<MachineModuleInfo>());
344   }
345 
346   DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
347                << MF.getName() << "\'");
348 
349   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
350     DEBUG(dbgs() << " skipped\n");
351     return false;
352   }
353   DEBUG(dbgs() << "\n");
354 
355   MF.RenumberBlocks();
356   BBAnalysis.resize(MF.getNumBlockIDs());
357 
358   std::vector<std::unique_ptr<IfcvtToken>> Tokens;
359   MadeChange = false;
360   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
361     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
362   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
363     // Do an initial analysis for each basic block and find all the potential
364     // candidates to perform if-conversion.
365     bool Change = false;
366     AnalyzeBlocks(MF, Tokens);
367     while (!Tokens.empty()) {
368       std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
369       Tokens.pop_back();
370       BBInfo &BBI = Token->BBI;
371       IfcvtKind Kind = Token->Kind;
372       unsigned NumDups = Token->NumDups;
373       unsigned NumDups2 = Token->NumDups2;
374 
375       // If the block has been evicted out of the queue or it has already been
376       // marked dead (due to it being predicated), then skip it.
377       if (BBI.IsDone)
378         BBI.IsEnqueued = false;
379       if (!BBI.IsEnqueued)
380         continue;
381 
382       BBI.IsEnqueued = false;
383 
384       bool RetVal = false;
385       switch (Kind) {
386       default: llvm_unreachable("Unexpected!");
387       case ICSimple:
388       case ICSimpleFalse: {
389         bool isFalse = Kind == ICSimpleFalse;
390         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
391         DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
392                                             " false" : "")
393                      << "): BB#" << BBI.BB->getNumber() << " ("
394                      << ((Kind == ICSimpleFalse)
395                          ? BBI.FalseBB->getNumber()
396                          : BBI.TrueBB->getNumber()) << ") ");
397         RetVal = IfConvertSimple(BBI, Kind);
398         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
399         if (RetVal) {
400           if (isFalse) ++NumSimpleFalse;
401           else         ++NumSimple;
402         }
403        break;
404       }
405       case ICTriangle:
406       case ICTriangleRev:
407       case ICTriangleFalse:
408       case ICTriangleFRev: {
409         bool isFalse = Kind == ICTriangleFalse;
410         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
411         if (DisableTriangle && !isFalse && !isRev) break;
412         if (DisableTriangleR && !isFalse && isRev) break;
413         if (DisableTriangleF && isFalse && !isRev) break;
414         if (DisableTriangleFR && isFalse && isRev) break;
415         DEBUG(dbgs() << "Ifcvt (Triangle");
416         if (isFalse)
417           DEBUG(dbgs() << " false");
418         if (isRev)
419           DEBUG(dbgs() << " rev");
420         DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
421                      << BBI.TrueBB->getNumber() << ",F:"
422                      << BBI.FalseBB->getNumber() << ") ");
423         RetVal = IfConvertTriangle(BBI, Kind);
424         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
425         if (RetVal) {
426           if (isFalse) {
427             if (isRev) ++NumTriangleFRev;
428             else       ++NumTriangleFalse;
429           } else {
430             if (isRev) ++NumTriangleRev;
431             else       ++NumTriangle;
432           }
433         }
434         break;
435       }
436       case ICDiamond: {
437         if (DisableDiamond) break;
438         DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
439                      << BBI.TrueBB->getNumber() << ",F:"
440                      << BBI.FalseBB->getNumber() << ") ");
441         RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
442                                   Token->TClobbersPred,
443                                   Token->FClobbersPred);
444         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
445         if (RetVal) ++NumDiamonds;
446         break;
447       }
448       case ICForkedDiamond: {
449         if (DisableForkedDiamond) break;
450         DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
451                      << BBI.BB->getNumber() << " (T:"
452                      << BBI.TrueBB->getNumber() << ",F:"
453                      << BBI.FalseBB->getNumber() << ") ");
454         RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
455                                       Token->TClobbersPred,
456                                       Token->FClobbersPred);
457         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
458         if (RetVal) ++NumForkedDiamonds;
459         break;
460       }
461       }
462 
463       if (RetVal && MRI->tracksLiveness())
464         recomputeLivenessFlags(*BBI.BB);
465 
466       Change |= RetVal;
467 
468       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
469         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
470       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
471         break;
472     }
473 
474     if (!Change)
475       break;
476     MadeChange |= Change;
477   }
478 
479   Tokens.clear();
480   BBAnalysis.clear();
481 
482   if (MadeChange && IfCvtBranchFold) {
483     BranchFolder BF(false, false, MBFI, *MBPI);
484     BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
485                         getAnalysisIfAvailable<MachineModuleInfo>());
486   }
487 
488   MadeChange |= BFChange;
489   return MadeChange;
490 }
491 
492 /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
493 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
494                                          MachineBasicBlock *TrueBB) {
495   for (MachineBasicBlock *SuccBB : BB->successors()) {
496     if (SuccBB != TrueBB)
497       return SuccBB;
498   }
499   return nullptr;
500 }
501 
502 /// Reverse the condition of the end of the block branch. Swap block's 'true'
503 /// and 'false' successors.
504 bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
505   DebugLoc dl;  // FIXME: this is nowhere
506   if (!TII->reverseBranchCondition(BBI.BrCond)) {
507     TII->removeBranch(*BBI.BB);
508     TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
509     std::swap(BBI.TrueBB, BBI.FalseBB);
510     return true;
511   }
512   return false;
513 }
514 
515 /// Returns the next block in the function blocks ordering. If it is the end,
516 /// returns NULL.
517 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
518   MachineFunction::iterator I = MBB.getIterator();
519   MachineFunction::iterator E = MBB.getParent()->end();
520   if (++I == E)
521     return nullptr;
522   return &*I;
523 }
524 
525 /// Returns true if the 'true' block (along with its predecessor) forms a valid
526 /// simple shape for ifcvt. It also returns the number of instructions that the
527 /// ifcvt would need to duplicate if performed in Dups.
528 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
529                               BranchProbability Prediction) const {
530   Dups = 0;
531   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
532     return false;
533 
534   if (TrueBBI.IsBrAnalyzable)
535     return false;
536 
537   if (TrueBBI.BB->pred_size() > 1) {
538     if (TrueBBI.CannotBeCopied ||
539         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
540                                         Prediction))
541       return false;
542     Dups = TrueBBI.NonPredSize;
543   }
544 
545   return true;
546 }
547 
548 /// Returns true if the 'true' and 'false' blocks (along with their common
549 /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
550 /// true, it checks if 'true' block's false branch branches to the 'false' block
551 /// rather than the other way around. It also returns the number of instructions
552 /// that the ifcvt would need to duplicate if performed in 'Dups'.
553 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
554                                 bool FalseBranch, unsigned &Dups,
555                                 BranchProbability Prediction) const {
556   Dups = 0;
557   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
558     return false;
559 
560   if (TrueBBI.BB->pred_size() > 1) {
561     if (TrueBBI.CannotBeCopied)
562       return false;
563 
564     unsigned Size = TrueBBI.NonPredSize;
565     if (TrueBBI.IsBrAnalyzable) {
566       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
567         // Ends with an unconditional branch. It will be removed.
568         --Size;
569       else {
570         MachineBasicBlock *FExit = FalseBranch
571           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
572         if (FExit)
573           // Require a conditional branch
574           ++Size;
575       }
576     }
577     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
578       return false;
579     Dups = Size;
580   }
581 
582   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
583   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
584     MachineFunction::iterator I = TrueBBI.BB->getIterator();
585     if (++I == TrueBBI.BB->getParent()->end())
586       return false;
587     TExit = &*I;
588   }
589   return TExit && TExit == FalseBBI.BB;
590 }
591 
592 /// Count duplicated instructions and move the iterators to show where they
593 /// are.
594 /// @param TIB True Iterator Begin
595 /// @param FIB False Iterator Begin
596 /// These two iterators initially point to the first instruction of the two
597 /// blocks, and finally point to the first non-shared instruction.
598 /// @param TIE True Iterator End
599 /// @param FIE False Iterator End
600 /// These two iterators initially point to End() for the two blocks() and
601 /// finally point to the first shared instruction in the tail.
602 /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
603 /// two blocks.
604 /// @param Dups1 count of duplicated instructions at the beginning of the 2
605 /// blocks.
606 /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
607 /// @param SkipUnconditionalBranches if true, Don't make sure that
608 /// unconditional branches at the end of the blocks are the same. True is
609 /// passed when the blocks are analyzable to allow for fallthrough to be
610 /// handled.
611 /// @return false if the shared portion prevents if conversion.
612 bool IfConverter::CountDuplicatedInstructions(
613     MachineBasicBlock::iterator &TIB,
614     MachineBasicBlock::iterator &FIB,
615     MachineBasicBlock::iterator &TIE,
616     MachineBasicBlock::iterator &FIE,
617     unsigned &Dups1, unsigned &Dups2,
618     MachineBasicBlock &TBB, MachineBasicBlock &FBB,
619     bool SkipUnconditionalBranches) const {
620 
621   while (TIB != TIE && FIB != FIE) {
622     // Skip dbg_value instructions. These do not count.
623     TIB = skipDebugInstructionsForward(TIB, TIE);
624     FIB = skipDebugInstructionsForward(FIB, FIE);
625     if (TIB == TIE || FIB == FIE)
626       break;
627     if (!TIB->isIdenticalTo(*FIB))
628       break;
629     // A pred-clobbering instruction in the shared portion prevents
630     // if-conversion.
631     std::vector<MachineOperand> PredDefs;
632     if (TII->DefinesPredicate(*TIB, PredDefs))
633       return false;
634     // If we get all the way to the branch instructions, don't count them.
635     if (!TIB->isBranch())
636       ++Dups1;
637     ++TIB;
638     ++FIB;
639   }
640 
641   // Check for already containing all of the block.
642   if (TIB == TIE || FIB == FIE)
643     return true;
644   // Now, in preparation for counting duplicate instructions at the ends of the
645   // blocks, switch to reverse_iterators. Note that getReverse() returns an
646   // iterator that points to the same instruction, unlike std::reverse_iterator.
647   // We have to do our own shifting so that we get the same range.
648   MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
649   MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
650   const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
651   const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
652 
653   if (!TBB.succ_empty() || !FBB.succ_empty()) {
654     if (SkipUnconditionalBranches) {
655       while (RTIE != RTIB && RTIE->isUnconditionalBranch())
656         ++RTIE;
657       while (RFIE != RFIB && RFIE->isUnconditionalBranch())
658         ++RFIE;
659     }
660   }
661 
662   // Count duplicate instructions at the ends of the blocks.
663   while (RTIE != RTIB && RFIE != RFIB) {
664     // Skip dbg_value instructions. These do not count.
665     // Note that these are reverse iterators going forward.
666     RTIE = skipDebugInstructionsForward(RTIE, RTIB);
667     RFIE = skipDebugInstructionsForward(RFIE, RFIB);
668     if (RTIE == RTIB || RFIE == RFIB)
669       break;
670     if (!RTIE->isIdenticalTo(*RFIE))
671       break;
672     // We have to verify that any branch instructions are the same, and then we
673     // don't count them toward the # of duplicate instructions.
674     if (!RTIE->isBranch())
675       ++Dups2;
676     ++RTIE;
677     ++RFIE;
678   }
679   TIE = std::next(RTIE.getReverse());
680   FIE = std::next(RFIE.getReverse());
681   return true;
682 }
683 
684 /// RescanInstructions - Run ScanInstructions on a pair of blocks.
685 /// @param TIB - True Iterator Begin, points to first non-shared instruction
686 /// @param FIB - False Iterator Begin, points to first non-shared instruction
687 /// @param TIE - True Iterator End, points past last non-shared instruction
688 /// @param FIE - False Iterator End, points past last non-shared instruction
689 /// @param TrueBBI  - BBInfo to update for the true block.
690 /// @param FalseBBI - BBInfo to update for the false block.
691 /// @returns - false if either block cannot be predicated or if both blocks end
692 ///   with a predicate-clobbering instruction.
693 bool IfConverter::RescanInstructions(
694     MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
695     MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
696     BBInfo &TrueBBI, BBInfo &FalseBBI) const {
697   bool BranchUnpredicable = true;
698   TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
699   ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
700   if (TrueBBI.IsUnpredicable)
701     return false;
702   ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
703   if (FalseBBI.IsUnpredicable)
704     return false;
705   if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
706     return false;
707   return true;
708 }
709 
710 #ifndef NDEBUG
711 static void verifySameBranchInstructions(
712     MachineBasicBlock *MBB1,
713     MachineBasicBlock *MBB2) {
714   const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
715   const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
716   MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
717   MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
718   while (E1 != B1 && E2 != B2) {
719     skipDebugInstructionsForward(E1, B1);
720     skipDebugInstructionsForward(E2, B2);
721     if (E1 == B1 && E2 == B2)
722       break;
723 
724     if (E1 == B1) {
725       assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
726       break;
727     }
728     if (E2 == B2) {
729       assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
730       break;
731     }
732 
733     if (E1->isBranch() || E2->isBranch())
734       assert(E1->isIdenticalTo(*E2) &&
735              "Branch mis-match, branch instructions don't match.");
736     else
737       break;
738     ++E1;
739     ++E2;
740   }
741 }
742 #endif
743 
744 /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
745 /// with their common predecessor) form a diamond if a common tail block is
746 /// extracted.
747 /// While not strictly a diamond, this pattern would form a diamond if
748 /// tail-merging had merged the shared tails.
749 ///           EBB
750 ///         _/   \_
751 ///         |     |
752 ///        TBB   FBB
753 ///        /  \ /   \
754 ///  FalseBB TrueBB FalseBB
755 /// Currently only handles analyzable branches.
756 /// Specifically excludes actual diamonds to avoid overlap.
757 bool IfConverter::ValidForkedDiamond(
758     BBInfo &TrueBBI, BBInfo &FalseBBI,
759     unsigned &Dups1, unsigned &Dups2,
760     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
761   Dups1 = Dups2 = 0;
762   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
763       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
764     return false;
765 
766   if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
767     return false;
768   // Don't IfConvert blocks that can't be folded into their predecessor.
769   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
770     return false;
771 
772   // This function is specifically looking for conditional tails, as
773   // unconditional tails are already handled by the standard diamond case.
774   if (TrueBBI.BrCond.size() == 0 ||
775       FalseBBI.BrCond.size() == 0)
776     return false;
777 
778   MachineBasicBlock *TT = TrueBBI.TrueBB;
779   MachineBasicBlock *TF = TrueBBI.FalseBB;
780   MachineBasicBlock *FT = FalseBBI.TrueBB;
781   MachineBasicBlock *FF = FalseBBI.FalseBB;
782 
783   if (!TT)
784     TT = getNextBlock(*TrueBBI.BB);
785   if (!TF)
786     TF = getNextBlock(*TrueBBI.BB);
787   if (!FT)
788     FT = getNextBlock(*FalseBBI.BB);
789   if (!FF)
790     FF = getNextBlock(*FalseBBI.BB);
791 
792   if (!TT || !TF)
793     return false;
794 
795   // Check successors. If they don't match, bail.
796   if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
797     return false;
798 
799   bool FalseReversed = false;
800   if (TF == FT && TT == FF) {
801     // If the branches are opposing, but we can't reverse, don't do it.
802     if (!FalseBBI.IsBrReversible)
803       return false;
804     FalseReversed = true;
805     reverseBranchCondition(FalseBBI);
806   }
807   auto UnReverseOnExit = make_scope_exit([&]() {
808     if (FalseReversed)
809       reverseBranchCondition(FalseBBI);
810   });
811 
812   // Count duplicate instructions at the beginning of the true and false blocks.
813   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
814   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
815   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
816   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
817   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
818                                   *TrueBBI.BB, *FalseBBI.BB,
819                                   /* SkipUnconditionalBranches */ true))
820     return false;
821 
822   TrueBBICalc.BB = TrueBBI.BB;
823   FalseBBICalc.BB = FalseBBI.BB;
824   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
825     return false;
826 
827   // The size is used to decide whether to if-convert, and the shared portions
828   // are subtracted off. Because of the subtraction, we just use the size that
829   // was calculated by the original ScanInstructions, as it is correct.
830   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
831   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
832   return true;
833 }
834 
835 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
836 /// with their common predecessor) forms a valid diamond shape for ifcvt.
837 bool IfConverter::ValidDiamond(
838     BBInfo &TrueBBI, BBInfo &FalseBBI,
839     unsigned &Dups1, unsigned &Dups2,
840     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
841   Dups1 = Dups2 = 0;
842   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
843       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
844     return false;
845 
846   MachineBasicBlock *TT = TrueBBI.TrueBB;
847   MachineBasicBlock *FT = FalseBBI.TrueBB;
848 
849   if (!TT && blockAlwaysFallThrough(TrueBBI))
850     TT = getNextBlock(*TrueBBI.BB);
851   if (!FT && blockAlwaysFallThrough(FalseBBI))
852     FT = getNextBlock(*FalseBBI.BB);
853   if (TT != FT)
854     return false;
855   if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
856     return false;
857   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
858     return false;
859 
860   // FIXME: Allow true block to have an early exit?
861   if (TrueBBI.FalseBB || FalseBBI.FalseBB)
862     return false;
863 
864   // Count duplicate instructions at the beginning and end of the true and
865   // false blocks.
866   // Skip unconditional branches only if we are considering an analyzable
867   // diamond. Otherwise the branches must be the same.
868   bool SkipUnconditionalBranches =
869       TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
870   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
871   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
872   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
873   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
874   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
875                                   *TrueBBI.BB, *FalseBBI.BB,
876                                   SkipUnconditionalBranches))
877     return false;
878 
879   TrueBBICalc.BB = TrueBBI.BB;
880   FalseBBICalc.BB = FalseBBI.BB;
881   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
882     return false;
883   // The size is used to decide whether to if-convert, and the shared portions
884   // are subtracted off. Because of the subtraction, we just use the size that
885   // was calculated by the original ScanInstructions, as it is correct.
886   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
887   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
888   return true;
889 }
890 
891 /// AnalyzeBranches - Look at the branches at the end of a block to determine if
892 /// the block is predicable.
893 void IfConverter::AnalyzeBranches(BBInfo &BBI) {
894   if (BBI.IsDone)
895     return;
896 
897   BBI.TrueBB = BBI.FalseBB = nullptr;
898   BBI.BrCond.clear();
899   BBI.IsBrAnalyzable =
900       !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
901   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
902   BBI.IsBrReversible = (RevCond.size() == 0) ||
903       !TII->reverseBranchCondition(RevCond);
904   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
905 
906   if (BBI.BrCond.size()) {
907     // No false branch. This BB must end with a conditional branch and a
908     // fallthrough.
909     if (!BBI.FalseBB)
910       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
911     if (!BBI.FalseBB) {
912       // Malformed bcc? True and false blocks are the same?
913       BBI.IsUnpredicable = true;
914     }
915   }
916 }
917 
918 /// ScanInstructions - Scan all the instructions in the block to determine if
919 /// the block is predicable. In most cases, that means all the instructions
920 /// in the block are isPredicable(). Also checks if the block contains any
921 /// instruction which can clobber a predicate (e.g. condition code register).
922 /// If so, the block is not predicable unless it's the last instruction.
923 void IfConverter::ScanInstructions(BBInfo &BBI,
924                                    MachineBasicBlock::iterator &Begin,
925                                    MachineBasicBlock::iterator &End,
926                                    bool BranchUnpredicable) const {
927   if (BBI.IsDone || BBI.IsUnpredicable)
928     return;
929 
930   bool AlreadyPredicated = !BBI.Predicate.empty();
931 
932   BBI.NonPredSize = 0;
933   BBI.ExtraCost = 0;
934   BBI.ExtraCost2 = 0;
935   BBI.ClobbersPred = false;
936   for (MachineInstr &MI : make_range(Begin, End)) {
937     if (MI.isDebugValue())
938       continue;
939 
940     // It's unsafe to duplicate convergent instructions in this context, so set
941     // BBI.CannotBeCopied to true if MI is convergent.  To see why, consider the
942     // following CFG, which is subject to our "simple" transformation.
943     //
944     //    BB0     // if (c1) goto BB1; else goto BB2;
945     //   /   \
946     //  BB1   |
947     //   |   BB2  // if (c2) goto TBB; else goto FBB;
948     //   |   / |
949     //   |  /  |
950     //   TBB   |
951     //    |    |
952     //    |   FBB
953     //    |
954     //    exit
955     //
956     // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
957     // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
958     // TBB contains a convergent instruction.  This is safe iff doing so does
959     // not add a control-flow dependency to the convergent instruction -- i.e.,
960     // it's safe iff the set of control flows that leads us to the convergent
961     // instruction does not get smaller after the transformation.
962     //
963     // Originally we executed TBB if c1 || c2.  After the transformation, there
964     // are two copies of TBB's instructions.  We get to the first if c1, and we
965     // get to the second if !c1 && c2.
966     //
967     // There are clearly fewer ways to satisfy the condition "c1" than
968     // "c1 || c2".  Since we've shrunk the set of control flows which lead to
969     // our convergent instruction, the transformation is unsafe.
970     if (MI.isNotDuplicable() || MI.isConvergent())
971       BBI.CannotBeCopied = true;
972 
973     bool isPredicated = TII->isPredicated(MI);
974     bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
975 
976     if (BranchUnpredicable && MI.isBranch()) {
977       BBI.IsUnpredicable = true;
978       return;
979     }
980 
981     // A conditional branch is not predicable, but it may be eliminated.
982     if (isCondBr)
983       continue;
984 
985     if (!isPredicated) {
986       BBI.NonPredSize++;
987       unsigned ExtraPredCost = TII->getPredicationCost(MI);
988       unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
989       if (NumCycles > 1)
990         BBI.ExtraCost += NumCycles-1;
991       BBI.ExtraCost2 += ExtraPredCost;
992     } else if (!AlreadyPredicated) {
993       // FIXME: This instruction is already predicated before the
994       // if-conversion pass. It's probably something like a conditional move.
995       // Mark this block unpredicable for now.
996       BBI.IsUnpredicable = true;
997       return;
998     }
999 
1000     if (BBI.ClobbersPred && !isPredicated) {
1001       // Predicate modification instruction should end the block (except for
1002       // already predicated instructions and end of block branches).
1003       // Predicate may have been modified, the subsequent (currently)
1004       // unpredicated instructions cannot be correctly predicated.
1005       BBI.IsUnpredicable = true;
1006       return;
1007     }
1008 
1009     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1010     // still potentially predicable.
1011     std::vector<MachineOperand> PredDefs;
1012     if (TII->DefinesPredicate(MI, PredDefs))
1013       BBI.ClobbersPred = true;
1014 
1015     if (!TII->isPredicable(MI)) {
1016       BBI.IsUnpredicable = true;
1017       return;
1018     }
1019   }
1020 }
1021 
1022 /// Determine if the block is a suitable candidate to be predicated by the
1023 /// specified predicate.
1024 /// @param BBI BBInfo for the block to check
1025 /// @param Pred Predicate array for the branch that leads to BBI
1026 /// @param isTriangle true if the Analysis is for a triangle
1027 /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1028 ///        case
1029 /// @param hasCommonTail true if BBI shares a tail with a sibling block that
1030 ///        contains any instruction that would make the block unpredicable.
1031 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
1032                                       SmallVectorImpl<MachineOperand> &Pred,
1033                                       bool isTriangle, bool RevBranch,
1034                                       bool hasCommonTail) {
1035   // If the block is dead or unpredicable, then it cannot be predicated.
1036   // Two blocks may share a common unpredicable tail, but this doesn't prevent
1037   // them from being if-converted. The non-shared portion is assumed to have
1038   // been checked
1039   if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1040     return false;
1041 
1042   // If it is already predicated but we couldn't analyze its terminator, the
1043   // latter might fallthrough, but we can't determine where to.
1044   // Conservatively avoid if-converting again.
1045   if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1046     return false;
1047 
1048   // If it is already predicated, check if the new predicate subsumes
1049   // its predicate.
1050   if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
1051     return false;
1052 
1053   if (!hasCommonTail && BBI.BrCond.size()) {
1054     if (!isTriangle)
1055       return false;
1056 
1057     // Test predicate subsumption.
1058     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1059     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1060     if (RevBranch) {
1061       if (TII->reverseBranchCondition(Cond))
1062         return false;
1063     }
1064     if (TII->reverseBranchCondition(RevPred) ||
1065         !TII->SubsumesPredicate(Cond, RevPred))
1066       return false;
1067   }
1068 
1069   return true;
1070 }
1071 
1072 /// Analyze the structure of the sub-CFG starting from the specified block.
1073 /// Record its successors and whether it looks like an if-conversion candidate.
1074 void IfConverter::AnalyzeBlock(
1075     MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1076   struct BBState {
1077     BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
1078     MachineBasicBlock *MBB;
1079 
1080     /// This flag is true if MBB's successors have been analyzed.
1081     bool SuccsAnalyzed;
1082   };
1083 
1084   // Push MBB to the stack.
1085   SmallVector<BBState, 16> BBStack(1, MBB);
1086 
1087   while (!BBStack.empty()) {
1088     BBState &State = BBStack.back();
1089     MachineBasicBlock *BB = State.MBB;
1090     BBInfo &BBI = BBAnalysis[BB->getNumber()];
1091 
1092     if (!State.SuccsAnalyzed) {
1093       if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1094         BBStack.pop_back();
1095         continue;
1096       }
1097 
1098       BBI.BB = BB;
1099       BBI.IsBeingAnalyzed = true;
1100 
1101       AnalyzeBranches(BBI);
1102       MachineBasicBlock::iterator Begin = BBI.BB->begin();
1103       MachineBasicBlock::iterator End = BBI.BB->end();
1104       ScanInstructions(BBI, Begin, End);
1105 
1106       // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1107       // not considered for ifcvt anymore.
1108       if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1109         BBI.IsBeingAnalyzed = false;
1110         BBI.IsAnalyzed = true;
1111         BBStack.pop_back();
1112         continue;
1113       }
1114 
1115       // Do not ifcvt if either path is a back edge to the entry block.
1116       if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1117         BBI.IsBeingAnalyzed = false;
1118         BBI.IsAnalyzed = true;
1119         BBStack.pop_back();
1120         continue;
1121       }
1122 
1123       // Do not ifcvt if true and false fallthrough blocks are the same.
1124       if (!BBI.FalseBB) {
1125         BBI.IsBeingAnalyzed = false;
1126         BBI.IsAnalyzed = true;
1127         BBStack.pop_back();
1128         continue;
1129       }
1130 
1131       // Push the False and True blocks to the stack.
1132       State.SuccsAnalyzed = true;
1133       BBStack.push_back(*BBI.FalseBB);
1134       BBStack.push_back(*BBI.TrueBB);
1135       continue;
1136     }
1137 
1138     BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1139     BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1140 
1141     if (TrueBBI.IsDone && FalseBBI.IsDone) {
1142       BBI.IsBeingAnalyzed = false;
1143       BBI.IsAnalyzed = true;
1144       BBStack.pop_back();
1145       continue;
1146     }
1147 
1148     SmallVector<MachineOperand, 4>
1149         RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1150     bool CanRevCond = !TII->reverseBranchCondition(RevCond);
1151 
1152     unsigned Dups = 0;
1153     unsigned Dups2 = 0;
1154     bool TNeedSub = !TrueBBI.Predicate.empty();
1155     bool FNeedSub = !FalseBBI.Predicate.empty();
1156     bool Enqueued = false;
1157 
1158     BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1159 
1160     if (CanRevCond) {
1161       BBInfo TrueBBICalc, FalseBBICalc;
1162       auto feasibleDiamond = [&]() {
1163         bool MeetsSize = MeetIfcvtSizeLimit(
1164             *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1165                           TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1166             *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1167                            FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1168             Prediction);
1169         bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1170                                                 /* IsTriangle */ false, /* RevCond */ false,
1171                                                 /* hasCommonTail */ true);
1172         bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1173                                                  /* IsTriangle */ false, /* RevCond */ false,
1174                                                  /* hasCommonTail */ true);
1175         return MeetsSize && TrueFeasible && FalseFeasible;
1176       };
1177 
1178       if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1179                        TrueBBICalc, FalseBBICalc)) {
1180         if (feasibleDiamond()) {
1181           // Diamond:
1182           //   EBB
1183           //   / \_
1184           //  |   |
1185           // TBB FBB
1186           //   \ /
1187           //  TailBB
1188           // Note TailBB can be empty.
1189           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1190               BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1191               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1192           Enqueued = true;
1193         }
1194       } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1195                                     TrueBBICalc, FalseBBICalc)) {
1196         if (feasibleDiamond()) {
1197           // ForkedDiamond:
1198           // if TBB and FBB have a common tail that includes their conditional
1199           // branch instructions, then we can If Convert this pattern.
1200           //          EBB
1201           //         _/ \_
1202           //         |   |
1203           //        TBB  FBB
1204           //        / \ /   \
1205           //  FalseBB TrueBB FalseBB
1206           //
1207           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1208               BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1209               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1210           Enqueued = true;
1211         }
1212       }
1213     }
1214 
1215     if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1216         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1217                            TrueBBI.ExtraCost2, Prediction) &&
1218         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1219       // Triangle:
1220       //   EBB
1221       //   | \_
1222       //   |  |
1223       //   | TBB
1224       //   |  /
1225       //   FBB
1226       Tokens.push_back(
1227           llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1228       Enqueued = true;
1229     }
1230 
1231     if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1232         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1233                            TrueBBI.ExtraCost2, Prediction) &&
1234         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
1235       Tokens.push_back(
1236           llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1237       Enqueued = true;
1238     }
1239 
1240     if (ValidSimple(TrueBBI, Dups, Prediction) &&
1241         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1242                            TrueBBI.ExtraCost2, Prediction) &&
1243         FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1244       // Simple (split, no rejoin):
1245       //   EBB
1246       //   | \_
1247       //   |  |
1248       //   | TBB---> exit
1249       //   |
1250       //   FBB
1251       Tokens.push_back(
1252           llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1253       Enqueued = true;
1254     }
1255 
1256     if (CanRevCond) {
1257       // Try the other path...
1258       if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1259                         Prediction.getCompl()) &&
1260           MeetIfcvtSizeLimit(*FalseBBI.BB,
1261                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1262                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1263           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
1264         Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1265                                                        FNeedSub, Dups));
1266         Enqueued = true;
1267       }
1268 
1269       if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1270                         Prediction.getCompl()) &&
1271           MeetIfcvtSizeLimit(*FalseBBI.BB,
1272                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1273                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1274         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
1275         Tokens.push_back(
1276             llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1277         Enqueued = true;
1278       }
1279 
1280       if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1281           MeetIfcvtSizeLimit(*FalseBBI.BB,
1282                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1283                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1284           FeasibilityAnalysis(FalseBBI, RevCond)) {
1285         Tokens.push_back(
1286             llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1287         Enqueued = true;
1288       }
1289     }
1290 
1291     BBI.IsEnqueued = Enqueued;
1292     BBI.IsBeingAnalyzed = false;
1293     BBI.IsAnalyzed = true;
1294     BBStack.pop_back();
1295   }
1296 }
1297 
1298 /// Analyze all blocks and find entries for all if-conversion candidates.
1299 void IfConverter::AnalyzeBlocks(
1300     MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1301   for (MachineBasicBlock &MBB : MF)
1302     AnalyzeBlock(MBB, Tokens);
1303 
1304   // Sort to favor more complex ifcvt scheme.
1305   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
1306 }
1307 
1308 /// Returns true either if ToMBB is the next block after MBB or that all the
1309 /// intervening blocks are empty (given MBB can fall through to its next block).
1310 static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1311   MachineFunction::iterator PI = MBB.getIterator();
1312   MachineFunction::iterator I = std::next(PI);
1313   MachineFunction::iterator TI = ToMBB.getIterator();
1314   MachineFunction::iterator E = MBB.getParent()->end();
1315   while (I != TI) {
1316     // Check isSuccessor to avoid case where the next block is empty, but
1317     // it's not a successor.
1318     if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1319       return false;
1320     PI = I++;
1321   }
1322   // Finally see if the last I is indeed a successor to PI.
1323   return PI->isSuccessor(&*I);
1324 }
1325 
1326 /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1327 /// can be if-converted. If predecessor is already enqueued, dequeue it!
1328 void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1329   for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
1330     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1331     if (PBBI.IsDone || PBBI.BB == &MBB)
1332       continue;
1333     PBBI.IsAnalyzed = false;
1334     PBBI.IsEnqueued = false;
1335   }
1336 }
1337 
1338 /// Inserts an unconditional branch from \p MBB to \p ToMBB.
1339 static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
1340                                const TargetInstrInfo *TII) {
1341   DebugLoc dl;  // FIXME: this is nowhere
1342   SmallVector<MachineOperand, 0> NoCond;
1343   TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
1344 }
1345 
1346 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1347 /// values defined in MI which are also live/used by MI.
1348 static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
1349   const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1350     ->getSubtarget().getRegisterInfo();
1351 
1352   // Before stepping forward past MI, remember which regs were live
1353   // before MI. This is needed to set the Undef flag only when reg is
1354   // dead.
1355   SparseSet<unsigned> LiveBeforeMI;
1356   LiveBeforeMI.setUniverse(TRI->getNumRegs());
1357   for (unsigned Reg : Redefs)
1358     LiveBeforeMI.insert(Reg);
1359 
1360   SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1361   Redefs.stepForward(MI, Clobbers);
1362 
1363   // Now add the implicit uses for each of the clobbered values.
1364   for (auto Clobber : Clobbers) {
1365     // FIXME: Const cast here is nasty, but better than making StepForward
1366     // take a mutable instruction instead of const.
1367     unsigned Reg = Clobber.first;
1368     MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
1369     MachineInstr *OpMI = Op.getParent();
1370     MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
1371     if (Op.isRegMask()) {
1372       // First handle regmasks.  They clobber any entries in the mask which
1373       // means that we need a def for those registers.
1374       if (LiveBeforeMI.count(Reg))
1375         MIB.addReg(Reg, RegState::Implicit);
1376 
1377       // We also need to add an implicit def of this register for the later
1378       // use to read from.
1379       // For the register allocator to have allocated a register clobbered
1380       // by the call which is used later, it must be the case that
1381       // the call doesn't return.
1382       MIB.addReg(Reg, RegState::Implicit | RegState::Define);
1383       continue;
1384     }
1385     if (LiveBeforeMI.count(Reg))
1386       MIB.addReg(Reg, RegState::Implicit);
1387     else {
1388       bool HasLiveSubReg = false;
1389       for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
1390         if (!LiveBeforeMI.count(*S))
1391           continue;
1392         HasLiveSubReg = true;
1393         break;
1394       }
1395       if (HasLiveSubReg)
1396         MIB.addReg(Reg, RegState::Implicit);
1397     }
1398   }
1399 }
1400 
1401 /// If convert a simple (split, no rejoin) sub-CFG.
1402 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1403   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1404   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1405   BBInfo *CvtBBI = &TrueBBI;
1406   BBInfo *NextBBI = &FalseBBI;
1407 
1408   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1409   if (Kind == ICSimpleFalse)
1410     std::swap(CvtBBI, NextBBI);
1411 
1412   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1413   MachineBasicBlock &NextMBB = *NextBBI->BB;
1414   if (CvtBBI->IsDone ||
1415       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1416     // Something has changed. It's no longer safe to predicate this block.
1417     BBI.IsAnalyzed = false;
1418     CvtBBI->IsAnalyzed = false;
1419     return false;
1420   }
1421 
1422   if (CvtMBB.hasAddressTaken())
1423     // Conservatively abort if-conversion if BB's address is taken.
1424     return false;
1425 
1426   if (Kind == ICSimpleFalse)
1427     if (TII->reverseBranchCondition(Cond))
1428       llvm_unreachable("Unable to reverse branch condition!");
1429 
1430   Redefs.init(*TRI);
1431 
1432   if (MRI->tracksLiveness()) {
1433     // Initialize liveins to the first BB. These are potentiall redefined by
1434     // predicated instructions.
1435     Redefs.addLiveIns(CvtMBB);
1436     Redefs.addLiveIns(NextMBB);
1437   }
1438 
1439   // Remove the branches from the entry so we can add the contents of the true
1440   // block to it.
1441   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1442 
1443   if (CvtMBB.pred_size() > 1) {
1444     // Copy instructions in the true block, predicate them, and add them to
1445     // the entry block.
1446     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1447 
1448     // Keep the CFG updated.
1449     BBI.BB->removeSuccessor(&CvtMBB, true);
1450   } else {
1451     // Predicate the instructions in the true block.
1452     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1453 
1454     // Merge converted block into entry block. The BB to Cvt edge is removed
1455     // by MergeBlocks.
1456     MergeBlocks(BBI, *CvtBBI);
1457   }
1458 
1459   bool IterIfcvt = true;
1460   if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1461     InsertUncondBranch(*BBI.BB, NextMBB, TII);
1462     BBI.HasFallThrough = false;
1463     // Now ifcvt'd block will look like this:
1464     // BB:
1465     // ...
1466     // t, f = cmp
1467     // if t op
1468     // b BBf
1469     //
1470     // We cannot further ifcvt this block because the unconditional branch
1471     // will have to be predicated on the new condition, that will not be
1472     // available if cmp executes.
1473     IterIfcvt = false;
1474   }
1475 
1476   // Update block info. BB can be iteratively if-converted.
1477   if (!IterIfcvt)
1478     BBI.IsDone = true;
1479   InvalidatePreds(*BBI.BB);
1480   CvtBBI->IsDone = true;
1481 
1482   // FIXME: Must maintain LiveIns.
1483   return true;
1484 }
1485 
1486 /// If convert a triangle sub-CFG.
1487 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1488   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1489   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1490   BBInfo *CvtBBI = &TrueBBI;
1491   BBInfo *NextBBI = &FalseBBI;
1492   DebugLoc dl;  // FIXME: this is nowhere
1493 
1494   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1495   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1496     std::swap(CvtBBI, NextBBI);
1497 
1498   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1499   MachineBasicBlock &NextMBB = *NextBBI->BB;
1500   if (CvtBBI->IsDone ||
1501       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1502     // Something has changed. It's no longer safe to predicate this block.
1503     BBI.IsAnalyzed = false;
1504     CvtBBI->IsAnalyzed = false;
1505     return false;
1506   }
1507 
1508   if (CvtMBB.hasAddressTaken())
1509     // Conservatively abort if-conversion if BB's address is taken.
1510     return false;
1511 
1512   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1513     if (TII->reverseBranchCondition(Cond))
1514       llvm_unreachable("Unable to reverse branch condition!");
1515 
1516   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1517     if (reverseBranchCondition(*CvtBBI)) {
1518       // BB has been changed, modify its predecessors (except for this
1519       // one) so they don't get ifcvt'ed based on bad intel.
1520       for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
1521         if (PBB == BBI.BB)
1522           continue;
1523         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1524         if (PBBI.IsEnqueued) {
1525           PBBI.IsAnalyzed = false;
1526           PBBI.IsEnqueued = false;
1527         }
1528       }
1529     }
1530   }
1531 
1532   // Initialize liveins to the first BB. These are potentially redefined by
1533   // predicated instructions.
1534   Redefs.init(*TRI);
1535   if (MRI->tracksLiveness()) {
1536     Redefs.addLiveIns(CvtMBB);
1537     Redefs.addLiveIns(NextMBB);
1538   }
1539 
1540   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1541   BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1542 
1543   if (HasEarlyExit) {
1544     // Get probabilities before modifying CvtMBB and BBI.BB.
1545     CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1546     CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1547     BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1548     BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
1549   }
1550 
1551   // Remove the branches from the entry so we can add the contents of the true
1552   // block to it.
1553   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1554 
1555   if (CvtMBB.pred_size() > 1) {
1556     // Copy instructions in the true block, predicate them, and add them to
1557     // the entry block.
1558     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1559   } else {
1560     // Predicate the 'true' block after removing its branch.
1561     CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
1562     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1563 
1564     // Now merge the entry of the triangle with the true block.
1565     MergeBlocks(BBI, *CvtBBI, false);
1566   }
1567 
1568   // Keep the CFG updated.
1569   BBI.BB->removeSuccessor(&CvtMBB, true);
1570 
1571   // If 'true' block has a 'false' successor, add an exit branch to it.
1572   if (HasEarlyExit) {
1573     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1574                                            CvtBBI->BrCond.end());
1575     if (TII->reverseBranchCondition(RevCond))
1576       llvm_unreachable("Unable to reverse branch condition!");
1577 
1578     // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1579     // NewNext = New_Prob(BBI.BB, NextMBB) =
1580     //   Prob(BBI.BB, NextMBB) +
1581     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1582     // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1583     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1584     auto NewTrueBB = getNextBlock(*BBI.BB);
1585     auto NewNext = BBNext + BBCvt * CvtNext;
1586     auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1587     if (NewTrueBBIter != BBI.BB->succ_end())
1588       BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1589 
1590     auto NewFalse = BBCvt * CvtFalse;
1591     TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1592     BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1593   }
1594 
1595   // Merge in the 'false' block if the 'false' block has no other
1596   // predecessors. Otherwise, add an unconditional branch to 'false'.
1597   bool FalseBBDead = false;
1598   bool IterIfcvt = true;
1599   bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
1600   if (!isFallThrough) {
1601     // Only merge them if the true block does not fallthrough to the false
1602     // block. By not merging them, we make it possible to iteratively
1603     // ifcvt the blocks.
1604     if (!HasEarlyExit &&
1605         NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1606         !NextMBB.hasAddressTaken()) {
1607       MergeBlocks(BBI, *NextBBI);
1608       FalseBBDead = true;
1609     } else {
1610       InsertUncondBranch(*BBI.BB, NextMBB, TII);
1611       BBI.HasFallThrough = false;
1612     }
1613     // Mixed predicated and unpredicated code. This cannot be iteratively
1614     // predicated.
1615     IterIfcvt = false;
1616   }
1617 
1618   // Update block info. BB can be iteratively if-converted.
1619   if (!IterIfcvt)
1620     BBI.IsDone = true;
1621   InvalidatePreds(*BBI.BB);
1622   CvtBBI->IsDone = true;
1623   if (FalseBBDead)
1624     NextBBI->IsDone = true;
1625 
1626   // FIXME: Must maintain LiveIns.
1627   return true;
1628 }
1629 
1630 /// Common code shared between diamond conversions.
1631 /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1632 /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1633 ///               and FalseBBI
1634 /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1635 ///               and \p FalseBBI
1636 /// \p RemoveBranch - Remove the common branch of the two blocks before
1637 ///                   predicating. Only false for unanalyzable fallthrough
1638 ///                   cases. The caller will replace the branch if necessary.
1639 /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1640 ///                    unanalyzable fallthrough
1641 bool IfConverter::IfConvertDiamondCommon(
1642     BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1643     unsigned NumDups1, unsigned NumDups2,
1644     bool TClobbersPred, bool FClobbersPred,
1645     bool RemoveBranch, bool MergeAddEdges) {
1646 
1647   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1648       TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1649     // Something has changed. It's no longer safe to predicate these blocks.
1650     BBI.IsAnalyzed = false;
1651     TrueBBI.IsAnalyzed = false;
1652     FalseBBI.IsAnalyzed = false;
1653     return false;
1654   }
1655 
1656   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1657     // Conservatively abort if-conversion if either BB has its address taken.
1658     return false;
1659 
1660   // Put the predicated instructions from the 'true' block before the
1661   // instructions from the 'false' block, unless the true block would clobber
1662   // the predicate, in which case, do the opposite.
1663   BBInfo *BBI1 = &TrueBBI;
1664   BBInfo *BBI2 = &FalseBBI;
1665   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1666   if (TII->reverseBranchCondition(RevCond))
1667     llvm_unreachable("Unable to reverse branch condition!");
1668   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1669   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1670 
1671   // Figure out the more profitable ordering.
1672   bool DoSwap = false;
1673   if (TClobbersPred && !FClobbersPred)
1674     DoSwap = true;
1675   else if (!TClobbersPred && !FClobbersPred) {
1676     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1677       DoSwap = true;
1678   } else if (TClobbersPred && FClobbersPred)
1679     llvm_unreachable("Predicate info cannot be clobbered by both sides.");
1680   if (DoSwap) {
1681     std::swap(BBI1, BBI2);
1682     std::swap(Cond1, Cond2);
1683   }
1684 
1685   // Remove the conditional branch from entry to the blocks.
1686   BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1687 
1688   MachineBasicBlock &MBB1 = *BBI1->BB;
1689   MachineBasicBlock &MBB2 = *BBI2->BB;
1690 
1691   // Initialize the Redefs:
1692   // - BB2 live-in regs need implicit uses before being redefined by BB1
1693   //   instructions.
1694   // - BB1 live-out regs need implicit uses before being redefined by BB2
1695   //   instructions. We start with BB1 live-ins so we have the live-out regs
1696   //   after tracking the BB1 instructions.
1697   Redefs.init(*TRI);
1698   if (MRI->tracksLiveness()) {
1699     Redefs.addLiveIns(MBB1);
1700     Redefs.addLiveIns(MBB2);
1701   }
1702 
1703   // Remove the duplicated instructions at the beginnings of both paths.
1704   // Skip dbg_value instructions
1705   MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1706   MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
1707   BBI1->NonPredSize -= NumDups1;
1708   BBI2->NonPredSize -= NumDups1;
1709 
1710   // Skip past the dups on each side separately since there may be
1711   // differing dbg_value entries.
1712   for (unsigned i = 0; i < NumDups1; ++DI1) {
1713     if (!DI1->isDebugValue())
1714       ++i;
1715   }
1716   while (NumDups1 != 0) {
1717     ++DI2;
1718     if (!DI2->isDebugValue())
1719       --NumDups1;
1720   }
1721 
1722   if (MRI->tracksLiveness()) {
1723     for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1724       SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Dummy;
1725       Redefs.stepForward(MI, Dummy);
1726     }
1727   }
1728   BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1729   MBB2.erase(MBB2.begin(), DI2);
1730 
1731   // The branches have been checked to match, so it is safe to remove the branch
1732   // in BB1 and rely on the copy in BB2
1733 #ifndef NDEBUG
1734   // Unanalyzable branches must match exactly. Check that now.
1735   if (!BBI1->IsBrAnalyzable)
1736     verifySameBranchInstructions(&MBB1, &MBB2);
1737 #endif
1738   BBI1->NonPredSize -= TII->removeBranch(*BBI1->BB);
1739   // Remove duplicated instructions.
1740   DI1 = MBB1.end();
1741   for (unsigned i = 0; i != NumDups2; ) {
1742     // NumDups2 only counted non-dbg_value instructions, so this won't
1743     // run off the head of the list.
1744     assert(DI1 != MBB1.begin());
1745     --DI1;
1746     // skip dbg_value instructions
1747     if (!DI1->isDebugValue())
1748       ++i;
1749   }
1750   MBB1.erase(DI1, MBB1.end());
1751 
1752   DI2 = BBI2->BB->end();
1753   // The branches have been checked to match. Skip over the branch in the false
1754   // block so that we don't try to predicate it.
1755   if (RemoveBranch)
1756     BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
1757   else {
1758     do {
1759       assert(DI2 != MBB2.begin());
1760       DI2--;
1761     } while (DI2->isBranch() || DI2->isDebugValue());
1762     DI2++;
1763   }
1764   while (NumDups2 != 0) {
1765     // NumDups2 only counted non-dbg_value instructions, so this won't
1766     // run off the head of the list.
1767     assert(DI2 != MBB2.begin());
1768     --DI2;
1769     // skip dbg_value instructions
1770     if (!DI2->isDebugValue())
1771       --NumDups2;
1772   }
1773 
1774   // Remember which registers would later be defined by the false block.
1775   // This allows us not to predicate instructions in the true block that would
1776   // later be re-defined. That is, rather than
1777   //   subeq  r0, r1, #1
1778   //   addne  r0, r1, #1
1779   // generate:
1780   //   sub    r0, r1, #1
1781   //   addne  r0, r1, #1
1782   SmallSet<unsigned, 4> RedefsByFalse;
1783   SmallSet<unsigned, 4> ExtUses;
1784   if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1785     for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
1786       if (FI.isDebugValue())
1787         continue;
1788       SmallVector<unsigned, 4> Defs;
1789       for (const MachineOperand &MO : FI.operands()) {
1790         if (!MO.isReg())
1791           continue;
1792         unsigned Reg = MO.getReg();
1793         if (!Reg)
1794           continue;
1795         if (MO.isDef()) {
1796           Defs.push_back(Reg);
1797         } else if (!RedefsByFalse.count(Reg)) {
1798           // These are defined before ctrl flow reach the 'false' instructions.
1799           // They cannot be modified by the 'true' instructions.
1800           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1801                SubRegs.isValid(); ++SubRegs)
1802             ExtUses.insert(*SubRegs);
1803         }
1804       }
1805 
1806       for (unsigned Reg : Defs) {
1807         if (!ExtUses.count(Reg)) {
1808           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1809                SubRegs.isValid(); ++SubRegs)
1810             RedefsByFalse.insert(*SubRegs);
1811         }
1812       }
1813     }
1814   }
1815 
1816   // Predicate the 'true' block.
1817   PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
1818 
1819   // After predicating BBI1, if there is a predicated terminator in BBI1 and
1820   // a non-predicated in BBI2, then we don't want to predicate the one from
1821   // BBI2. The reason is that if we merged these blocks, we would end up with
1822   // two predicated terminators in the same block.
1823   if (!MBB2.empty() && (DI2 == MBB2.end())) {
1824     MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1825     MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1826     if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1827         BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
1828       --DI2;
1829   }
1830 
1831   // Predicate the 'false' block.
1832   PredicateBlock(*BBI2, DI2, *Cond2);
1833 
1834   // Merge the true block into the entry of the diamond.
1835   MergeBlocks(BBI, *BBI1, MergeAddEdges);
1836   MergeBlocks(BBI, *BBI2, MergeAddEdges);
1837   return true;
1838 }
1839 
1840 /// If convert an almost-diamond sub-CFG where the true
1841 /// and false blocks share a common tail.
1842 bool IfConverter::IfConvertForkedDiamond(
1843     BBInfo &BBI, IfcvtKind Kind,
1844     unsigned NumDups1, unsigned NumDups2,
1845     bool TClobbersPred, bool FClobbersPred) {
1846   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1847   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1848 
1849   // Save the debug location for later.
1850   DebugLoc dl;
1851   MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1852   if (TIE != TrueBBI.BB->end())
1853     dl = TIE->getDebugLoc();
1854   // Removing branches from both blocks is safe, because we have already
1855   // determined that both blocks have the same branch instructions. The branch
1856   // will be added back at the end, unpredicated.
1857   if (!IfConvertDiamondCommon(
1858       BBI, TrueBBI, FalseBBI,
1859       NumDups1, NumDups2,
1860       TClobbersPred, FClobbersPred,
1861       /* RemoveBranch */ true, /* MergeAddEdges */ true))
1862     return false;
1863 
1864   // Add back the branch.
1865   // Debug location saved above when removing the branch from BBI2
1866   TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1867                     TrueBBI.BrCond, dl);
1868 
1869   // Update block info.
1870   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1871   InvalidatePreds(*BBI.BB);
1872 
1873   // FIXME: Must maintain LiveIns.
1874   return true;
1875 }
1876 
1877 /// If convert a diamond sub-CFG.
1878 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1879                                    unsigned NumDups1, unsigned NumDups2,
1880                                    bool TClobbersPred, bool FClobbersPred) {
1881   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1882   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1883   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1884 
1885   // True block must fall through or end with an unanalyzable terminator.
1886   if (!TailBB) {
1887     if (blockAlwaysFallThrough(TrueBBI))
1888       TailBB = FalseBBI.TrueBB;
1889     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1890   }
1891 
1892   if (!IfConvertDiamondCommon(
1893       BBI, TrueBBI, FalseBBI,
1894       NumDups1, NumDups2,
1895       TClobbersPred, FClobbersPred,
1896       /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
1897       /* MergeAddEdges */ TailBB == nullptr))
1898     return false;
1899 
1900   // If the if-converted block falls through or unconditionally branches into
1901   // the tail block, and the tail block does not have other predecessors, then
1902   // fold the tail block in as well. Otherwise, unless it falls through to the
1903   // tail, add a unconditional branch to it.
1904   if (TailBB) {
1905     // We need to remove the edges to the true and false blocks manually since
1906     // we didn't let IfConvertDiamondCommon update the CFG.
1907     BBI.BB->removeSuccessor(TrueBBI.BB);
1908     BBI.BB->removeSuccessor(FalseBBI.BB, true);
1909 
1910     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1911     bool CanMergeTail = !TailBBI.HasFallThrough &&
1912       !TailBBI.BB->hasAddressTaken();
1913     // The if-converted block can still have a predicated terminator
1914     // (e.g. a predicated return). If that is the case, we cannot merge
1915     // it with the tail block.
1916     MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1917     if (TI != BBI.BB->end() && TII->isPredicated(*TI))
1918       CanMergeTail = false;
1919     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1920     // check if there are any other predecessors besides those.
1921     unsigned NumPreds = TailBB->pred_size();
1922     if (NumPreds > 1)
1923       CanMergeTail = false;
1924     else if (NumPreds == 1 && CanMergeTail) {
1925       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1926       if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
1927         CanMergeTail = false;
1928     }
1929     if (CanMergeTail) {
1930       MergeBlocks(BBI, TailBBI);
1931       TailBBI.IsDone = true;
1932     } else {
1933       BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
1934       InsertUncondBranch(*BBI.BB, *TailBB, TII);
1935       BBI.HasFallThrough = false;
1936     }
1937   }
1938 
1939   // Update block info.
1940   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1941   InvalidatePreds(*BBI.BB);
1942 
1943   // FIXME: Must maintain LiveIns.
1944   return true;
1945 }
1946 
1947 static bool MaySpeculate(const MachineInstr &MI,
1948                          SmallSet<unsigned, 4> &LaterRedefs) {
1949   bool SawStore = true;
1950   if (!MI.isSafeToMove(nullptr, SawStore))
1951     return false;
1952 
1953   for (const MachineOperand &MO : MI.operands()) {
1954     if (!MO.isReg())
1955       continue;
1956     unsigned Reg = MO.getReg();
1957     if (!Reg)
1958       continue;
1959     if (MO.isDef() && !LaterRedefs.count(Reg))
1960       return false;
1961   }
1962 
1963   return true;
1964 }
1965 
1966 /// Predicate instructions from the start of the block to the specified end with
1967 /// the specified condition.
1968 void IfConverter::PredicateBlock(BBInfo &BBI,
1969                                  MachineBasicBlock::iterator E,
1970                                  SmallVectorImpl<MachineOperand> &Cond,
1971                                  SmallSet<unsigned, 4> *LaterRedefs) {
1972   bool AnyUnpred = false;
1973   bool MaySpec = LaterRedefs != nullptr;
1974   for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
1975     if (I.isDebugValue() || TII->isPredicated(I))
1976       continue;
1977     // It may be possible not to predicate an instruction if it's the 'true'
1978     // side of a diamond and the 'false' side may re-define the instruction's
1979     // defs.
1980     if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
1981       AnyUnpred = true;
1982       continue;
1983     }
1984     // If any instruction is predicated, then every instruction after it must
1985     // be predicated.
1986     MaySpec = false;
1987     if (!TII->PredicateInstruction(I, Cond)) {
1988 #ifndef NDEBUG
1989       dbgs() << "Unable to predicate " << I << "!\n";
1990 #endif
1991       llvm_unreachable(nullptr);
1992     }
1993 
1994     // If the predicated instruction now redefines a register as the result of
1995     // if-conversion, add an implicit kill.
1996     UpdatePredRedefs(I, Redefs);
1997   }
1998 
1999   BBI.Predicate.append(Cond.begin(), Cond.end());
2000 
2001   BBI.IsAnalyzed = false;
2002   BBI.NonPredSize = 0;
2003 
2004   ++NumIfConvBBs;
2005   if (AnyUnpred)
2006     ++NumUnpred;
2007 }
2008 
2009 /// Copy and predicate instructions from source BB to the destination block.
2010 /// Skip end of block branches if IgnoreBr is true.
2011 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2012                                         SmallVectorImpl<MachineOperand> &Cond,
2013                                         bool IgnoreBr) {
2014   MachineFunction &MF = *ToBBI.BB->getParent();
2015 
2016   MachineBasicBlock &FromMBB = *FromBBI.BB;
2017   for (MachineInstr &I : FromMBB) {
2018     // Do not copy the end of the block branches.
2019     if (IgnoreBr && I.isBranch())
2020       break;
2021 
2022     MachineInstr *MI = MF.CloneMachineInstr(&I);
2023     ToBBI.BB->insert(ToBBI.BB->end(), MI);
2024     ToBBI.NonPredSize++;
2025     unsigned ExtraPredCost = TII->getPredicationCost(I);
2026     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2027     if (NumCycles > 1)
2028       ToBBI.ExtraCost += NumCycles-1;
2029     ToBBI.ExtraCost2 += ExtraPredCost;
2030 
2031     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
2032       if (!TII->PredicateInstruction(*MI, Cond)) {
2033 #ifndef NDEBUG
2034         dbgs() << "Unable to predicate " << I << "!\n";
2035 #endif
2036         llvm_unreachable(nullptr);
2037       }
2038     }
2039 
2040     // If the predicated instruction now redefines a register as the result of
2041     // if-conversion, add an implicit kill.
2042     UpdatePredRedefs(*MI, Redefs);
2043   }
2044 
2045   if (!IgnoreBr) {
2046     std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2047                                            FromMBB.succ_end());
2048     MachineBasicBlock *NBB = getNextBlock(FromMBB);
2049     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2050 
2051     for (MachineBasicBlock *Succ : Succs) {
2052       // Fallthrough edge can't be transferred.
2053       if (Succ == FallThrough)
2054         continue;
2055       ToBBI.BB->addSuccessor(Succ);
2056     }
2057   }
2058 
2059   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2060   ToBBI.Predicate.append(Cond.begin(), Cond.end());
2061 
2062   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2063   ToBBI.IsAnalyzed = false;
2064 
2065   ++NumDupBBs;
2066 }
2067 
2068 /// Move all instructions from FromBB to the end of ToBB.  This will leave
2069 /// FromBB as an empty block, so remove all of its successor edges except for
2070 /// the fall-through edge.  If AddEdges is true, i.e., when FromBBI's branch is
2071 /// being moved, add those successor edges to ToBBI and remove the old edge
2072 /// from ToBBI to FromBBI.
2073 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
2074   MachineBasicBlock &FromMBB = *FromBBI.BB;
2075   assert(!FromMBB.hasAddressTaken() &&
2076          "Removing a BB whose address is taken!");
2077 
2078   // In case FromMBB contains terminators (e.g. return instruction),
2079   // first move the non-terminator instructions, then the terminators.
2080   MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
2081   MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2082   ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
2083 
2084   // If FromBB has non-predicated terminator we should copy it at the end.
2085   if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
2086     ToTI = ToBBI.BB->end();
2087   ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2088 
2089   // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2090   // unknown probabilities into known ones.
2091   // FIXME: This usage is too tricky and in the future we would like to
2092   // eliminate all unknown probabilities in MBB.
2093   if (ToBBI.IsBrAnalyzable)
2094     ToBBI.BB->normalizeSuccProbs();
2095 
2096   SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2097                                                 FromMBB.succ_end());
2098   MachineBasicBlock *NBB = getNextBlock(FromMBB);
2099   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2100   // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2101   // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2102   auto To2FromProb = BranchProbability::getZero();
2103   if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2104     // Remove the old edge but remember the edge probability so we can calculate
2105     // the correct weights on the new edges being added further down.
2106     To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2107     ToBBI.BB->removeSuccessor(&FromMBB);
2108   }
2109 
2110   for (MachineBasicBlock *Succ : FromSuccs) {
2111     // Fallthrough edge can't be transferred.
2112     if (Succ == FallThrough)
2113       continue;
2114 
2115     auto NewProb = BranchProbability::getZero();
2116     if (AddEdges) {
2117       // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2118       // which is a portion of the edge probability from FromMBB to Succ. The
2119       // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2120       // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
2121       NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
2122 
2123       // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2124       // only happens when if-converting a diamond CFG and FromMBB is the
2125       // tail BB.  In this case FromMBB post-dominates ToBBI.BB and hence we
2126       // could just use the probabilities on FromMBB's out-edges when adding
2127       // new successors.
2128       if (!To2FromProb.isZero())
2129         NewProb *= To2FromProb;
2130     }
2131 
2132     FromMBB.removeSuccessor(Succ);
2133 
2134     if (AddEdges) {
2135       // If the edge from ToBBI.BB to Succ already exists, update the
2136       // probability of this edge by adding NewProb to it. An example is shown
2137       // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2138       // don't have to set C as A's successor as it already is. We only need to
2139       // update the edge probability on A->C. Note that B will not be
2140       // immediately removed from A's successors. It is possible that B->D is
2141       // not removed either if D is a fallthrough of B. Later the edge A->D
2142       // (generated here) and B->D will be combined into one edge. To maintain
2143       // correct edge probability of this combined edge, we need to set the edge
2144       // probability of A->B to zero, which is already done above. The edge
2145       // probability on A->D is calculated by scaling the original probability
2146       // on A->B by the probability of B->D.
2147       //
2148       // Before ifcvt:      After ifcvt (assume B->D is kept):
2149       //
2150       //       A                A
2151       //      /|               /|\
2152       //     / B              / B|
2153       //    | /|             |  ||
2154       //    |/ |             |  |/
2155       //    C  D             C  D
2156       //
2157       if (ToBBI.BB->isSuccessor(Succ))
2158         ToBBI.BB->setSuccProbability(
2159             find(ToBBI.BB->successors(), Succ),
2160             MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2161       else
2162         ToBBI.BB->addSuccessor(Succ, NewProb);
2163     }
2164   }
2165 
2166   // Move the now empty FromMBB out of the way to the end of the function so
2167   // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2168   MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2169   if (Last != &FromMBB)
2170     FromMBB.moveAfter(Last);
2171 
2172   // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2173   // we've done above.
2174   if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2175     ToBBI.BB->normalizeSuccProbs();
2176 
2177   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2178   FromBBI.Predicate.clear();
2179 
2180   ToBBI.NonPredSize += FromBBI.NonPredSize;
2181   ToBBI.ExtraCost += FromBBI.ExtraCost;
2182   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2183   FromBBI.NonPredSize = 0;
2184   FromBBI.ExtraCost = 0;
2185   FromBBI.ExtraCost2 = 0;
2186 
2187   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2188   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2189   ToBBI.IsAnalyzed = false;
2190   FromBBI.IsAnalyzed = false;
2191 }
2192 
2193 FunctionPass *
2194 llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
2195   return new IfConverter(std::move(Ftor));
2196 }
2197