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