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