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