IfConversion.cpp revision a2acf840a70c273a03ffb5752221350b4949fc0e
1//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the Evan Cheng and is distributed under
6// the University of Illinois Open Source 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/Function.h"
16#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineModuleInfo.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/Target/TargetInstrInfo.h"
20#include "llvm/Target/TargetLowering.h"
21#include "llvm/Target/TargetMachine.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/Statistic.h"
26using namespace llvm;
27
28namespace {
29  // Hidden options for help debugging.
30  cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31  cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32  cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33  cl::opt<bool> DisableSimple("disable-ifcvt-simple",
34                              cl::init(false), cl::Hidden);
35  cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
36                               cl::init(false), cl::Hidden);
37  cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
38                                cl::init(false), cl::Hidden);
39  cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
40                                 cl::init(false), cl::Hidden);
41  cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
42                                 cl::init(false), cl::Hidden);
43  cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
44                                  cl::init(false), cl::Hidden);
45  cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
46                               cl::init(false), cl::Hidden);
47}
48
49STATISTIC(NumSimple,       "Number of simple if-conversions performed");
50STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
51STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
52STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
53STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
54STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
55STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
56STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
57STATISTIC(NumDupBBs,       "Number of duplicated blocks");
58
59namespace {
60  class IfConverter : public MachineFunctionPass {
61    enum BBICKind {
62      ICNotClassfied,  // BB data valid, but not classified.
63      ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
64      ICSimpleFalse,   // Same as ICSimple, but on the false path.
65      ICTriangle,      // BB is entry of a triangle sub-CFG.
66      ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
67      ICTriangleFalse, // Same as ICTriangle, but on the false path.
68      ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
69      ICDiamond        // BB is entry of a diamond sub-CFG.
70    };
71
72    /// BBInfo - One per MachineBasicBlock, this is used to cache the result
73    /// if-conversion feasibility analysis. This includes results from
74    /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
75    /// classification, and common tail block of its successors (if it's a
76    /// diamond shape), its size, whether it's predicable, and whether any
77    /// instruction can clobber the 'would-be' predicate.
78    ///
79    /// Kind            - Type of block. See BBICKind.
80    /// IsDone          - True if BB is not to be considered for ifcvt.
81    /// IsBeingAnalyzed - True if BB is currently being analyzed.
82    /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
83    /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
84    /// IsBrAnalyzable  - True if AnalyzeBranch() returns false.
85    /// HasFallThrough  - True if BB may fallthrough to the following BB.
86    /// IsUnpredicable  - True if BB is known to be unpredicable.
87    /// ClobbersPredicate- True if BB would modify the predicate (e.g. has
88    ///                   cmp, call, etc.)
89    /// NonPredSize     - Number of non-predicated instructions.
90    /// BB              - Corresponding MachineBasicBlock.
91    /// TrueBB / FalseBB- See AnalyzeBranch().
92    /// BrCond          - Conditions for end of block conditional branches.
93    /// Predicate       - Predicate used in the BB.
94    struct BBInfo {
95      BBICKind Kind;
96      bool IsDone          : 1;
97      bool IsBeingAnalyzed : 1;
98      bool IsAnalyzed      : 1;
99      bool IsEnqueued      : 1;
100      bool IsBrAnalyzable  : 1;
101      bool HasFallThrough  : 1;
102      bool IsUnpredicable  : 1;
103      bool CannotBeCopied  : 1;
104      bool ClobbersPred    : 1;
105      unsigned NonPredSize;
106      MachineBasicBlock *BB;
107      MachineBasicBlock *TrueBB;
108      MachineBasicBlock *FalseBB;
109      MachineBasicBlock *TailBB;
110      std::vector<MachineOperand> BrCond;
111      std::vector<MachineOperand> Predicate;
112      BBInfo() : Kind(ICNotClassfied), IsDone(false), IsBeingAnalyzed(false),
113                 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
114                 HasFallThrough(false), IsUnpredicable(false),
115                 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
116                 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
117    };
118
119    /// Roots - Basic blocks that do not have successors. These are the starting
120    /// points of Graph traversal.
121    std::vector<MachineBasicBlock*> Roots;
122
123    /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
124    /// basic block number.
125    std::vector<BBInfo> BBAnalysis;
126
127    const TargetLowering *TLI;
128    const TargetInstrInfo *TII;
129    bool MadeChange;
130  public:
131    static char ID;
132    IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
133
134    virtual bool runOnMachineFunction(MachineFunction &MF);
135    virtual const char *getPassName() const { return "If converter"; }
136
137  private:
138    bool ReverseBranchCondition(BBInfo &BBI);
139    bool ValidSimple(BBInfo &TrueBBI) const;
140    bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
141                       bool FalseBranch = false) const;
142    bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
143    void ScanInstructions(BBInfo &BBI);
144    BBInfo &AnalyzeBlock(MachineBasicBlock *BB);
145    bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
146                             bool isTriangle = false, bool RevBranch = false);
147    bool AttemptRestructuring(BBInfo &BBI);
148    bool AnalyzeBlocks(MachineFunction &MF,
149                       std::vector<BBInfo*> &Candidates);
150    void ReTryPreds(MachineBasicBlock *BB);
151    void RemoveExtraEdges(BBInfo &BBI);
152    bool IfConvertSimple(BBInfo &BBI);
153    bool IfConvertTriangle(BBInfo &BBI);
154    bool IfConvertDiamond(BBInfo &BBI);
155    void PredicateBlock(BBInfo &BBI,
156                        std::vector<MachineOperand> &Cond,
157                        bool IgnoreTerm = false);
158    void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
159                               std::vector<MachineOperand> &Cond,
160                               bool IgnoreBr = false);
161    void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
162
163    // blockAlwaysFallThrough - Block ends without a terminator.
164    bool blockAlwaysFallThrough(BBInfo &BBI) const {
165      return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
166    }
167
168    // IfcvtCandidateCmp - Used to sort if-conversion candidates.
169    static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
170      // Favor diamond over triangle, etc.
171      return (unsigned)C1->Kind < (unsigned)C2->Kind;
172    }
173  };
174  char IfConverter::ID = 0;
175}
176
177FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
178
179bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
180  TLI = MF.getTarget().getTargetLowering();
181  TII = MF.getTarget().getInstrInfo();
182  if (!TII) return false;
183
184  static int FnNum = -1;
185  DOUT << "\nIfcvt: function (" << ++FnNum <<  ") \'"
186       << MF.getFunction()->getName() << "\'";
187
188  if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
189    DOUT << " skipped\n";
190    return false;
191  }
192  DOUT << "\n";
193
194  MF.RenumberBlocks();
195  BBAnalysis.resize(MF.getNumBlockIDs());
196
197  // Look for root nodes, i.e. blocks without successors.
198  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
199    if (I->succ_size() == 0)
200      Roots.push_back(I);
201
202  std::vector<BBInfo*> Candidates;
203  MadeChange = false;
204  unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
205    NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
206  while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
207    // Do an intial analysis for each basic block and finding all the potential
208    // candidates to perform if-convesion.
209    bool Change = AnalyzeBlocks(MF, Candidates);
210    while (!Candidates.empty()) {
211      BBInfo &BBI = *Candidates.back();
212      Candidates.pop_back();
213
214      // If the block has been evicted out of the queue or it has already been
215      // marked dead (due to it being predicated), then skip it.
216      if (!BBI.IsEnqueued || BBI.IsDone)
217        continue;
218      BBI.IsEnqueued = false;
219
220      bool RetVal = false;
221      switch (BBI.Kind) {
222      default: assert(false && "Unexpected!");
223        break;
224      case ICSimple:
225      case ICSimpleFalse: {
226        bool isFalse = BBI.Kind == ICSimpleFalse;
227        if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
228        DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
229             << "): BB#" << BBI.BB->getNumber() << " ("
230             << ((BBI.Kind == ICSimpleFalse)
231                 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
232        RetVal = IfConvertSimple(BBI);
233        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
234        if (RetVal)
235          if (isFalse) NumSimpleFalse++;
236          else         NumSimple++;
237       break;
238      }
239      case ICTriangle:
240      case ICTriangleRev:
241      case ICTriangleFalse:
242      case ICTriangleFRev: {
243        bool isFalse    = BBI.Kind == ICTriangleFalse;
244        bool isRev      = (BBI.Kind == ICTriangleRev || BBI.Kind == ICTriangleFRev);
245        if (DisableTriangle && !isFalse && !isRev) break;
246        if (DisableTriangleR && !isFalse && isRev) break;
247        if (DisableTriangleF && isFalse && !isRev) break;
248        if (DisableTriangleFR && isFalse && isRev) break;
249        DOUT << "Ifcvt (Triangle";
250        if (isFalse)
251          DOUT << " false";
252        if (isRev)
253          DOUT << " rev";
254        DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
255             << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
256             << ") ";
257        RetVal = IfConvertTriangle(BBI);
258        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
259        if (RetVal) {
260          if (isFalse) {
261            if (isRev) NumTriangleFRev++;
262            else       NumTriangleFalse++;
263          } else {
264            if (isRev) NumTriangleRev++;
265            else       NumTriangle++;
266          }
267        }
268        break;
269      }
270      case ICDiamond:
271        if (DisableDiamond) break;
272        DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
273             << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
274        if (BBI.TailBB)
275          DOUT << "," << BBI.TailBB->getNumber() ;
276        DOUT << ") ";
277        RetVal = IfConvertDiamond(BBI);
278        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
279        if (RetVal) NumDiamonds++;
280        break;
281      }
282      Change |= RetVal;
283
284      NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
285        NumTriangleFalse + NumTriangleFRev + NumDiamonds;
286      if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
287        break;
288    }
289
290    if (!Change)
291      break;
292    MadeChange |= Change;
293  }
294
295  Roots.clear();
296  BBAnalysis.clear();
297
298  return MadeChange;
299}
300
301static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
302                                         MachineBasicBlock *TrueBB) {
303  for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
304         E = BB->succ_end(); SI != E; ++SI) {
305    MachineBasicBlock *SuccBB = *SI;
306    if (SuccBB != TrueBB)
307      return SuccBB;
308  }
309  return NULL;
310}
311
312bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
313  if (!TII->ReverseBranchCondition(BBI.BrCond)) {
314    TII->RemoveBranch(*BBI.BB);
315    TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
316    std::swap(BBI.TrueBB, BBI.FalseBB);
317    return true;
318  }
319  return false;
320}
321
322/// getNextBlock - Returns the next block in the function blocks ordering. If
323/// it is the end, returns NULL.
324static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
325  MachineFunction::iterator I = BB;
326  MachineFunction::iterator E = BB->getParent()->end();
327  if (++I == E)
328    return NULL;
329  return I;
330}
331
332/// ValidSimple - Returns true if the 'true' block (along with its
333/// predecessor) forms a valid simple shape for ifcvt.
334bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
335  if (TrueBBI.IsBeingAnalyzed)
336    return false;
337
338  if (TrueBBI.BB->pred_size() > 1) {
339    if (TrueBBI.CannotBeCopied ||
340        TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
341      return false;
342  }
343
344  return !blockAlwaysFallThrough(TrueBBI) && TrueBBI.BrCond.size() == 0;
345}
346
347/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
348/// with their common predecessor) forms a valid triangle shape for ifcvt.
349bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
350                                bool FalseBranch) const {
351  if (TrueBBI.IsBeingAnalyzed)
352    return false;
353
354  if (TrueBBI.BB->pred_size() > 1) {
355    if (TrueBBI.CannotBeCopied)
356      return false;
357
358    unsigned Size = TrueBBI.NonPredSize;
359    if (TrueBBI.FalseBB)
360      ++Size;
361    if (Size > TLI->getIfCvtDupBlockSizeLimit())
362      return false;
363  }
364
365  MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
366  if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
367    MachineFunction::iterator I = TrueBBI.BB;
368    if (++I == TrueBBI.BB->getParent()->end())
369      return false;
370    TExit = I;
371  }
372  return TExit && TExit == FalseBBI.BB;
373}
374
375/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
376/// with their common predecessor) forms a valid diamond shape for ifcvt.
377bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
378  if (TrueBBI.IsBeingAnalyzed || FalseBBI.IsBeingAnalyzed)
379    return false;
380
381  MachineBasicBlock *TT = TrueBBI.TrueBB;
382  MachineBasicBlock *FT = FalseBBI.TrueBB;
383
384  if (!TT && blockAlwaysFallThrough(TrueBBI))
385    TT = getNextBlock(TrueBBI.BB);
386  if (!FT && blockAlwaysFallThrough(FalseBBI))
387    FT = getNextBlock(FalseBBI.BB);
388  if (TT != FT)
389    return false;
390  if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
391    return false;
392  // FIXME: Allow false block to have an early exit?
393  return (TrueBBI.BB->pred_size() == 1 &&
394          FalseBBI.BB->pred_size() == 1 &&
395          !TrueBBI.FalseBB && !FalseBBI.FalseBB);
396}
397
398/// ScanInstructions - Scan all the instructions in the block to determine if
399/// the block is predicable. In most cases, that means all the instructions
400/// in the block has M_PREDICABLE flag. Also checks if the block contains any
401/// instruction which can clobber a predicate (e.g. condition code register).
402/// If so, the block is not predicable unless it's the last instruction.
403void IfConverter::ScanInstructions(BBInfo &BBI) {
404  if (BBI.IsDone)
405    return;
406
407  // First analyze the end of BB branches.
408  BBI.TrueBB = BBI.FalseBB = NULL;
409  BBI.BrCond.clear();
410  BBI.IsBrAnalyzable =
411    !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
412  BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
413
414  if (BBI.BrCond.size()) {
415    // No false branch. This BB must end with a conditional branch and a
416    // fallthrough.
417    if (!BBI.FalseBB)
418      BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
419    assert(BBI.FalseBB && "Expected to find the fallthrough block!");
420  }
421
422  // Then scan all the instructions.
423  BBI.NonPredSize = 0;
424  BBI.ClobbersPred = false;
425  bool SeenCondBr = false;
426  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
427       I != E; ++I) {
428    if (!BBI.CannotBeCopied && !TII->CanBeDuplicated(I))
429      BBI.CannotBeCopied = true;
430
431    const TargetInstrDescriptor *TID = I->getInstrDescriptor();
432    bool isPredicated = TII->isPredicated(I);
433    bool isCondBr = BBI.IsBrAnalyzable &&
434      (TID->Flags & M_BRANCH_FLAG) != 0 && (TID->Flags & M_BARRIER_FLAG) == 0;
435
436    if (!isPredicated && !isCondBr)
437      BBI.NonPredSize++;
438
439    if (BBI.ClobbersPred && !isPredicated) {
440      // Predicate modification instruction should end the block (except for
441      // already predicated instructions and end of block branches).
442      if (isCondBr) {
443        SeenCondBr = true;
444
445        // Conditional branches is not predicable. But it may be eliminated.
446        continue;
447      }
448
449      // Predicate may have been modified, the subsequent (currently)
450      // unpredocated instructions cannot be correctly predicated.
451      BBI.IsUnpredicable = true;
452      return;
453    }
454
455    if (TID->Flags & M_CLOBBERS_PRED)
456      BBI.ClobbersPred = true;
457
458    if ((TID->Flags & M_PREDICABLE) == 0) {
459      BBI.IsUnpredicable = true;
460      return;
461    }
462  }
463}
464
465/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
466/// predicated by the specified predicate.
467bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
468                                      std::vector<MachineOperand> &Pred,
469                                      bool isTriangle, bool RevBranch) {
470  // Forget about it if it's unpredicable.
471  if (BBI.IsUnpredicable)
472    return false;
473
474  // If the block is dead, or it is going to be the entry block of a sub-CFG
475  // that will be if-converted, then it cannot be predicated.
476  if (BBI.IsDone || BBI.IsEnqueued)
477    return false;
478
479  // Check predication threshold.
480  if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
481    return false;
482
483  // If it is already predicated, check if its predicate subsumes the new
484  // predicate.
485  if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
486    return false;
487
488  if (BBI.BrCond.size()) {
489    if (!isTriangle)
490      return false;
491
492    // Test predicate subsumsion.
493    std::vector<MachineOperand> RevPred(Pred);
494    std::vector<MachineOperand> Cond(BBI.BrCond);
495    if (RevBranch) {
496      if (TII->ReverseBranchCondition(Cond))
497        return false;
498    }
499    if (TII->ReverseBranchCondition(RevPred) ||
500        !TII->SubsumesPredicate(Cond, RevPred))
501      return false;
502  }
503
504  return true;
505}
506
507/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
508/// the specified block. Record its successors and whether it looks like an
509/// if-conversion candidate.
510IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
511  BBInfo &BBI = BBAnalysis[BB->getNumber()];
512
513  if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
514    return BBI;
515
516  BBI.BB = BB;
517  BBI.IsBeingAnalyzed = true;
518  BBI.Kind = ICNotClassfied;
519
520  ScanInstructions(BBI);
521
522  // Unanalyable or ends with fallthrough or unconditional branch.
523  if (!BBI.IsBrAnalyzable || BBI.BrCond.size() == 0) {
524    BBI.IsBeingAnalyzed = false;
525    BBI.IsAnalyzed = true;
526    return BBI;
527  }
528
529  // Do not ifcvt if either path is a back edge to the entry block.
530  if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
531    BBI.IsBeingAnalyzed = false;
532    BBI.IsAnalyzed = true;
533    return BBI;
534  }
535
536  BBInfo &TrueBBI  = AnalyzeBlock(BBI.TrueBB);
537  BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB);
538
539  if (TrueBBI.IsDone && FalseBBI.IsDone) {
540    BBI.IsBeingAnalyzed = false;
541    BBI.IsAnalyzed = true;
542    return BBI;
543  }
544
545  std::vector<MachineOperand> RevCond(BBI.BrCond);
546  bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
547
548  if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
549      !(TrueBBI.ClobbersPred && FalseBBI.ClobbersPred) &&
550      FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
551      FeasibilityAnalysis(FalseBBI, RevCond)) {
552    // Diamond:
553    //   EBB
554    //   / \_
555    //  |   |
556    // TBB FBB
557    //   \ /
558    //  TailBB
559    // Note TailBB can be empty.
560    BBI.Kind = ICDiamond;
561    BBI.TailBB = TrueBBI.TrueBB;
562  } else {
563    // FIXME: Consider duplicating if BB is small.
564    if (ValidTriangle(TrueBBI, FalseBBI) &&
565        FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
566      // Triangle:
567      //   EBB
568      //   | \_
569      //   |  |
570      //   | TBB
571      //   |  /
572      //   FBB
573      BBI.Kind = ICTriangle;
574    } else if (ValidTriangle(TrueBBI, FalseBBI, true) &&
575               FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
576      BBI.Kind = ICTriangleRev;
577    } else if (ValidSimple(TrueBBI) &&
578               FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
579      // Simple (split, no rejoin):
580      //   EBB
581      //   | \_
582      //   |  |
583      //   | TBB---> exit
584      //   |
585      //   FBB
586      BBI.Kind = ICSimple;
587    } else if (CanRevCond) {
588      // Try the other path...
589      if (ValidTriangle(FalseBBI, TrueBBI) &&
590          FeasibilityAnalysis(FalseBBI, RevCond, true)) {
591        BBI.Kind = ICTriangleFalse;
592      } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
593                 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
594        BBI.Kind = ICTriangleFRev;
595      } else if (ValidSimple(FalseBBI) &&
596                 FeasibilityAnalysis(FalseBBI, RevCond)) {
597        BBI.Kind = ICSimpleFalse;
598      }
599    }
600  }
601
602  BBI.IsBeingAnalyzed = false;
603  BBI.IsAnalyzed = true;
604  return BBI;
605}
606
607/// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
608/// expose more if-conversion opportunities. e.g.
609///
610///                cmp
611///                b le BB1
612///                /  \____
613///               /        |
614///             cmp        |
615///             b eq BB1   |
616///              /  \____  |
617///             /        \ |
618///                      BB1
619///  ==>
620///
621///                cmp
622///                b eq BB1
623///                /  \____
624///               /        |
625///             cmp        |
626///             b le BB1   |
627///              /  \____  |
628///             /        \ |
629///                      BB1
630bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
631  return false;
632}
633
634/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
635/// candidates. It returns true if any CFG restructuring is done to expose more
636/// if-conversion opportunities.
637bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
638                                std::vector<BBInfo*> &Candidates) {
639  bool Change = false;
640  std::set<MachineBasicBlock*> Visited;
641  for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
642    for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
643           E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
644      MachineBasicBlock *BB = *I;
645      BBInfo &BBI = AnalyzeBlock(BB);
646      switch (BBI.Kind) {
647        case ICSimple:
648        case ICSimpleFalse:
649        case ICTriangle:
650        case ICTriangleRev:
651        case ICTriangleFalse:
652        case ICTriangleFRev:
653        case ICDiamond:
654          BBI.IsEnqueued = true;
655          Candidates.push_back(&BBI);
656          break;
657        default:
658          Change |= AttemptRestructuring(BBI);
659          break;
660      }
661    }
662  }
663
664  // Sort to favor more complex ifcvt scheme.
665  std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
666
667  return Change;
668}
669
670/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
671/// that all the intervening blocks are empty (given BB can fall through to its
672/// next block).
673static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
674  MachineFunction::iterator I = BB;
675  MachineFunction::iterator TI = ToBB;
676  MachineFunction::iterator E = BB->getParent()->end();
677  while (++I != TI)
678    if (I == E || !I->empty())
679      return false;
680  return true;
681}
682
683/// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
684/// to determine if it can be if-converted. If predecessor is already
685/// enqueud, dequeue it!
686void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
687  for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
688         E = BB->pred_end(); PI != E; ++PI) {
689    BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
690    if (PBBI.IsDone || PBBI.BB == BB)
691      continue;
692    PBBI.Kind = ICNotClassfied;
693    PBBI.IsAnalyzed = false;
694    PBBI.IsEnqueued = false;
695  }
696}
697
698/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
699///
700static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
701                               const TargetInstrInfo *TII) {
702  std::vector<MachineOperand> NoCond;
703  TII->InsertBranch(*BB, ToBB, NULL, NoCond);
704}
705
706/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
707/// successors.
708void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
709  MachineBasicBlock *TBB = NULL, *FBB = NULL;
710  std::vector<MachineOperand> Cond;
711  bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
712  bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
713  if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
714    if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
715          (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
716      BBI.BB->removeSuccessor(BBI.TrueBB);
717  if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
718    if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
719          (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
720      BBI.BB->removeSuccessor(BBI.FalseBB);
721}
722
723/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
724///
725bool IfConverter::IfConvertSimple(BBInfo &BBI) {
726  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
727  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
728  BBInfo *CvtBBI = &TrueBBI;
729  BBInfo *NextBBI = &FalseBBI;
730
731  std::vector<MachineOperand> Cond(BBI.BrCond);
732  if (BBI.Kind == ICSimpleFalse)
733    std::swap(CvtBBI, NextBBI);
734
735  if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
736    // Something has changed. It's no longer safe to predicate this block.
737    BBI.Kind = ICNotClassfied;
738    BBI.IsAnalyzed = false;
739    CvtBBI->IsAnalyzed = false;
740    return false;
741  }
742
743  if (BBI.Kind == ICSimpleFalse)
744    TII->ReverseBranchCondition(Cond);
745
746  if (CvtBBI->BB->pred_size() > 1) {
747    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
748    // Copy instructions in the true block, predicate them add them to
749    // the entry block.
750    CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
751  } else {
752    PredicateBlock(*CvtBBI, Cond);
753
754    // Merge converted block into entry block.
755    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
756    MergeBlocks(BBI, *CvtBBI);
757  }
758
759  bool IterIfcvt = true;
760  if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
761    InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
762    BBI.HasFallThrough = false;
763    // Now ifcvt'd block will look like this:
764    // BB:
765    // ...
766    // t, f = cmp
767    // if t op
768    // b BBf
769    //
770    // We cannot further ifcvt this block because the unconditional branch
771    // will have to be predicated on the new condition, that will not be
772    // available if cmp executes.
773    IterIfcvt = false;
774  }
775
776  RemoveExtraEdges(BBI);
777
778  // Update block info. BB can be iteratively if-converted.
779  if (!IterIfcvt)
780    BBI.IsDone = true;
781  ReTryPreds(BBI.BB);
782  CvtBBI->IsDone = true;
783
784  // FIXME: Must maintain LiveIns.
785  return true;
786}
787
788/// IfConvertTriangle - If convert a triangle sub-CFG.
789///
790bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
791  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
792  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
793  BBInfo *CvtBBI = &TrueBBI;
794  BBInfo *NextBBI = &FalseBBI;
795
796  std::vector<MachineOperand> Cond(BBI.BrCond);
797  if (BBI.Kind == ICTriangleFalse || BBI.Kind == ICTriangleFRev)
798    std::swap(CvtBBI, NextBBI);
799
800  if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
801    // Something has changed. It's no longer safe to predicate this block.
802    BBI.Kind = ICNotClassfied;
803    BBI.IsAnalyzed = false;
804    CvtBBI->IsAnalyzed = false;
805    return false;
806  }
807
808  if (BBI.Kind == ICTriangleFalse || BBI.Kind == ICTriangleFRev)
809    TII->ReverseBranchCondition(Cond);
810
811  if (BBI.Kind == ICTriangleRev || BBI.Kind == ICTriangleFRev) {
812    ReverseBranchCondition(*CvtBBI);
813    // BB has been changed, modify its predecessors (except for this
814    // one) so they don't get ifcvt'ed based on bad intel.
815    for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
816           E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
817      MachineBasicBlock *PBB = *PI;
818      if (PBB == BBI.BB)
819        continue;
820      BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
821      if (PBBI.IsEnqueued) {
822        PBBI.Kind = ICNotClassfied;
823        PBBI.IsAnalyzed = false;
824        PBBI.IsEnqueued = false;
825      }
826    }
827  }
828
829  bool HasEarlyExit = CvtBBI->FalseBB != NULL;
830  bool DupBB = CvtBBI->BB->pred_size() > 1;
831  if (DupBB) {
832    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
833    // Copy instructions in the true block, predicate them add them to
834    // the entry block.
835    CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
836  } else {
837    // Predicate the 'true' block after removing its branch.
838    CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
839    PredicateBlock(*CvtBBI, Cond);
840  }
841
842  // If 'true' block has a 'false' successor, add an exit branch to it.
843  if (HasEarlyExit) {
844    std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
845    if (TII->ReverseBranchCondition(RevCond))
846      assert(false && "Unable to reverse branch condition!");
847    if (DupBB) {
848      TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
849      BBI.BB->addSuccessor(CvtBBI->FalseBB);
850    } else {
851      TII->InsertBranch(*CvtBBI->BB, CvtBBI->FalseBB, NULL, RevCond);
852    }
853  }
854
855  if (!DupBB) {
856    // Now merge the entry of the triangle with the true block.
857    BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
858    MergeBlocks(BBI, *CvtBBI);
859  }
860
861  // Merge in the 'false' block if the 'false' block has no other
862  // predecessors. Otherwise, add a unconditional branch from to 'false'.
863  bool FalseBBDead = false;
864  bool IterIfcvt = true;
865  bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
866  if (!isFallThrough) {
867    // Only merge them if the true block does not fallthrough to the false
868    // block. By not merging them, we make it possible to iteratively
869    // ifcvt the blocks.
870    if (!HasEarlyExit && NextBBI->BB->pred_size() == 1) {
871      MergeBlocks(BBI, *NextBBI);
872      FalseBBDead = true;
873    } else {
874      InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
875      BBI.HasFallThrough = false;
876    }
877    // Mixed predicated and unpredicated code. This cannot be iteratively
878    // predicated.
879    IterIfcvt = false;
880  }
881
882  RemoveExtraEdges(BBI);
883
884  // Update block info. BB can be iteratively if-converted.
885  if (!IterIfcvt)
886    BBI.IsDone = true;
887  ReTryPreds(BBI.BB);
888  CvtBBI->IsDone = true;
889  if (FalseBBDead)
890    NextBBI->IsDone = true;
891
892  // FIXME: Must maintain LiveIns.
893  return true;
894}
895
896/// IfConvertDiamond - If convert a diamond sub-CFG.
897///
898bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
899  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
900  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
901
902  SmallVector<MachineInstr*, 2> Dups;
903  if (!BBI.TailBB) {
904    // No common merge block. Check if the terminators (e.g. return) are
905    // the same or predicable.
906    MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
907    MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
908    while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
909      if (TT->isIdenticalTo(FT))
910        Dups.push_back(TT);  // Will erase these later.
911      else if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0 ||
912               (FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
913        return false; // Can't if-convert. Abort!
914      ++TT;
915      ++FT;
916    }
917
918    // One of the two pathes have more terminators, make sure they are
919    // all predicable.
920    while (TT != BBI.TrueBB->end()) {
921      if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
922        return false; // Can't if-convert. Abort!
923      ++TT;
924    }
925    while (FT != BBI.FalseBB->end()) {
926      if ((FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
927        return false; // Can't if-convert. Abort!
928      ++FT;
929    }
930  }
931
932  // Remove the duplicated instructions from the 'true' block.
933  for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
934    Dups[i]->eraseFromParent();
935    --TrueBBI.NonPredSize;
936  }
937
938  // Merge the 'true' and 'false' blocks by copying the instructions
939  // from the 'false' block to the 'true' block. That is, unless the true
940  // block would clobber the predicate, in that case, do the opposite.
941  BBInfo *BBI1 = &TrueBBI;
942  BBInfo *BBI2 = &FalseBBI;
943  std::vector<MachineOperand> RevCond(BBI.BrCond);
944  TII->ReverseBranchCondition(RevCond);
945  std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
946  std::vector<MachineOperand> *Cond2 = &RevCond;
947  // Check the 'true' and 'false' blocks if either isn't ended with a branch.
948  // Either the block fallthrough to another block or it ends with a
949  // return. If it's the former, add a branch to its successor.
950  bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
951  bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
952
953  if ((TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred) ||
954      (!TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred &&
955       NeedBr1 && !NeedBr2)) {
956    std::swap(BBI1, BBI2);
957    std::swap(Cond1, Cond2);
958    std::swap(NeedBr1, NeedBr2);
959  }
960
961  // Predicate the 'true' block after removing its branch.
962  BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
963  PredicateBlock(*BBI1, *Cond1);
964
965  // Add an early exit branch if needed.
966  if (NeedBr1)
967    TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
968
969  // Predicate the 'false' block.
970  PredicateBlock(*BBI2, *Cond2, true);
971
972  // Add an unconditional branch from 'false' to to 'false' successor if it
973  // will not be the fallthrough block.
974  if (NeedBr2 && !NeedBr1) {
975    // If BBI2 isn't going to be merged in, then the existing fallthrough
976    // or branch is fine.
977    if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
978      InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
979      BBI2->HasFallThrough = false;
980    }
981  }
982
983  // Keep them as two separate blocks if there is an early exit.
984  if (!NeedBr1)
985    MergeBlocks(*BBI1, *BBI2);
986
987  // Remove the conditional branch from entry to the blocks.
988  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
989
990  // Merge the combined block into the entry of the diamond.
991  MergeBlocks(BBI, *BBI1);
992
993  // 'True' and 'false' aren't combined, see if we need to add a unconditional
994  // branch to the 'false' block.
995  if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
996    InsertUncondBranch(BBI.BB, BBI2->BB, TII);
997    BBI1->HasFallThrough = false;
998  }
999
1000  // If the if-converted block fallthrough or unconditionally branch into the
1001  // tail block, and the tail block does not have other predecessors, then
1002  // fold the tail block in as well.
1003  BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
1004  if (BBI.TailBB &&
1005      BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
1006    CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1007    BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
1008    MergeBlocks(*CvtBBI, TailBBI);
1009    TailBBI.IsDone = true;
1010  }
1011
1012  RemoveExtraEdges(BBI);
1013
1014  // Update block info.
1015  BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1016
1017  // FIXME: Must maintain LiveIns.
1018  return true;
1019}
1020
1021/// PredicateBlock - Predicate every instruction in the block with the specified
1022/// condition. If IgnoreTerm is true, skip over all terminator instructions.
1023void IfConverter::PredicateBlock(BBInfo &BBI,
1024                                 std::vector<MachineOperand> &Cond,
1025                                 bool IgnoreTerm) {
1026  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
1027       I != E; ++I) {
1028    if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
1029      continue;
1030    if (TII->isPredicated(I))
1031      continue;
1032    if (!TII->PredicateInstruction(I, Cond)) {
1033      cerr << "Unable to predicate " << *I << "!\n";
1034      abort();
1035    }
1036  }
1037
1038  std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1039
1040  BBI.IsAnalyzed = false;
1041  BBI.NonPredSize = 0;
1042
1043  NumIfConvBBs++;
1044}
1045
1046/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1047/// the destination block. Skip end of block branches if IgnoreBr is true.
1048void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1049                                        std::vector<MachineOperand> &Cond,
1050                                        bool IgnoreBr) {
1051  for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1052         E = FromBBI.BB->end(); I != E; ++I) {
1053    const TargetInstrDescriptor *TID = I->getInstrDescriptor();
1054    bool isPredicated = TII->isPredicated(I);
1055    // Do not copy the end of the block branches.
1056    if (IgnoreBr && !isPredicated && (TID->Flags & M_BRANCH_FLAG) != 0)
1057      break;
1058
1059    MachineInstr *MI = I->clone();
1060    ToBBI.BB->insert(ToBBI.BB->end(), MI);
1061    ToBBI.NonPredSize++;
1062
1063    if (!isPredicated)
1064      if (!TII->PredicateInstruction(MI, Cond)) {
1065        cerr << "Unable to predicate " << *MI << "!\n";
1066        abort();
1067      }
1068  }
1069
1070  std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1071            std::back_inserter(ToBBI.Predicate));
1072  std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1073
1074  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1075  ToBBI.IsAnalyzed = false;
1076
1077  NumDupBBs++;
1078}
1079
1080/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1081///
1082void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1083  ToBBI.BB->splice(ToBBI.BB->end(),
1084                   FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1085
1086  // Redirect all branches to FromBB to ToBB.
1087  std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1088                                         FromBBI.BB->pred_end());
1089  for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1090    MachineBasicBlock *Pred = Preds[i];
1091    if (Pred == ToBBI.BB)
1092      continue;
1093    Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1094  }
1095
1096  std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1097                                         FromBBI.BB->succ_end());
1098  MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1099  MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1100
1101  for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1102    MachineBasicBlock *Succ = Succs[i];
1103    // Fallthrough edge can't be transferred.
1104    if (Succ == FallThrough)
1105      continue;
1106    FromBBI.BB->removeSuccessor(Succ);
1107    if (!ToBBI.BB->isSuccessor(Succ))
1108      ToBBI.BB->addSuccessor(Succ);
1109  }
1110
1111  // Now FromBBI always fall through to the next block!
1112  if (NBB)
1113    FromBBI.BB->addSuccessor(NBB);
1114
1115  std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1116            std::back_inserter(ToBBI.Predicate));
1117  FromBBI.Predicate.clear();
1118
1119  ToBBI.NonPredSize += FromBBI.NonPredSize;
1120  FromBBI.NonPredSize = 0;
1121
1122  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1123  ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1124  ToBBI.IsAnalyzed = false;
1125  FromBBI.IsAnalyzed = false;
1126}
1127