IfConversion.cpp revision a1a9f408dadefb157d1204f72200936f013521fd
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/Debug.h"
23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/Statistic.h"
25using namespace llvm;
26
27STATISTIC(NumSimple,    "Number of simple if-conversions performed");
28STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
29STATISTIC(NumTriangle,  "Number of triangle if-conversions performed");
30STATISTIC(NumDiamonds,  "Number of diamond if-conversions performed");
31STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
32
33namespace {
34  class IfConverter : public MachineFunctionPass {
35    enum BBICKind {
36      ICNotAnalyzed,   // BB has not been analyzed.
37      ICReAnalyze,     // BB must be re-analyzed.
38      ICNotClassfied,  // BB data valid, but not classified.
39      ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
40      ICSimpleFalse,   // Same as ICSimple, but on the false path.
41      ICTriangle,      // BB is entry of a triangle sub-CFG.
42      ICDiamond,       // BB is entry of a diamond sub-CFG.
43      ICChild,         // BB is part of the sub-CFG that'll be predicated.
44      ICDead           // BB has been converted and merged, it's now dead.
45    };
46
47    /// BBInfo - One per MachineBasicBlock, this is used to cache the result
48    /// if-conversion feasibility analysis. This includes results from
49    /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
50    /// classification, and common tail block of its successors (if it's a
51    /// diamond shape), its size, whether it's predicable, and whether any
52    /// instruction can clobber the 'would-be' predicate.
53    ///
54    /// Kind            - Type of block. See BBICKind.
55    /// NonPredSize     - Number of non-predicated instructions.
56    /// IsAnalyzable    - True if AnalyzeBranch() returns false.
57    /// ModifyPredicate - FIXME: Not used right now. True if BB would modify
58    ///                   the predicate (e.g. has cmp, call, etc.)
59    /// BB              - Corresponding MachineBasicBlock.
60    /// TrueBB / FalseBB- See AnalyzeBranch().
61    /// BrCond          - Conditions for end of block conditional branches.
62    /// Predicate       - Predicate used in the BB.
63    struct BBInfo {
64      BBICKind Kind;
65      unsigned NonPredSize;
66      bool IsAnalyzable;
67      bool ModifyPredicate;
68      MachineBasicBlock *BB;
69      MachineBasicBlock *TrueBB;
70      MachineBasicBlock *FalseBB;
71      MachineBasicBlock *TailBB;
72      std::vector<MachineOperand> BrCond;
73      std::vector<MachineOperand> Predicate;
74      BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
75                 IsAnalyzable(false), ModifyPredicate(false),
76                 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
77    };
78
79    /// Roots - Basic blocks that do not have successors. These are the starting
80    /// points of Graph traversal.
81    std::vector<MachineBasicBlock*> Roots;
82
83    /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
84    /// basic block number.
85    std::vector<BBInfo> BBAnalysis;
86
87    const TargetLowering *TLI;
88    const TargetInstrInfo *TII;
89    bool MadeChange;
90  public:
91    static char ID;
92    IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
93
94    virtual bool runOnMachineFunction(MachineFunction &MF);
95    virtual const char *getPassName() const { return "If converter"; }
96
97  private:
98    bool ReverseBranchCondition(BBInfo &BBI);
99    void StructuralAnalysis(MachineBasicBlock *BB);
100    bool FeasibilityAnalysis(BBInfo &BBI,
101                             std::vector<MachineOperand> &Cond,
102                             bool IgnoreTerm = false);
103    bool AttemptRestructuring(BBInfo &BBI);
104    bool AnalyzeBlocks(MachineFunction &MF,
105                       std::vector<BBInfo*> &Candidates);
106    void ReTryPreds(MachineBasicBlock *BB);
107    bool IfConvertSimple(BBInfo &BBI);
108    bool IfConvertTriangle(BBInfo &BBI);
109    bool IfConvertDiamond(BBInfo &BBI);
110    void PredicateBlock(BBInfo &BBI,
111                        std::vector<MachineOperand> &Cond,
112                        bool IgnoreTerm = false);
113    void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
114
115    // IfcvtCandidateCmp - Used to sort if-conversion candidates.
116    static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
117      // Favor diamond over triangle, etc.
118      return (unsigned)C1->Kind < (unsigned)C2->Kind;
119    }
120  };
121  char IfConverter::ID = 0;
122}
123
124FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
125
126bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
127  TLI = MF.getTarget().getTargetLowering();
128  TII = MF.getTarget().getInstrInfo();
129  if (!TII) return false;
130
131  DOUT << "\nIfcvt: function \'" << MF.getFunction()->getName() << "\'\n";
132
133  MF.RenumberBlocks();
134  BBAnalysis.resize(MF.getNumBlockIDs());
135
136  // Look for root nodes, i.e. blocks without successors.
137  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
138    if (I->succ_size() == 0)
139      Roots.push_back(I);
140
141  std::vector<BBInfo*> Candidates;
142  MadeChange = false;
143  while (true) {
144    // Do an intial analysis for each basic block and finding all the potential
145    // candidates to perform if-convesion.
146    bool Change = AnalyzeBlocks(MF, Candidates);
147    while (!Candidates.empty()) {
148      BBInfo &BBI = *Candidates.back();
149      Candidates.pop_back();
150
151      bool RetVal = false;
152      switch (BBI.Kind) {
153      default: assert(false && "Unexpected!");
154        break;
155      case ICReAnalyze:
156        // One or more of 'children' have been modified, abort!
157      case ICDead:
158        // Block has been already been if-converted, abort!
159        break;
160      case ICSimple:
161      case ICSimpleFalse:
162        DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
163             << "): BB#" << BBI.BB->getNumber() << " ";
164        RetVal = IfConvertSimple(BBI);
165        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
166        if (RetVal)
167          if (BBI.Kind == ICSimple) NumSimple++;
168          else                      NumSimpleRev++;
169       break;
170      case ICTriangle:
171        DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " ";
172        RetVal = IfConvertTriangle(BBI);
173        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
174        if (RetVal) NumTriangle++;
175        break;
176      case ICDiamond:
177        DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " ";
178        RetVal = IfConvertDiamond(BBI);
179        DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
180        if (RetVal) NumDiamonds++;
181        break;
182      }
183      Change |= RetVal;
184    }
185
186    if (!Change)
187      break;
188    MadeChange |= Change;
189  }
190
191  Roots.clear();
192  BBAnalysis.clear();
193
194  return MadeChange;
195}
196
197static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
198                                         MachineBasicBlock *TrueBB) {
199  for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
200         E = BB->succ_end(); SI != E; ++SI) {
201    MachineBasicBlock *SuccBB = *SI;
202    if (SuccBB != TrueBB)
203      return SuccBB;
204  }
205  return NULL;
206}
207
208bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
209  if (!TII->ReverseBranchCondition(BBI.BrCond)) {
210    TII->RemoveBranch(*BBI.BB);
211    TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
212    std::swap(BBI.TrueBB, BBI.FalseBB);
213    return true;
214  }
215  return false;
216}
217
218/// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
219/// the specified block. Record its successors and whether it looks like an
220/// if-conversion candidate.
221void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
222  BBInfo &BBI = BBAnalysis[BB->getNumber()];
223
224  if (BBI.Kind == ICReAnalyze) {
225    BBI.BrCond.clear();
226    BBI.TrueBB = BBI.FalseBB = NULL;
227  } else {
228    if (BBI.Kind != ICNotAnalyzed)
229      return;  // Already analyzed.
230    BBI.BB = BB;
231    BBI.NonPredSize = std::distance(BB->begin(), BB->end());
232  }
233
234  // Look for 'root' of a simple (non-nested) triangle or diamond.
235  BBI.Kind = ICNotClassfied;
236  BBI.IsAnalyzable =
237    !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
238  if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
239    return;
240  // Do not ifcvt if either path is a back edge to the entry block.
241  if (BBI.TrueBB == BB || BBI.FalseBB == BB)
242    return;
243
244  StructuralAnalysis(BBI.TrueBB);
245  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
246
247  // No false branch. This BB must end with a conditional branch and a
248  // fallthrough.
249  if (!BBI.FalseBB)
250    BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
251  assert(BBI.FalseBB && "Expected to find the fallthrough block!");
252
253  StructuralAnalysis(BBI.FalseBB);
254  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
255
256  // Look for more opportunities to if-convert a triangle. Try to restructure
257  // the CFG to form a triangle with the 'false' path.
258  std::vector<MachineOperand> RevCond(BBI.BrCond);
259  bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
260  if (FalseBBI.FalseBB) {
261    if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB)
262      return;
263    std::vector<MachineOperand> Cond(BBI.BrCond);
264    if (CanRevCond &&
265        FalseBBI.TrueBB && FalseBBI.BB->pred_size() == 1 &&
266        FeasibilityAnalysis(FalseBBI, RevCond, true)) {
267      std::vector<MachineOperand> FalseCond(FalseBBI.BrCond);
268      if (FalseBBI.TrueBB == BBI.TrueBB &&
269          TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
270        // Reverse 'true' and 'false' paths.
271        ReverseBranchCondition(BBI);
272        BBI.Kind = ICTriangle;
273        FalseBBI.Kind = ICChild;
274      } else if (FalseBBI.FalseBB == BBI.TrueBB &&
275                 !TII->ReverseBranchCondition(FalseCond) &&
276                 TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
277        // Reverse 'false' block's 'true' and 'false' paths and then
278        // reverse 'true' and 'false' paths.
279        ReverseBranchCondition(FalseBBI);
280        ReverseBranchCondition(BBI);
281        BBI.Kind = ICTriangle;
282        FalseBBI.Kind = ICChild;
283      }
284    }
285  } else if (TrueBBI.TrueBB == FalseBBI.TrueBB && CanRevCond &&
286             TrueBBI.BB->pred_size() == 1 &&
287             TrueBBI.BB->pred_size() == 1 &&
288             // Check the 'true' and 'false' blocks if either isn't ended with
289             // a branch. If the block does not fallthrough to another block
290             // then we need to add a branch to its successor.
291             !(TrueBBI.ModifyPredicate &&
292               !TrueBBI.TrueBB && TrueBBI.BB->succ_size()) &&
293             !(FalseBBI.ModifyPredicate &&
294               !FalseBBI.TrueBB && FalseBBI.BB->succ_size()) &&
295             FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
296             FeasibilityAnalysis(FalseBBI, RevCond)) {
297    // Diamond:
298    //   EBB
299    //   / \_
300    //  |   |
301    // TBB FBB
302    //   \ /
303    //  TailBB
304    // Note MBB can be empty in case both TBB and FBB are return blocks.
305    BBI.Kind = ICDiamond;
306    TrueBBI.Kind = FalseBBI.Kind = ICChild;
307    BBI.TailBB = TrueBBI.TrueBB;
308  } else {
309    // FIXME: Consider duplicating if BB is small.
310    bool TryTriangle = TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB &&
311                       BBI.TrueBB->pred_size() == 1;
312    bool TrySimple = TrueBBI.BrCond.size() == 0 && BBI.TrueBB->pred_size() == 1;
313    if ((TryTriangle || TrySimple) &&
314        FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
315      if (TryTriangle) {
316        // Triangle:
317        //   EBB
318        //   | \_
319        //   |  |
320        //   | TBB
321        //   |  /
322        //   FBB
323        BBI.Kind = ICTriangle;
324        TrueBBI.Kind = ICChild;
325      } else {
326        // Simple (split, no rejoin):
327        //   EBB
328        //   | \_
329        //   |  |
330        //   | TBB---> exit
331        //   |
332        //   FBB
333        BBI.Kind = ICSimple;
334        TrueBBI.Kind = ICChild;
335      }
336    } else if (FalseBBI.BrCond.size() == 0 && BBI.FalseBB->pred_size() == 1) {
337      // Try 'simple' on the other path...
338      std::vector<MachineOperand> RevCond(BBI.BrCond);
339      if (TII->ReverseBranchCondition(RevCond))
340        assert(false && "Unable to reverse branch condition!");
341      if (FeasibilityAnalysis(FalseBBI, RevCond)) {
342        BBI.Kind = ICSimpleFalse;
343        FalseBBI.Kind = ICChild;
344      }
345    }
346  }
347  return;
348}
349
350/// FeasibilityAnalysis - Determine if the block is predicable. In most
351/// cases, that means all the instructions in the block has M_PREDICABLE flag.
352/// Also checks if the block contains any instruction which can clobber a
353/// predicate (e.g. condition code register). If so, the block is not
354/// predicable unless it's the last instruction. If IgnoreTerm is true then
355/// all the terminator instructions are skipped.
356bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
357                                      std::vector<MachineOperand> &Cond,
358                                      bool IgnoreTerm) {
359  // If the block is dead, or it is going to be the entry block of a sub-CFG
360  // that will be if-converted, then it cannot be predicated.
361  if (BBI.Kind != ICNotAnalyzed &&
362      BBI.Kind != ICNotClassfied &&
363      BBI.Kind != ICChild)
364    return false;
365
366  // Check predication threshold.
367  if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
368    return false;
369
370  // If it is already predicated, check if its predicate subsumes the new
371  // predicate.
372  if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
373    return false;
374
375  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
376       I != E; ++I) {
377    if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
378      continue;
379    // TODO: check if instruction clobbers predicate.
380    if (!I->isPredicable())
381      return false;
382  }
383
384  return true;
385}
386
387/// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
388/// expose more if-conversion opportunities. e.g.
389///
390///                cmp
391///                b le BB1
392///                /  \____
393///               /        |
394///             cmp        |
395///             b eq BB1   |
396///              /  \____  |
397///             /        \ |
398///                      BB1
399///  ==>
400///
401///                cmp
402///                b eq BB1
403///                /  \____
404///               /        |
405///             cmp        |
406///             b le BB1   |
407///              /  \____  |
408///             /        \ |
409///                      BB1
410bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
411  return false;
412}
413
414/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
415/// candidates. It returns true if any CFG restructuring is done to expose more
416/// if-conversion opportunities.
417bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
418                                std::vector<BBInfo*> &Candidates) {
419  bool Change = false;
420  std::set<MachineBasicBlock*> Visited;
421  for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
422    for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
423           E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
424      MachineBasicBlock *BB = *I;
425      StructuralAnalysis(BB);
426      BBInfo &BBI = BBAnalysis[BB->getNumber()];
427      switch (BBI.Kind) {
428        case ICSimple:
429        case ICSimpleFalse:
430        case ICTriangle:
431        case ICDiamond:
432          Candidates.push_back(&BBI);
433          break;
434        default:
435          Change |= AttemptRestructuring(BBI);
436          break;
437      }
438    }
439  }
440
441  // Sort to favor more complex ifcvt scheme.
442  std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
443
444  return Change;
445}
446
447/// isNextBlock - Returns true either if ToBB the next block after BB or
448/// that all the intervening blocks are empty.
449static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
450  MachineFunction::iterator I = BB;
451  MachineFunction::iterator TI = ToBB;
452  MachineFunction::iterator E = BB->getParent()->end();
453  while (++I != TI)
454    if (I == E || !I->empty())
455      return false;
456  return true;
457}
458
459/// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
460/// to determine if it can be if-converted.
461void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
462  for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
463         E = BB->pred_end(); PI != E; ++PI) {
464    BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
465    PBBI.Kind = ICReAnalyze;
466  }
467}
468
469/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
470///
471static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
472                               const TargetInstrInfo *TII) {
473  std::vector<MachineOperand> NoCond;
474  TII->InsertBranch(*BB, ToBB, NULL, NoCond);
475}
476
477/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
478///
479bool IfConverter::IfConvertSimple(BBInfo &BBI) {
480  bool ReverseCond = BBI.Kind == ICSimpleFalse;
481
482  BBI.Kind = ICNotClassfied;
483
484  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
485  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
486  BBInfo *CvtBBI = &TrueBBI;
487  BBInfo *NextBBI = &FalseBBI;
488
489  std::vector<MachineOperand> Cond(BBI.BrCond);
490  if (ReverseCond) {
491    std::swap(CvtBBI, NextBBI);
492    TII->ReverseBranchCondition(Cond);
493  }
494
495  PredicateBlock(*CvtBBI, Cond);
496  // If the 'true' block ends without a branch, add a conditional branch
497  // to its successor unless that happens to be the 'false' block.
498  if (CvtBBI->IsAnalyzable && CvtBBI->TrueBB == NULL) {
499    assert(CvtBBI->BB->succ_size() == 1 && "Unexpected!");
500    MachineBasicBlock *SuccBB = *CvtBBI->BB->succ_begin();
501    if (SuccBB != NextBBI->BB)
502      TII->InsertBranch(*CvtBBI->BB, SuccBB, NULL, Cond);
503  }
504
505  // Merge converted block into entry block. Also add an unconditional branch
506  // to the 'false' branch.
507  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
508  MergeBlocks(BBI, *CvtBBI);
509  if (!isNextBlock(BBI.BB, NextBBI->BB))
510    InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
511  std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
512
513  // Update block info. BB can be iteratively if-converted.
514  BBI.Kind = ICReAnalyze;
515  ReTryPreds(BBI.BB);
516  CvtBBI->Kind = ICDead;
517
518  // FIXME: Must maintain LiveIns.
519  return true;
520}
521
522/// IfConvertTriangle - If convert a triangle sub-CFG.
523///
524bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
525  BBI.Kind = ICNotClassfied;
526
527  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
528
529  // Predicate the 'true' block after removing its branch.
530  TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
531  PredicateBlock(TrueBBI, BBI.BrCond);
532
533  // If 'true' block has a 'false' successor, add an exit branch to it.
534  bool HasEarlyExit = TrueBBI.FalseBB != NULL;
535  if (HasEarlyExit) {
536    std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
537    if (TII->ReverseBranchCondition(RevCond))
538      assert(false && "Unable to reverse branch condition!");
539    TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
540  }
541
542  // Join the 'true' and 'false' blocks if the 'false' block has no other
543  // predecessors. Otherwise, add a unconditional branch from 'true' to 'false'.
544  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
545  bool FalseBBDead = false;
546  if (!HasEarlyExit && FalseBBI.BB->pred_size() == 2) {
547    MergeBlocks(TrueBBI, FalseBBI);
548    FalseBBDead = true;
549  } else if (!isNextBlock(TrueBBI.BB, FalseBBI.BB))
550    InsertUncondBranch(TrueBBI.BB, FalseBBI.BB, TII);
551
552  // Now merge the entry of the triangle with the true block.
553  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
554  MergeBlocks(BBI, TrueBBI);
555  std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
556            std::back_inserter(BBI.Predicate));
557
558  // Update block info. BB can be iteratively if-converted.
559  BBI.Kind = ICReAnalyze;
560  ReTryPreds(BBI.BB);
561  TrueBBI.Kind = ICDead;
562  if (FalseBBDead)
563    FalseBBI.Kind = ICDead;
564
565  // FIXME: Must maintain LiveIns.
566  return true;
567}
568
569/// IfConvertDiamond - If convert a diamond sub-CFG.
570///
571bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
572  BBI.Kind = ICNotClassfied;
573
574  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
575  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
576
577  SmallVector<MachineInstr*, 2> Dups;
578  if (!BBI.TailBB) {
579    // No common merge block. Check if the terminators (e.g. return) are
580    // the same or predicable.
581    MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
582    MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
583    while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
584      if (TT->isIdenticalTo(FT))
585        Dups.push_back(TT);  // Will erase these later.
586      else if (!TT->isPredicable() && !FT->isPredicable())
587        return false; // Can't if-convert. Abort!
588      ++TT;
589      ++FT;
590    }
591
592    // One of the two pathes have more terminators, make sure they are
593    // all predicable.
594    while (TT != BBI.TrueBB->end()) {
595      if (!TT->isPredicable()) {
596        return false; // Can't if-convert. Abort!
597      }
598      ++TT;
599    }
600    while (FT != BBI.FalseBB->end()) {
601      if (!FT->isPredicable()) {
602        return false; // Can't if-convert. Abort!
603      }
604      ++FT;
605    }
606  }
607
608  // Remove the duplicated instructions from the 'true' block.
609  for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
610    Dups[i]->eraseFromParent();
611    --TrueBBI.NonPredSize;
612  }
613
614  // Check the 'true' and 'false' blocks if either isn't ended with a branch.
615  // Either the block fallthrough to another block or it ends with a
616  // return. If it's the former, add a branch to its successor.
617  bool TrueNeedBr  = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
618  bool FalseNeedBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
619
620  // Merge the 'true' and 'false' blocks by copying the instructions
621  // from the 'false' block to the 'true' block. That is, unless the true
622  // block would clobber the predicate, in that case, do the opposite.
623  std::vector<MachineOperand> RevCond(BBI.BrCond);
624  TII->ReverseBranchCondition(RevCond);
625  BBInfo *CvtBBI;
626  if (!TrueBBI.ModifyPredicate) {
627    // Predicate the 'true' block after removing its branch.
628    TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
629    PredicateBlock(TrueBBI, BBI.BrCond);
630
631    // Predicate the 'false' block.
632    PredicateBlock(FalseBBI, RevCond, true);
633
634    if (TrueNeedBr)
635      TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL,
636                        BBI.BrCond);
637    // Add an unconditional branch from 'false' to to 'false' successor if it
638    // will not be the fallthrough block.
639    if (FalseNeedBr &&
640        !isNextBlock(BBI.BB, *BBI.FalseBB->succ_begin()))
641      InsertUncondBranch(BBI.FalseBB, *BBI.FalseBB->succ_begin(), TII);
642    MergeBlocks(TrueBBI, FalseBBI);
643    CvtBBI = &TrueBBI;
644  } else {
645    // Predicate the 'false' block after removing its branch.
646    FalseBBI.NonPredSize -= TII->RemoveBranch(*BBI.FalseBB);
647    PredicateBlock(FalseBBI, RevCond);
648
649    // Predicate the 'false' block.
650    PredicateBlock(TrueBBI, BBI.BrCond, true);
651
652    // Add a conditional branch from 'false' to 'false' successor if needed.
653    if (FalseNeedBr)
654      TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
655                        RevCond);
656    // Add an unconditional branch from 'true' to to 'true' successor if it
657    // will not be the fallthrough block.
658    if (TrueNeedBr &&
659        !isNextBlock(BBI.BB, *BBI.TrueBB->succ_begin()))
660      InsertUncondBranch(BBI.TrueBB, *BBI.TrueBB->succ_begin(), TII);
661    MergeBlocks(FalseBBI, TrueBBI);
662    CvtBBI = &FalseBBI;
663  }
664
665  // Remove the conditional branch from entry to the blocks.
666  BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
667
668  bool OkToIfcvt = true;
669  // Merge the combined block into the entry of the diamond if the entry
670  // block is its only predecessor. Otherwise, insert an unconditional
671  // branch from entry to the if-converted block.
672  if (CvtBBI->BB->pred_size() == 1) {
673    MergeBlocks(BBI, *CvtBBI);
674    CvtBBI = &BBI;
675    OkToIfcvt = false;
676  } else if (!isNextBlock(BBI.BB, CvtBBI->BB))
677    InsertUncondBranch(BBI.BB, CvtBBI->BB, TII);
678
679  // If the if-converted block fallthrough or unconditionally branch into the
680  // tail block, and the tail block does not have other predecessors, then
681  // fold the tail block in as well.
682  if (BBI.TailBB &&
683      BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
684    CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
685    BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
686    MergeBlocks(*CvtBBI, TailBBI);
687    TailBBI.Kind = ICDead;
688  }
689
690  // Update block info. BB may be iteratively if-converted.
691  if (OkToIfcvt) {
692    BBI.Kind = ICReAnalyze;
693    ReTryPreds(BBI.BB);
694  }
695  TrueBBI.Kind = ICDead;
696  FalseBBI.Kind = ICDead;
697
698  // FIXME: Must maintain LiveIns.
699  return true;
700}
701
702/// PredicateBlock - Predicate every instruction in the block with the specified
703/// condition. If IgnoreTerm is true, skip over all terminator instructions.
704void IfConverter::PredicateBlock(BBInfo &BBI,
705                                 std::vector<MachineOperand> &Cond,
706                                 bool IgnoreTerm) {
707  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
708       I != E; ++I) {
709    if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
710      continue;
711    if (TII->isPredicated(I))
712      continue;
713    if (!TII->PredicateInstruction(I, Cond)) {
714      cerr << "Unable to predicate " << *I << "!\n";
715      abort();
716    }
717  }
718
719  BBI.NonPredSize = 0;
720  NumIfConvBBs++;
721}
722
723/// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
724///
725static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
726  for (MachineBasicBlock::pred_iterator I = FromBB->pred_begin(),
727         E = FromBB->pred_end(); I != E; ++I) {
728    MachineBasicBlock *Pred = *I;
729    Pred->removeSuccessor(FromBB);
730    if (!Pred->isSuccessor(ToBB))
731      Pred->addSuccessor(ToBB);
732  }
733}
734
735/// TransferSuccs - Transfer all the successors of FromBB to ToBB.
736///
737static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
738  for (MachineBasicBlock::succ_iterator I = FromBB->succ_begin(),
739         E = FromBB->succ_end(); I != E; ++I) {
740    MachineBasicBlock *Succ = *I;
741    FromBB->removeSuccessor(Succ);
742    if (!ToBB->isSuccessor(Succ))
743      ToBB->addSuccessor(Succ);
744  }
745}
746
747/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
748///
749void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
750  ToBBI.BB->splice(ToBBI.BB->end(),
751                   FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
752
753  // If FromBBI is previously a successor, remove it from ToBBI's successor
754  // list and update its TrueBB / FalseBB field if needed.
755  if (ToBBI.BB->isSuccessor(FromBBI.BB))
756    ToBBI.BB->removeSuccessor(FromBBI.BB);
757
758  // Redirect all branches to FromBB to ToBB.
759  std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
760                                         FromBBI.BB->pred_end());
761  for (unsigned i = 0, e = Preds.size(); i != e; ++i)
762    Preds[i]->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
763
764  // Transfer preds / succs and update size.
765  TransferPreds(ToBBI.BB, FromBBI.BB);
766  TransferSuccs(ToBBI.BB, FromBBI.BB);
767  ToBBI.NonPredSize += FromBBI.NonPredSize;
768  FromBBI.NonPredSize = 0;
769}
770