CodeGen: Remove more ilist iterator implicit conversions, NFC
[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                      BranchProbability Prediction) const;
194     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
195                        bool FalseBranch, unsigned &Dups,
196                        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                             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                             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->getIterator();
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                               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                                 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->getIterator();
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 (auto &BB : MF)
952     AnalyzeBlock(&BB, Tokens);
953
954   // Sort to favor more complex ifcvt scheme.
955   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
956 }
957
958 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
959 /// that all the intervening blocks are empty (given BB can fall through to its
960 /// next block).
961 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
962   MachineFunction::iterator PI = BB->getIterator();
963   MachineFunction::iterator I = std::next(PI);
964   MachineFunction::iterator TI = ToBB->getIterator();
965   MachineFunction::iterator E = BB->getParent()->end();
966   while (I != TI) {
967     // Check isSuccessor to avoid case where the next block is empty, but
968     // it's not a successor.
969     if (I == E || !I->empty() || !PI->isSuccessor(&*I))
970       return false;
971     PI = I++;
972   }
973   return true;
974 }
975
976 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
977 /// to determine if it can be if-converted. If predecessor is already enqueued,
978 /// dequeue it!
979 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
980   for (const auto &Predecessor : BB->predecessors()) {
981     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
982     if (PBBI.IsDone || PBBI.BB == BB)
983       continue;
984     PBBI.IsAnalyzed = false;
985     PBBI.IsEnqueued = false;
986   }
987 }
988
989 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
990 ///
991 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
992                                const TargetInstrInfo *TII) {
993   DebugLoc dl;  // FIXME: this is nowhere
994   SmallVector<MachineOperand, 0> NoCond;
995   TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
996 }
997
998 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
999 /// successors.
1000 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
1001   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1002   SmallVector<MachineOperand, 4> Cond;
1003   if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1004     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
1005 }
1006
1007 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1008 /// values defined in MI which are not live/used by MI.
1009 static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
1010   SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1011   Redefs.stepForward(*MI, Clobbers);
1012
1013   // Now add the implicit uses for each of the clobbered values.
1014   for (auto Reg : Clobbers) {
1015     // FIXME: Const cast here is nasty, but better than making StepForward
1016     // take a mutable instruction instead of const.
1017     MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1018     MachineInstr *OpMI = Op.getParent();
1019     MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
1020     if (Op.isRegMask()) {
1021       // First handle regmasks.  They clobber any entries in the mask which
1022       // means that we need a def for those registers.
1023       MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
1024
1025       // We also need to add an implicit def of this register for the later
1026       // use to read from.
1027       // For the register allocator to have allocated a register clobbered
1028       // by the call which is used later, it must be the case that
1029       // the call doesn't return.
1030       MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1031       continue;
1032     }
1033     assert(Op.isReg() && "Register operand required");
1034     if (Op.isDead()) {
1035       // If we found a dead def, but it needs to be live, then remove the dead
1036       // flag.
1037       if (Redefs.contains(Op.getReg()))
1038         Op.setIsDead(false);
1039     }
1040     MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
1041   }
1042 }
1043
1044 /**
1045  * Remove kill flags from operands with a registers in the @p DontKill set.
1046  */
1047 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
1048   for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1049     if (!O->isReg() || !O->isKill())
1050       continue;
1051     if (DontKill.contains(O->getReg()))
1052       O->setIsKill(false);
1053   }
1054 }
1055
1056 /**
1057  * Walks a range of machine instructions and removes kill flags for registers
1058  * in the @p DontKill set.
1059  */
1060 static void RemoveKills(MachineBasicBlock::iterator I,
1061                         MachineBasicBlock::iterator E,
1062                         const LivePhysRegs &DontKill,
1063                         const MCRegisterInfo &MCRI) {
1064   for ( ; I != E; ++I)
1065     RemoveKills(*I, DontKill);
1066 }
1067
1068 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1069 ///
1070 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1071   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1072   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1073   BBInfo *CvtBBI = &TrueBBI;
1074   BBInfo *NextBBI = &FalseBBI;
1075
1076   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1077   if (Kind == ICSimpleFalse)
1078     std::swap(CvtBBI, NextBBI);
1079
1080   if (CvtBBI->IsDone ||
1081       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1082     // Something has changed. It's no longer safe to predicate this block.
1083     BBI.IsAnalyzed = false;
1084     CvtBBI->IsAnalyzed = false;
1085     return false;
1086   }
1087
1088   if (CvtBBI->BB->hasAddressTaken())
1089     // Conservatively abort if-conversion if BB's address is taken.
1090     return false;
1091
1092   if (Kind == ICSimpleFalse)
1093     if (TII->ReverseBranchCondition(Cond))
1094       llvm_unreachable("Unable to reverse branch condition!");
1095
1096   // Initialize liveins to the first BB. These are potentiall redefined by
1097   // predicated instructions.
1098   Redefs.init(TRI);
1099   Redefs.addLiveIns(CvtBBI->BB);
1100   Redefs.addLiveIns(NextBBI->BB);
1101
1102   // Compute a set of registers which must not be killed by instructions in
1103   // BB1: This is everything live-in to BB2.
1104   DontKill.init(TRI);
1105   DontKill.addLiveIns(NextBBI->BB);
1106
1107   if (CvtBBI->BB->pred_size() > 1) {
1108     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1109     // Copy instructions in the true block, predicate them, and add them to
1110     // the entry block.
1111     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1112
1113     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1114     // explicitly remove CvtBBI as a successor.
1115     BBI.BB->removeSuccessor(CvtBBI->BB);
1116   } else {
1117     RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
1118     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1119
1120     // Merge converted block into entry block.
1121     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1122     MergeBlocks(BBI, *CvtBBI);
1123   }
1124
1125   bool IterIfcvt = true;
1126   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1127     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1128     BBI.HasFallThrough = false;
1129     // Now ifcvt'd block will look like this:
1130     // BB:
1131     // ...
1132     // t, f = cmp
1133     // if t op
1134     // b BBf
1135     //
1136     // We cannot further ifcvt this block because the unconditional branch
1137     // will have to be predicated on the new condition, that will not be
1138     // available if cmp executes.
1139     IterIfcvt = false;
1140   }
1141
1142   RemoveExtraEdges(BBI);
1143
1144   // Update block info. BB can be iteratively if-converted.
1145   if (!IterIfcvt)
1146     BBI.IsDone = true;
1147   InvalidatePreds(BBI.BB);
1148   CvtBBI->IsDone = true;
1149
1150   // FIXME: Must maintain LiveIns.
1151   return true;
1152 }
1153
1154 /// Scale down weights to fit into uint32_t. NewTrue is the new weight
1155 /// for successor TrueBB, and NewFalse is the new weight for successor
1156 /// FalseBB.
1157 static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
1158                          MachineBasicBlock *MBB,
1159                          const MachineBasicBlock *TrueBB,
1160                          const MachineBasicBlock *FalseBB,
1161                          const MachineBranchProbabilityInfo *MBPI) {
1162   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1163   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1164   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1165                                         SE = MBB->succ_end();
1166        SI != SE; ++SI) {
1167     if (*SI == TrueBB)
1168       MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
1169     else if (*SI == FalseBB)
1170       MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
1171     else
1172       MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
1173   }
1174 }
1175
1176 /// IfConvertTriangle - If convert a triangle sub-CFG.
1177 ///
1178 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1179   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1180   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1181   BBInfo *CvtBBI = &TrueBBI;
1182   BBInfo *NextBBI = &FalseBBI;
1183   DebugLoc dl;  // FIXME: this is nowhere
1184
1185   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1186   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1187     std::swap(CvtBBI, NextBBI);
1188
1189   if (CvtBBI->IsDone ||
1190       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1191     // Something has changed. It's no longer safe to predicate this block.
1192     BBI.IsAnalyzed = false;
1193     CvtBBI->IsAnalyzed = false;
1194     return false;
1195   }
1196
1197   if (CvtBBI->BB->hasAddressTaken())
1198     // Conservatively abort if-conversion if BB's address is taken.
1199     return false;
1200
1201   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1202     if (TII->ReverseBranchCondition(Cond))
1203       llvm_unreachable("Unable to reverse branch condition!");
1204
1205   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1206     if (ReverseBranchCondition(*CvtBBI)) {
1207       // BB has been changed, modify its predecessors (except for this
1208       // one) so they don't get ifcvt'ed based on bad intel.
1209       for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1210              E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1211         MachineBasicBlock *PBB = *PI;
1212         if (PBB == BBI.BB)
1213           continue;
1214         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1215         if (PBBI.IsEnqueued) {
1216           PBBI.IsAnalyzed = false;
1217           PBBI.IsEnqueued = false;
1218         }
1219       }
1220     }
1221   }
1222
1223   // Initialize liveins to the first BB. These are potentially redefined by
1224   // predicated instructions.
1225   Redefs.init(TRI);
1226   Redefs.addLiveIns(CvtBBI->BB);
1227   Redefs.addLiveIns(NextBBI->BB);
1228
1229   DontKill.clear();
1230
1231   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1232   uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
1233   uint32_t WeightScale = 0;
1234
1235   if (HasEarlyExit) {
1236     // Get weights before modifying CvtBBI->BB and BBI.BB.
1237     CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
1238     CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
1239     BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
1240     BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
1241     SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
1242   }
1243
1244   if (CvtBBI->BB->pred_size() > 1) {
1245     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1246     // Copy instructions in the true block, predicate them, and add them to
1247     // the entry block.
1248     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1249
1250     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1251     // explicitly remove CvtBBI as a successor.
1252     BBI.BB->removeSuccessor(CvtBBI->BB);
1253   } else {
1254     // Predicate the 'true' block after removing its branch.
1255     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1256     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1257
1258     // Now merge the entry of the triangle with the true block.
1259     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1260     MergeBlocks(BBI, *CvtBBI, false);
1261   }
1262
1263   // If 'true' block has a 'false' successor, add an exit branch to it.
1264   if (HasEarlyExit) {
1265     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1266                                            CvtBBI->BrCond.end());
1267     if (TII->ReverseBranchCondition(RevCond))
1268       llvm_unreachable("Unable to reverse branch condition!");
1269     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1270     BBI.BB->addSuccessor(CvtBBI->FalseBB);
1271     // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
1272     // New_Weight(BBI.BB, NextBBI->BB) =
1273     //   Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
1274     //   Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
1275     // New_Weight(BBI.BB, CvtBBI->FalseBB) =
1276     //   Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
1277
1278     uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
1279     uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
1280     // We need to scale down all weights of BBI.BB to fit uint32_t.
1281     // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
1282     // the next block.
1283     ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
1284                  CvtBBI->FalseBB, MBPI);
1285   }
1286
1287   // Merge in the 'false' block if the 'false' block has no other
1288   // predecessors. Otherwise, add an unconditional branch to 'false'.
1289   bool FalseBBDead = false;
1290   bool IterIfcvt = true;
1291   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1292   if (!isFallThrough) {
1293     // Only merge them if the true block does not fallthrough to the false
1294     // block. By not merging them, we make it possible to iteratively
1295     // ifcvt the blocks.
1296     if (!HasEarlyExit &&
1297         NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1298         !NextBBI->BB->hasAddressTaken()) {
1299       MergeBlocks(BBI, *NextBBI);
1300       FalseBBDead = true;
1301     } else {
1302       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1303       BBI.HasFallThrough = false;
1304     }
1305     // Mixed predicated and unpredicated code. This cannot be iteratively
1306     // predicated.
1307     IterIfcvt = false;
1308   }
1309
1310   RemoveExtraEdges(BBI);
1311
1312   // Update block info. BB can be iteratively if-converted.
1313   if (!IterIfcvt)
1314     BBI.IsDone = true;
1315   InvalidatePreds(BBI.BB);
1316   CvtBBI->IsDone = true;
1317   if (FalseBBDead)
1318     NextBBI->IsDone = true;
1319
1320   // FIXME: Must maintain LiveIns.
1321   return true;
1322 }
1323
1324 /// IfConvertDiamond - If convert a diamond sub-CFG.
1325 ///
1326 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1327                                    unsigned NumDups1, unsigned NumDups2) {
1328   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1329   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1330   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1331   // True block must fall through or end with an unanalyzable terminator.
1332   if (!TailBB) {
1333     if (blockAlwaysFallThrough(TrueBBI))
1334       TailBB = FalseBBI.TrueBB;
1335     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1336   }
1337
1338   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1339       TrueBBI.BB->pred_size() > 1 ||
1340       FalseBBI.BB->pred_size() > 1) {
1341     // Something has changed. It's no longer safe to predicate these blocks.
1342     BBI.IsAnalyzed = false;
1343     TrueBBI.IsAnalyzed = false;
1344     FalseBBI.IsAnalyzed = false;
1345     return false;
1346   }
1347
1348   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1349     // Conservatively abort if-conversion if either BB has its address taken.
1350     return false;
1351
1352   // Put the predicated instructions from the 'true' block before the
1353   // instructions from the 'false' block, unless the true block would clobber
1354   // the predicate, in which case, do the opposite.
1355   BBInfo *BBI1 = &TrueBBI;
1356   BBInfo *BBI2 = &FalseBBI;
1357   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1358   if (TII->ReverseBranchCondition(RevCond))
1359     llvm_unreachable("Unable to reverse branch condition!");
1360   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1361   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1362
1363   // Figure out the more profitable ordering.
1364   bool DoSwap = false;
1365   if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1366     DoSwap = true;
1367   else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1368     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1369       DoSwap = true;
1370   }
1371   if (DoSwap) {
1372     std::swap(BBI1, BBI2);
1373     std::swap(Cond1, Cond2);
1374   }
1375
1376   // Remove the conditional branch from entry to the blocks.
1377   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1378
1379   // Initialize liveins to the first BB. These are potentially redefined by
1380   // predicated instructions.
1381   Redefs.init(TRI);
1382   Redefs.addLiveIns(BBI1->BB);
1383
1384   // Remove the duplicated instructions at the beginnings of both paths.
1385   // Skip dbg_value instructions
1386   MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1387   MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
1388   BBI1->NonPredSize -= NumDups1;
1389   BBI2->NonPredSize -= NumDups1;
1390
1391   // Skip past the dups on each side separately since there may be
1392   // differing dbg_value entries.
1393   for (unsigned i = 0; i < NumDups1; ++DI1) {
1394     if (!DI1->isDebugValue())
1395       ++i;
1396   }
1397   while (NumDups1 != 0) {
1398     ++DI2;
1399     if (!DI2->isDebugValue())
1400       --NumDups1;
1401   }
1402
1403   // Compute a set of registers which must not be killed by instructions in BB1:
1404   // This is everything used+live in BB2 after the duplicated instructions. We
1405   // can compute this set by simulating liveness backwards from the end of BB2.
1406   DontKill.init(TRI);
1407   for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1408        E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
1409     DontKill.stepBackward(*I);
1410   }
1411
1412   for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1413        ++I) {
1414     SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1415     Redefs.stepForward(*I, IgnoredClobbers);
1416   }
1417   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1418   BBI2->BB->erase(BBI2->BB->begin(), DI2);
1419
1420   // Remove branch from 'true' block and remove duplicated instructions.
1421   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1422   DI1 = BBI1->BB->end();
1423   for (unsigned i = 0; i != NumDups2; ) {
1424     // NumDups2 only counted non-dbg_value instructions, so this won't
1425     // run off the head of the list.
1426     assert (DI1 != BBI1->BB->begin());
1427     --DI1;
1428     // skip dbg_value instructions
1429     if (!DI1->isDebugValue())
1430       ++i;
1431   }
1432   BBI1->BB->erase(DI1, BBI1->BB->end());
1433
1434   // Kill flags in the true block for registers living into the false block
1435   // must be removed.
1436   RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1437
1438   // Remove 'false' block branch and find the last instruction to predicate.
1439   BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1440   DI2 = BBI2->BB->end();
1441   while (NumDups2 != 0) {
1442     // NumDups2 only counted non-dbg_value instructions, so this won't
1443     // run off the head of the list.
1444     assert (DI2 != BBI2->BB->begin());
1445     --DI2;
1446     // skip dbg_value instructions
1447     if (!DI2->isDebugValue())
1448       --NumDups2;
1449   }
1450
1451   // Remember which registers would later be defined by the false block.
1452   // This allows us not to predicate instructions in the true block that would
1453   // later be re-defined. That is, rather than
1454   //   subeq  r0, r1, #1
1455   //   addne  r0, r1, #1
1456   // generate:
1457   //   sub    r0, r1, #1
1458   //   addne  r0, r1, #1
1459   SmallSet<unsigned, 4> RedefsByFalse;
1460   SmallSet<unsigned, 4> ExtUses;
1461   if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1462     for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1463       if (FI->isDebugValue())
1464         continue;
1465       SmallVector<unsigned, 4> Defs;
1466       for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1467         const MachineOperand &MO = FI->getOperand(i);
1468         if (!MO.isReg())
1469           continue;
1470         unsigned Reg = MO.getReg();
1471         if (!Reg)
1472           continue;
1473         if (MO.isDef()) {
1474           Defs.push_back(Reg);
1475         } else if (!RedefsByFalse.count(Reg)) {
1476           // These are defined before ctrl flow reach the 'false' instructions.
1477           // They cannot be modified by the 'true' instructions.
1478           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1479                SubRegs.isValid(); ++SubRegs)
1480             ExtUses.insert(*SubRegs);
1481         }
1482       }
1483
1484       for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1485         unsigned Reg = Defs[i];
1486         if (!ExtUses.count(Reg)) {
1487           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1488                SubRegs.isValid(); ++SubRegs)
1489             RedefsByFalse.insert(*SubRegs);
1490         }
1491       }
1492     }
1493   }
1494
1495   // Predicate the 'true' block.
1496   PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
1497
1498   // Predicate the 'false' block.
1499   PredicateBlock(*BBI2, DI2, *Cond2);
1500
1501   // Merge the true block into the entry of the diamond.
1502   MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1503   MergeBlocks(BBI, *BBI2, TailBB == nullptr);
1504
1505   // If the if-converted block falls through or unconditionally branches into
1506   // the tail block, and the tail block does not have other predecessors, then
1507   // fold the tail block in as well. Otherwise, unless it falls through to the
1508   // tail, add a unconditional branch to it.
1509   if (TailBB) {
1510     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1511     bool CanMergeTail = !TailBBI.HasFallThrough &&
1512       !TailBBI.BB->hasAddressTaken();
1513     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1514     // check if there are any other predecessors besides those.
1515     unsigned NumPreds = TailBB->pred_size();
1516     if (NumPreds > 1)
1517       CanMergeTail = false;
1518     else if (NumPreds == 1 && CanMergeTail) {
1519       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1520       if (*PI != BBI1->BB && *PI != BBI2->BB)
1521         CanMergeTail = false;
1522     }
1523     if (CanMergeTail) {
1524       MergeBlocks(BBI, TailBBI);
1525       TailBBI.IsDone = true;
1526     } else {
1527       BBI.BB->addSuccessor(TailBB);
1528       InsertUncondBranch(BBI.BB, TailBB, TII);
1529       BBI.HasFallThrough = false;
1530     }
1531   }
1532
1533   // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1534   // which can happen here if TailBB is unanalyzable and is merged, so
1535   // explicitly remove BBI1 and BBI2 as successors.
1536   BBI.BB->removeSuccessor(BBI1->BB);
1537   BBI.BB->removeSuccessor(BBI2->BB);
1538   RemoveExtraEdges(BBI);
1539
1540   // Update block info.
1541   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1542   InvalidatePreds(BBI.BB);
1543
1544   // FIXME: Must maintain LiveIns.
1545   return true;
1546 }
1547
1548 static bool MaySpeculate(const MachineInstr *MI,
1549                          SmallSet<unsigned, 4> &LaterRedefs) {
1550   bool SawStore = true;
1551   if (!MI->isSafeToMove(nullptr, SawStore))
1552     return false;
1553
1554   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1555     const MachineOperand &MO = MI->getOperand(i);
1556     if (!MO.isReg())
1557       continue;
1558     unsigned Reg = MO.getReg();
1559     if (!Reg)
1560       continue;
1561     if (MO.isDef() && !LaterRedefs.count(Reg))
1562       return false;
1563   }
1564
1565   return true;
1566 }
1567
1568 /// PredicateBlock - Predicate instructions from the start of the block to the
1569 /// specified end with the specified condition.
1570 void IfConverter::PredicateBlock(BBInfo &BBI,
1571                                  MachineBasicBlock::iterator E,
1572                                  SmallVectorImpl<MachineOperand> &Cond,
1573                                  SmallSet<unsigned, 4> *LaterRedefs) {
1574   bool AnyUnpred = false;
1575   bool MaySpec = LaterRedefs != nullptr;
1576   for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1577     if (I->isDebugValue() || TII->isPredicated(I))
1578       continue;
1579     // It may be possible not to predicate an instruction if it's the 'true'
1580     // side of a diamond and the 'false' side may re-define the instruction's
1581     // defs.
1582     if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
1583       AnyUnpred = true;
1584       continue;
1585     }
1586     // If any instruction is predicated, then every instruction after it must
1587     // be predicated.
1588     MaySpec = false;
1589     if (!TII->PredicateInstruction(I, Cond)) {
1590 #ifndef NDEBUG
1591       dbgs() << "Unable to predicate " << *I << "!\n";
1592 #endif
1593       llvm_unreachable(nullptr);
1594     }
1595
1596     // If the predicated instruction now redefines a register as the result of
1597     // if-conversion, add an implicit kill.
1598     UpdatePredRedefs(I, Redefs);
1599   }
1600
1601   BBI.Predicate.append(Cond.begin(), Cond.end());
1602
1603   BBI.IsAnalyzed = false;
1604   BBI.NonPredSize = 0;
1605
1606   ++NumIfConvBBs;
1607   if (AnyUnpred)
1608     ++NumUnpred;
1609 }
1610
1611 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1612 /// the destination block. Skip end of block branches if IgnoreBr is true.
1613 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1614                                         SmallVectorImpl<MachineOperand> &Cond,
1615                                         bool IgnoreBr) {
1616   MachineFunction &MF = *ToBBI.BB->getParent();
1617
1618   for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1619          E = FromBBI.BB->end(); I != E; ++I) {
1620     // Do not copy the end of the block branches.
1621     if (IgnoreBr && I->isBranch())
1622       break;
1623
1624     MachineInstr *MI = MF.CloneMachineInstr(I);
1625     ToBBI.BB->insert(ToBBI.BB->end(), MI);
1626     ToBBI.NonPredSize++;
1627     unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1628     unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
1629     if (NumCycles > 1)
1630       ToBBI.ExtraCost += NumCycles-1;
1631     ToBBI.ExtraCost2 += ExtraPredCost;
1632
1633     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1634       if (!TII->PredicateInstruction(MI, Cond)) {
1635 #ifndef NDEBUG
1636         dbgs() << "Unable to predicate " << *I << "!\n";
1637 #endif
1638         llvm_unreachable(nullptr);
1639       }
1640     }
1641
1642     // If the predicated instruction now redefines a register as the result of
1643     // if-conversion, add an implicit kill.
1644     UpdatePredRedefs(MI, Redefs);
1645
1646     // Some kill flags may not be correct anymore.
1647     if (!DontKill.empty())
1648       RemoveKills(*MI, DontKill);
1649   }
1650
1651   if (!IgnoreBr) {
1652     std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1653                                            FromBBI.BB->succ_end());
1654     MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1655     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
1656
1657     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1658       MachineBasicBlock *Succ = Succs[i];
1659       // Fallthrough edge can't be transferred.
1660       if (Succ == FallThrough)
1661         continue;
1662       ToBBI.BB->addSuccessor(Succ);
1663     }
1664   }
1665
1666   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1667   ToBBI.Predicate.append(Cond.begin(), Cond.end());
1668
1669   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1670   ToBBI.IsAnalyzed = false;
1671
1672   ++NumDupBBs;
1673 }
1674
1675 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1676 /// This will leave FromBB as an empty block, so remove all of its
1677 /// successor edges except for the fall-through edge.  If AddEdges is true,
1678 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1679 /// ToBBI.
1680 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1681   assert(!FromBBI.BB->hasAddressTaken() &&
1682          "Removing a BB whose address is taken!");
1683
1684   ToBBI.BB->splice(ToBBI.BB->end(),
1685                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1686
1687   SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1688                                                 FromBBI.BB->succ_end());
1689   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1690   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
1691
1692   // The edge weight from ToBBI.BB to FromBBI.BB, which is only needed when
1693   // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
1694   uint32_t To2FromWeight = 0;
1695   // WeightScale and SumWeight are for calculating successor probabilities of
1696   // FromBBI.BB.
1697   uint32_t WeightScale = 0;
1698   uint32_t SumWeight = 0;
1699   if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
1700     To2FromWeight = MBPI->getEdgeWeight(ToBBI.BB, FromBBI.BB);
1701     // Set the edge weight from ToBBI.BB to FromBBI.BB to zero to avoid the edge
1702     // weight being merged to other edges when this edge is removed later.
1703     ToBBI.BB->setSuccWeight(
1704         std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB), 0);
1705     SumWeight = MBPI->getSumForBlock(FromBBI.BB, WeightScale);
1706   }
1707
1708   for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1709     MachineBasicBlock *Succ = FromSuccs[i];
1710     // Fallthrough edge can't be transferred.
1711     if (Succ == FallThrough)
1712       continue;
1713
1714     uint32_t NewWeight = 0;
1715     if (AddEdges) {
1716       // Calculate the edge weight for the edge from ToBBI.BB to Succ, which is
1717       // a portion of the edge weight from FromBBI.BB to Succ. The portion ratio
1718       // is the edge probability from ToBBI.BB to FromBBI.BB (if FromBBI is a
1719       // successor of ToBBI.BB. See comment below for excepion).
1720       NewWeight = MBPI->getEdgeWeight(FromBBI.BB, Succ);
1721
1722       // To2FromWeight is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
1723       // only happens when if-converting a diamond CFG and FromBBI.BB is the
1724       // tail BB.  In this case FromBBI.BB post-dominates ToBBI.BB and hence we
1725       // could just use the weights on FromBBI.BB's out-edges when adding new
1726       // successors.
1727       if (To2FromWeight > 0) {
1728         BranchProbability Prob(NewWeight / WeightScale, SumWeight);
1729         NewWeight = Prob.scale(To2FromWeight);
1730       }
1731     }
1732
1733     FromBBI.BB->removeSuccessor(Succ);
1734
1735     if (AddEdges) {
1736       // If the edge from ToBBI.BB to Succ already exists, update the weight of
1737       // this edge by adding NewWeight to it. An example is shown below, in
1738       // which A is ToBBI.BB and B is FromBBI.BB. In this case we don't have to
1739       // set C as A's successor as it already is. We only need to update the
1740       // edge weight on A->C. Note that B will not be immediately removed from
1741       // A's successors. It is possible that B->D is not removed either if D is
1742       // a fallthrough of B. Later the edge A->D (generated here) and B->D will
1743       // be combined into one edge. To maintain correct edge weight of this
1744       // combined edge, we need to set the edge weight of A->B to zero, which is
1745       // already done above. The edge weight on A->D is calculated by scaling
1746       // the original weight on A->B by the probability of B->D.
1747       //
1748       // Before ifcvt:      After ifcvt (assume B->D is kept):
1749       //
1750       //       A                A
1751       //      /|               /|\
1752       //     / B              / B|
1753       //    | /|             |  ||
1754       //    |/ |             |  |/
1755       //    C  D             C  D
1756       //
1757       if (ToBBI.BB->isSuccessor(Succ))
1758         ToBBI.BB->setSuccWeight(
1759             std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
1760             MBPI->getEdgeWeight(ToBBI.BB, Succ) + NewWeight);
1761       else
1762         ToBBI.BB->addSuccessor(Succ, NewWeight);
1763     }
1764   }
1765
1766   // Now FromBBI always falls through to the next block!
1767   if (NBB && !FromBBI.BB->isSuccessor(NBB))
1768     FromBBI.BB->addSuccessor(NBB);
1769
1770   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1771   FromBBI.Predicate.clear();
1772
1773   ToBBI.NonPredSize += FromBBI.NonPredSize;
1774   ToBBI.ExtraCost += FromBBI.ExtraCost;
1775   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1776   FromBBI.NonPredSize = 0;
1777   FromBBI.ExtraCost = 0;
1778   FromBBI.ExtraCost2 = 0;
1779
1780   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1781   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1782   ToBBI.IsAnalyzed = false;
1783   FromBBI.IsAnalyzed = false;
1784 }
1785
1786 FunctionPass *
1787 llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1788   return new IfConverter(Ftor);
1789 }