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