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