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