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