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