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