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