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