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