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