Add a late optimization to BranchFolding that hoist common instruction sequences
[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/SmallSet.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     /// ExtraCost       - Extra cost for multi-cycle instructions.
97     /// ExtraCost2      - Some instructions are slower when predicated
98     /// BB              - Corresponding MachineBasicBlock.
99     /// TrueBB / FalseBB- See AnalyzeBranch().
100     /// BrCond          - Conditions for end of block conditional branches.
101     /// Predicate       - Predicate used in the BB.
102     struct BBInfo {
103       bool IsDone          : 1;
104       bool IsBeingAnalyzed : 1;
105       bool IsAnalyzed      : 1;
106       bool IsEnqueued      : 1;
107       bool IsBrAnalyzable  : 1;
108       bool HasFallThrough  : 1;
109       bool IsUnpredicable  : 1;
110       bool CannotBeCopied  : 1;
111       bool ClobbersPred    : 1;
112       unsigned NonPredSize;
113       unsigned ExtraCost;
114       unsigned ExtraCost2;
115       MachineBasicBlock *BB;
116       MachineBasicBlock *TrueBB;
117       MachineBasicBlock *FalseBB;
118       SmallVector<MachineOperand, 4> BrCond;
119       SmallVector<MachineOperand, 4> Predicate;
120       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
121                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
122                  HasFallThrough(false), IsUnpredicable(false),
123                  CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
124                  ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
125     };
126
127     /// IfcvtToken - Record information about pending if-conversions to attempt:
128     /// BBI             - Corresponding BBInfo.
129     /// Kind            - Type of block. See IfcvtKind.
130     /// NeedSubsumption - True if the to-be-predicated BB has already been
131     ///                   predicated.
132     /// NumDups      - Number of instructions that would be duplicated due
133     ///                   to this if-conversion. (For diamonds, the number of
134     ///                   identical instructions at the beginnings of both
135     ///                   paths).
136     /// NumDups2     - For diamonds, the number of identical instructions
137     ///                   at the ends of both paths.
138     struct IfcvtToken {
139       BBInfo &BBI;
140       IfcvtKind Kind;
141       bool NeedSubsumption;
142       unsigned NumDups;
143       unsigned NumDups2;
144       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
145         : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
146     };
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       initializeIfConverterPass(*PassRegistry::getPassRegistry());
163     }
164     
165     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166       AU.addRequired<MachineLoopInfo>();
167       MachineFunctionPass::getAnalysisUsage(AU);
168     }
169
170     virtual bool runOnMachineFunction(MachineFunction &MF);
171     virtual const char *getPassName() const { return "If Converter"; }
172
173   private:
174     bool ReverseBranchCondition(BBInfo &BBI);
175     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
176                      float Prediction, float Confidence) const;
177     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
178                        bool FalseBranch, unsigned &Dups,
179                        float Prediction, float Confidence) const;
180     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
181                       unsigned &Dups1, unsigned &Dups2) const;
182     void ScanInstructions(BBInfo &BBI);
183     BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
184                          std::vector<IfcvtToken*> &Tokens);
185     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
186                              bool isTriangle = false, bool RevBranch = false);
187     void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
188     void InvalidatePreds(MachineBasicBlock *BB);
189     void RemoveExtraEdges(BBInfo &BBI);
190     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
191     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
192     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
193                           unsigned NumDups1, unsigned NumDups2);
194     void PredicateBlock(BBInfo &BBI,
195                         MachineBasicBlock::iterator E,
196                         SmallVectorImpl<MachineOperand> &Cond,
197                         SmallSet<unsigned, 4> &Redefs);
198     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
199                                SmallVectorImpl<MachineOperand> &Cond,
200                                SmallSet<unsigned, 4> &Redefs,
201                                bool IgnoreBr = false);
202     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
203
204     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
205                             unsigned Cycle, unsigned Extra,
206                             float Prediction, float Confidence) const {
207       return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
208                                                    Prediction, Confidence);
209     }
210
211     bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
212                             unsigned TCycle, unsigned TExtra,
213                             MachineBasicBlock &FBB,
214                             unsigned FCycle, unsigned FExtra,
215                             float Prediction, float Confidence) const {
216       return TCycle > 0 && FCycle > 0 &&
217         TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
218                                  Prediction, Confidence);
219     }
220
221     // blockAlwaysFallThrough - Block ends without a terminator.
222     bool blockAlwaysFallThrough(BBInfo &BBI) const {
223       return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
224     }
225
226     // IfcvtTokenCmp - Used to sort if-conversion candidates.
227     static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
228       int Incr1 = (C1->Kind == ICDiamond)
229         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
230       int Incr2 = (C2->Kind == ICDiamond)
231         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
232       if (Incr1 > Incr2)
233         return true;
234       else if (Incr1 == Incr2) {
235         // Favors subsumption.
236         if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
237           return true;
238         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
239           // Favors diamond over triangle, etc.
240           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
241             return true;
242           else if (C1->Kind == C2->Kind)
243             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
244         }
245       }
246       return false;
247     }
248   };
249
250   char IfConverter::ID = 0;
251 }
252
253 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
254 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
255 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
256
257 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
258
259 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
260   TLI = MF.getTarget().getTargetLowering();
261   TII = MF.getTarget().getInstrInfo();
262   TRI = MF.getTarget().getRegisterInfo();
263   MLI = &getAnalysis<MachineLoopInfo>();
264   InstrItins = MF.getTarget().getInstrItineraryData();
265   if (!TII) return false;
266
267   // Tail merge tend to expose more if-conversion opportunities.
268   BranchFolder BF(true, false);
269   bool BFChange = BF.OptimizeFunction(MF, TII,
270                                    MF.getTarget().getRegisterInfo(),
271                                    getAnalysisIfAvailable<MachineModuleInfo>());
272
273   DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
274                << MF.getFunction()->getName() << "\'");
275
276   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
277     DEBUG(dbgs() << " skipped\n");
278     return false;
279   }
280   DEBUG(dbgs() << "\n");
281
282   MF.RenumberBlocks();
283   BBAnalysis.resize(MF.getNumBlockIDs());
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   BBAnalysis.clear();
400
401   if (MadeChange && IfCvtBranchFold) {
402     BranchFolder BF(false, false);
403     BF.OptimizeFunction(MF, TII,
404                         MF.getTarget().getRegisterInfo(),
405                         getAnalysisIfAvailable<MachineModuleInfo>());
406   }
407
408   MadeChange |= BFChange;
409   return MadeChange;
410 }
411
412 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
413 /// its 'true' successor.
414 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
415                                          MachineBasicBlock *TrueBB) {
416   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
417          E = BB->succ_end(); SI != E; ++SI) {
418     MachineBasicBlock *SuccBB = *SI;
419     if (SuccBB != TrueBB)
420       return SuccBB;
421   }
422   return NULL;
423 }
424
425 /// ReverseBranchCondition - Reverse the condition of the end of the block
426 /// branch. Swap block's 'true' and 'false' successors.
427 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
428   DebugLoc dl;  // FIXME: this is nowhere
429   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
430     TII->RemoveBranch(*BBI.BB);
431     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
432     std::swap(BBI.TrueBB, BBI.FalseBB);
433     return true;
434   }
435   return false;
436 }
437
438 /// getNextBlock - Returns the next block in the function blocks ordering. If
439 /// it is the end, returns NULL.
440 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
441   MachineFunction::iterator I = BB;
442   MachineFunction::iterator E = BB->getParent()->end();
443   if (++I == E)
444     return NULL;
445   return I;
446 }
447
448 /// ValidSimple - Returns true if the 'true' block (along with its
449 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
450 /// number of instructions that the ifcvt would need to duplicate if performed
451 /// in Dups.
452 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
453                               float Prediction, float Confidence) const {
454   Dups = 0;
455   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
456     return false;
457
458   if (TrueBBI.IsBrAnalyzable)
459     return false;
460
461   if (TrueBBI.BB->pred_size() > 1) {
462     if (TrueBBI.CannotBeCopied ||
463         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
464                                         Prediction, Confidence))
465       return false;
466     Dups = TrueBBI.NonPredSize;
467   }
468
469   return true;
470 }
471
472 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
473 /// with their common predecessor) forms a valid triangle shape for ifcvt.
474 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
475 /// branches to the 'false' block rather than the other way around. It also
476 /// returns the number of instructions that the ifcvt would need to duplicate
477 /// if performed in 'Dups'.
478 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
479                                 bool FalseBranch, unsigned &Dups,
480                                 float Prediction, float Confidence) const {
481   Dups = 0;
482   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
483     return false;
484
485   if (TrueBBI.BB->pred_size() > 1) {
486     if (TrueBBI.CannotBeCopied)
487       return false;
488
489     unsigned Size = TrueBBI.NonPredSize;
490     if (TrueBBI.IsBrAnalyzable) {
491       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
492         // Ends with an unconditional branch. It will be removed.
493         --Size;
494       else {
495         MachineBasicBlock *FExit = FalseBranch
496           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
497         if (FExit)
498           // Require a conditional branch
499           ++Size;
500       }
501     }
502     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size,
503                                         Prediction, Confidence))
504       return false;
505     Dups = Size;
506   }
507
508   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
509   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
510     MachineFunction::iterator I = TrueBBI.BB;
511     if (++I == TrueBBI.BB->getParent()->end())
512       return false;
513     TExit = I;
514   }
515   return TExit && TExit == FalseBBI.BB;
516 }
517
518 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
519 /// with their common predecessor) forms a valid diamond shape for ifcvt.
520 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
521                                unsigned &Dups1, unsigned &Dups2) const {
522   Dups1 = Dups2 = 0;
523   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
524       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
525     return false;
526
527   MachineBasicBlock *TT = TrueBBI.TrueBB;
528   MachineBasicBlock *FT = FalseBBI.TrueBB;
529
530   if (!TT && blockAlwaysFallThrough(TrueBBI))
531     TT = getNextBlock(TrueBBI.BB);
532   if (!FT && blockAlwaysFallThrough(FalseBBI))
533     FT = getNextBlock(FalseBBI.BB);
534   if (TT != FT)
535     return false;
536   if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
537     return false;
538   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
539     return false;
540
541   // FIXME: Allow true block to have an early exit?
542   if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
543       (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
544     return false;
545
546   // Count duplicate instructions at the beginning of the true and false blocks.
547   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
548   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
549   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
550   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
551   while (TIB != TIE && FIB != FIE) {
552     // Skip dbg_value instructions. These do not count.
553     if (TIB->isDebugValue()) {
554       while (TIB != TIE && TIB->isDebugValue())
555         ++TIB;
556       if (TIB == TIE)
557         break;
558     }
559     if (FIB->isDebugValue()) {
560       while (FIB != FIE && FIB->isDebugValue())
561         ++FIB;
562       if (FIB == FIE)
563         break;
564     }
565     if (!TIB->isIdenticalTo(FIB))
566       break;
567     ++Dups1;
568     ++TIB;
569     ++FIB;
570   }
571
572   // Now, in preparation for counting duplicate instructions at the ends of the
573   // blocks, move the end iterators up past any branch instructions.
574   while (TIE != TIB) {
575     --TIE;
576     if (!TIE->getDesc().isBranch())
577       break;
578   }
579   while (FIE != FIB) {
580     --FIE;
581     if (!FIE->getDesc().isBranch())
582       break;
583   }
584
585   // If Dups1 includes all of a block, then don't count duplicate
586   // instructions at the end of the blocks.
587   if (TIB == TIE || FIB == FIE)
588     return true;
589
590   // Count duplicate instructions at the ends of the blocks.
591   while (TIE != TIB && FIE != FIB) {
592     // Skip dbg_value instructions. These do not count.
593     if (TIE->isDebugValue()) {
594       while (TIE != TIB && TIE->isDebugValue())
595         --TIE;
596       if (TIE == TIB)
597         break;
598     }
599     if (FIE->isDebugValue()) {
600       while (FIE != FIB && FIE->isDebugValue())
601         --FIE;
602       if (FIE == FIB)
603         break;
604     }
605     if (!TIE->isIdenticalTo(FIE))
606       break;
607     ++Dups2;
608     --TIE;
609     --FIE;
610   }
611
612   return true;
613 }
614
615 /// ScanInstructions - Scan all the instructions in the block to determine if
616 /// the block is predicable. In most cases, that means all the instructions
617 /// in the block are isPredicable(). Also checks if the block contains any
618 /// instruction which can clobber a predicate (e.g. condition code register).
619 /// If so, the block is not predicable unless it's the last instruction.
620 void IfConverter::ScanInstructions(BBInfo &BBI) {
621   if (BBI.IsDone)
622     return;
623
624   bool AlreadyPredicated = BBI.Predicate.size() > 0;
625   // First analyze the end of BB branches.
626   BBI.TrueBB = BBI.FalseBB = NULL;
627   BBI.BrCond.clear();
628   BBI.IsBrAnalyzable =
629     !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
630   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
631
632   if (BBI.BrCond.size()) {
633     // No false branch. This BB must end with a conditional branch and a
634     // fallthrough.
635     if (!BBI.FalseBB)
636       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
637     if (!BBI.FalseBB) {
638       // Malformed bcc? True and false blocks are the same?
639       BBI.IsUnpredicable = true;
640       return;
641     }
642   }
643
644   // Then scan all the instructions.
645   BBI.NonPredSize = 0;
646   BBI.ExtraCost = 0;
647   BBI.ExtraCost2 = 0;
648   BBI.ClobbersPred = false;
649   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
650        I != E; ++I) {
651     if (I->isDebugValue())
652       continue;
653
654     const TargetInstrDesc &TID = I->getDesc();
655     if (TID.isNotDuplicable())
656       BBI.CannotBeCopied = true;
657
658     bool isPredicated = TII->isPredicated(I);
659     bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
660
661     if (!isCondBr) {
662       if (!isPredicated) {
663         BBI.NonPredSize++;
664         unsigned ExtraPredCost = 0;
665         unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
666                                                   &ExtraPredCost);
667         if (NumCycles > 1)
668           BBI.ExtraCost += NumCycles-1;
669         BBI.ExtraCost2 += ExtraPredCost;
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                                        TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
818                          *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
819                                         FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
820                          Prediction, Confidence) &&
821       FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
822       FeasibilityAnalysis(FalseBBI, RevCond)) {
823     // Diamond:
824     //   EBB
825     //   / \_
826     //  |   |
827     // TBB FBB
828     //   \ /
829     //  TailBB
830     // Note TailBB can be empty.
831     Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
832                                     Dups2));
833     Enqueued = true;
834   }
835
836   if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction, Confidence) &&
837       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
838                          TrueBBI.ExtraCost2, Prediction, Confidence) &&
839       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
840     // Triangle:
841     //   EBB
842     //   | \_
843     //   |  |
844     //   | TBB
845     //   |  /
846     //   FBB
847     Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
848     Enqueued = true;
849   }
850
851   if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction, Confidence) &&
852       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
853                          TrueBBI.ExtraCost2, Prediction, Confidence) &&
854       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
855     Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
856     Enqueued = true;
857   }
858
859   if (ValidSimple(TrueBBI, Dups, Prediction, Confidence) &&
860       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
861                          TrueBBI.ExtraCost2, Prediction, Confidence) &&
862       FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
863     // Simple (split, no rejoin):
864     //   EBB
865     //   | \_
866     //   |  |
867     //   | TBB---> exit
868     //   |
869     //   FBB
870     Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
871     Enqueued = true;
872   }
873
874   if (CanRevCond) {
875     // Try the other path...
876     if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
877                       1.0-Prediction, Confidence) &&
878         MeetIfcvtSizeLimit(*FalseBBI.BB,
879                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
880                            FalseBBI.ExtraCost2, 1.0-Prediction, Confidence) &&
881         FeasibilityAnalysis(FalseBBI, RevCond, true)) {
882       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
883       Enqueued = true;
884     }
885
886     if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
887                       1.0-Prediction, Confidence) &&
888         MeetIfcvtSizeLimit(*FalseBBI.BB,
889                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
890                            FalseBBI.ExtraCost2, 1.0-Prediction, Confidence) &&
891         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
892       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
893       Enqueued = true;
894     }
895
896     if (ValidSimple(FalseBBI, Dups, 1.0-Prediction, Confidence) &&
897         MeetIfcvtSizeLimit(*FalseBBI.BB,
898                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
899                            FalseBBI.ExtraCost2, 1.0-Prediction, Confidence) &&
900         FeasibilityAnalysis(FalseBBI, RevCond)) {
901       Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
902       Enqueued = true;
903     }
904   }
905
906   BBI.IsEnqueued = Enqueued;
907   BBI.IsBeingAnalyzed = false;
908   BBI.IsAnalyzed = true;
909   return BBI;
910 }
911
912 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
913 /// candidates.
914 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
915                                 std::vector<IfcvtToken*> &Tokens) {
916   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
917     MachineBasicBlock *BB = I;
918     AnalyzeBlock(BB, Tokens);
919   }
920
921   // Sort to favor more complex ifcvt scheme.
922   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
923 }
924
925 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
926 /// that all the intervening blocks are empty (given BB can fall through to its
927 /// next block).
928 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
929   MachineFunction::iterator PI = BB;
930   MachineFunction::iterator I = llvm::next(PI);
931   MachineFunction::iterator TI = ToBB;
932   MachineFunction::iterator E = BB->getParent()->end();
933   while (I != TI) {
934     // Check isSuccessor to avoid case where the next block is empty, but
935     // it's not a successor.
936     if (I == E || !I->empty() || !PI->isSuccessor(I))
937       return false;
938     PI = I++;
939   }
940   return true;
941 }
942
943 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
944 /// to determine if it can be if-converted. If predecessor is already enqueued,
945 /// dequeue it!
946 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
947   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
948          E = BB->pred_end(); PI != E; ++PI) {
949     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
950     if (PBBI.IsDone || PBBI.BB == BB)
951       continue;
952     PBBI.IsAnalyzed = false;
953     PBBI.IsEnqueued = false;
954   }
955 }
956
957 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
958 ///
959 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
960                                const TargetInstrInfo *TII) {
961   DebugLoc dl;  // FIXME: this is nowhere
962   SmallVector<MachineOperand, 0> NoCond;
963   TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
964 }
965
966 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
967 /// successors.
968 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
969   MachineBasicBlock *TBB = NULL, *FBB = NULL;
970   SmallVector<MachineOperand, 4> Cond;
971   if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
972     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
973 }
974
975 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
976 /// modeled as read + write (sort like two-address instructions). These
977 /// routines track register liveness and add implicit uses to if-converted
978 /// instructions to conform to the model.
979 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
980                            const TargetRegisterInfo *TRI) {
981   for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
982          E = BB->livein_end(); I != E; ++I) {
983     unsigned Reg = *I;
984     Redefs.insert(Reg);
985     for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
986          *Subreg; ++Subreg)
987       Redefs.insert(*Subreg);
988   }
989 }
990
991 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
992                              const TargetRegisterInfo *TRI,
993                              bool AddImpUse = false) {
994   SmallVector<unsigned, 4> Defs;
995   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
996     const MachineOperand &MO = MI->getOperand(i);
997     if (!MO.isReg())
998       continue;
999     unsigned Reg = MO.getReg();
1000     if (!Reg)
1001       continue;
1002     if (MO.isDef())
1003       Defs.push_back(Reg);
1004     else if (MO.isKill()) {
1005       Redefs.erase(Reg);
1006       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1007         Redefs.erase(*SR);
1008     }
1009   }
1010   for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1011     unsigned Reg = Defs[i];
1012     if (Redefs.count(Reg)) {
1013       if (AddImpUse)
1014         // Treat predicated update as read + write.
1015         MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
1016                                                 true/*IsImp*/,false/*IsKill*/));
1017     } else {
1018       Redefs.insert(Reg);
1019       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1020         Redefs.insert(*SR);
1021     }
1022   }
1023 }
1024
1025 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1026                              MachineBasicBlock::iterator E,
1027                              SmallSet<unsigned,4> &Redefs,
1028                              const TargetRegisterInfo *TRI) {
1029   while (I != E) {
1030     UpdatePredRedefs(I, Redefs, TRI);
1031     ++I;
1032   }
1033 }
1034
1035 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1036 ///
1037 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1038   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1039   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1040   BBInfo *CvtBBI = &TrueBBI;
1041   BBInfo *NextBBI = &FalseBBI;
1042
1043   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1044   if (Kind == ICSimpleFalse)
1045     std::swap(CvtBBI, NextBBI);
1046
1047   if (CvtBBI->IsDone ||
1048       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1049     // Something has changed. It's no longer safe to predicate this block.
1050     BBI.IsAnalyzed = false;
1051     CvtBBI->IsAnalyzed = false;
1052     return false;
1053   }
1054
1055   if (Kind == ICSimpleFalse)
1056     if (TII->ReverseBranchCondition(Cond))
1057       assert(false && "Unable to reverse branch condition!");
1058
1059   // Initialize liveins to the first BB. These are potentiall redefined by
1060   // predicated instructions.
1061   SmallSet<unsigned, 4> Redefs;
1062   InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1063   InitPredRedefs(NextBBI->BB, Redefs, TRI);
1064
1065   if (CvtBBI->BB->pred_size() > 1) {
1066     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1067     // Copy instructions in the true block, predicate them, and add them to
1068     // the entry block.
1069     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1070   } else {
1071     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1072
1073     // Merge converted block into entry block.
1074     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1075     MergeBlocks(BBI, *CvtBBI);
1076   }
1077
1078   bool IterIfcvt = true;
1079   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1080     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1081     BBI.HasFallThrough = false;
1082     // Now ifcvt'd block will look like this:
1083     // BB:
1084     // ...
1085     // t, f = cmp
1086     // if t op
1087     // b BBf
1088     //
1089     // We cannot further ifcvt this block because the unconditional branch
1090     // will have to be predicated on the new condition, that will not be
1091     // available if cmp executes.
1092     IterIfcvt = false;
1093   }
1094
1095   RemoveExtraEdges(BBI);
1096
1097   // Update block info. BB can be iteratively if-converted.
1098   if (!IterIfcvt)
1099     BBI.IsDone = true;
1100   InvalidatePreds(BBI.BB);
1101   CvtBBI->IsDone = true;
1102
1103   // FIXME: Must maintain LiveIns.
1104   return true;
1105 }
1106
1107 /// IfConvertTriangle - If convert a triangle sub-CFG.
1108 ///
1109 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1110   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1111   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1112   BBInfo *CvtBBI = &TrueBBI;
1113   BBInfo *NextBBI = &FalseBBI;
1114   DebugLoc dl;  // FIXME: this is nowhere
1115
1116   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1117   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1118     std::swap(CvtBBI, NextBBI);
1119
1120   if (CvtBBI->IsDone ||
1121       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1122     // Something has changed. It's no longer safe to predicate this block.
1123     BBI.IsAnalyzed = false;
1124     CvtBBI->IsAnalyzed = false;
1125     return false;
1126   }
1127
1128   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1129     if (TII->ReverseBranchCondition(Cond))
1130       assert(false && "Unable to reverse branch condition!");
1131
1132   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1133     if (ReverseBranchCondition(*CvtBBI)) {
1134       // BB has been changed, modify its predecessors (except for this
1135       // one) so they don't get ifcvt'ed based on bad intel.
1136       for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1137              E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1138         MachineBasicBlock *PBB = *PI;
1139         if (PBB == BBI.BB)
1140           continue;
1141         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1142         if (PBBI.IsEnqueued) {
1143           PBBI.IsAnalyzed = false;
1144           PBBI.IsEnqueued = false;
1145         }
1146       }
1147     }
1148   }
1149
1150   // Initialize liveins to the first BB. These are potentially redefined by
1151   // predicated instructions.
1152   SmallSet<unsigned, 4> Redefs;
1153   InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1154   InitPredRedefs(NextBBI->BB, Redefs, TRI);
1155
1156   bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1157   if (CvtBBI->BB->pred_size() > 1) {
1158     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1159     // Copy instructions in the true block, predicate them, and add them to
1160     // the entry block.
1161     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1162   } else {
1163     // Predicate the 'true' block after removing its branch.
1164     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1165     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1166
1167     // Now merge the entry of the triangle with the true block.
1168     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1169     MergeBlocks(BBI, *CvtBBI, false);
1170   }
1171
1172   // If 'true' block has a 'false' successor, add an exit branch to it.
1173   if (HasEarlyExit) {
1174     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1175                                            CvtBBI->BrCond.end());
1176     if (TII->ReverseBranchCondition(RevCond))
1177       assert(false && "Unable to reverse branch condition!");
1178     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1179     BBI.BB->addSuccessor(CvtBBI->FalseBB);
1180   }
1181
1182   // Merge in the 'false' block if the 'false' block has no other
1183   // predecessors. Otherwise, add an unconditional branch to 'false'.
1184   bool FalseBBDead = false;
1185   bool IterIfcvt = true;
1186   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1187   if (!isFallThrough) {
1188     // Only merge them if the true block does not fallthrough to the false
1189     // block. By not merging them, we make it possible to iteratively
1190     // ifcvt the blocks.
1191     if (!HasEarlyExit &&
1192         NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1193       MergeBlocks(BBI, *NextBBI);
1194       FalseBBDead = true;
1195     } else {
1196       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1197       BBI.HasFallThrough = false;
1198     }
1199     // Mixed predicated and unpredicated code. This cannot be iteratively
1200     // predicated.
1201     IterIfcvt = false;
1202   }
1203
1204   RemoveExtraEdges(BBI);
1205
1206   // Update block info. BB can be iteratively if-converted.
1207   if (!IterIfcvt)
1208     BBI.IsDone = true;
1209   InvalidatePreds(BBI.BB);
1210   CvtBBI->IsDone = true;
1211   if (FalseBBDead)
1212     NextBBI->IsDone = true;
1213
1214   // FIXME: Must maintain LiveIns.
1215   return true;
1216 }
1217
1218 /// IfConvertDiamond - If convert a diamond sub-CFG.
1219 ///
1220 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1221                                    unsigned NumDups1, unsigned NumDups2) {
1222   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1223   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1224   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1225   // True block must fall through or end with an unanalyzable terminator.
1226   if (!TailBB) {
1227     if (blockAlwaysFallThrough(TrueBBI))
1228       TailBB = FalseBBI.TrueBB;
1229     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1230   }
1231
1232   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1233       TrueBBI.BB->pred_size() > 1 ||
1234       FalseBBI.BB->pred_size() > 1) {
1235     // Something has changed. It's no longer safe to predicate these blocks.
1236     BBI.IsAnalyzed = false;
1237     TrueBBI.IsAnalyzed = false;
1238     FalseBBI.IsAnalyzed = false;
1239     return false;
1240   }
1241
1242   // Put the predicated instructions from the 'true' block before the
1243   // instructions from the 'false' block, unless the true block would clobber
1244   // the predicate, in which case, do the opposite.
1245   BBInfo *BBI1 = &TrueBBI;
1246   BBInfo *BBI2 = &FalseBBI;
1247   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1248   if (TII->ReverseBranchCondition(RevCond))
1249     assert(false && "Unable to reverse branch condition!");
1250   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1251   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1252
1253   // Figure out the more profitable ordering.
1254   bool DoSwap = false;
1255   if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1256     DoSwap = true;
1257   else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1258     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1259       DoSwap = true;
1260   }
1261   if (DoSwap) {
1262     std::swap(BBI1, BBI2);
1263     std::swap(Cond1, Cond2);
1264   }
1265
1266   // Remove the conditional branch from entry to the blocks.
1267   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1268
1269   // Initialize liveins to the first BB. These are potentially redefined by
1270   // predicated instructions.
1271   SmallSet<unsigned, 4> Redefs;
1272   InitPredRedefs(BBI1->BB, Redefs, TRI);
1273
1274   // Remove the duplicated instructions at the beginnings of both paths.
1275   MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1276   MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1277   MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1278   MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1279   // Skip dbg_value instructions
1280   while (DI1 != DIE1 && DI1->isDebugValue())
1281     ++DI1;
1282   while (DI2 != DIE2 && DI2->isDebugValue())
1283     ++DI2;
1284   BBI1->NonPredSize -= NumDups1;
1285   BBI2->NonPredSize -= NumDups1;
1286
1287   // Skip past the dups on each side separately since there may be
1288   // differing dbg_value entries.
1289   for (unsigned i = 0; i < NumDups1; ++DI1) {
1290     if (!DI1->isDebugValue())
1291       ++i;
1292   }
1293   while (NumDups1 != 0) {
1294     ++DI2;
1295     if (!DI2->isDebugValue())
1296       --NumDups1;
1297   }
1298
1299   UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1300   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1301   BBI2->BB->erase(BBI2->BB->begin(), DI2);
1302
1303   // Predicate the 'true' block after removing its branch.
1304   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1305   DI1 = BBI1->BB->end();
1306   for (unsigned i = 0; i != NumDups2; ) {
1307     // NumDups2 only counted non-dbg_value instructions, so this won't
1308     // run off the head of the list.
1309     assert (DI1 != BBI1->BB->begin());
1310     --DI1;
1311     // skip dbg_value instructions
1312     if (!DI1->isDebugValue())
1313       ++i;
1314   }
1315   BBI1->BB->erase(DI1, BBI1->BB->end());
1316   PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
1317
1318   // Predicate the 'false' block.
1319   BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1320   DI2 = BBI2->BB->end();
1321   while (NumDups2 != 0) {
1322     // NumDups2 only counted non-dbg_value instructions, so this won't
1323     // run off the head of the list.
1324     assert (DI2 != BBI2->BB->begin());
1325     --DI2;
1326     // skip dbg_value instructions
1327     if (!DI2->isDebugValue())
1328       --NumDups2;
1329   }
1330   PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1331
1332   // Merge the true block into the entry of the diamond.
1333   MergeBlocks(BBI, *BBI1, TailBB == 0);
1334   MergeBlocks(BBI, *BBI2, TailBB == 0);
1335
1336   // If the if-converted block falls through or unconditionally branches into
1337   // the tail block, and the tail block does not have other predecessors, then
1338   // fold the tail block in as well. Otherwise, unless it falls through to the
1339   // tail, add a unconditional branch to it.
1340   if (TailBB) {
1341     BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1342     bool CanMergeTail = !TailBBI.HasFallThrough;
1343     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1344     // check if there are any other predecessors besides those.
1345     unsigned NumPreds = TailBB->pred_size();
1346     if (NumPreds > 1)
1347       CanMergeTail = false;
1348     else if (NumPreds == 1 && CanMergeTail) {
1349       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1350       if (*PI != BBI1->BB && *PI != BBI2->BB)
1351         CanMergeTail = false;
1352     }
1353     if (CanMergeTail) {
1354       MergeBlocks(BBI, TailBBI);
1355       TailBBI.IsDone = true;
1356     } else {
1357       BBI.BB->addSuccessor(TailBB);
1358       InsertUncondBranch(BBI.BB, TailBB, TII);
1359       BBI.HasFallThrough = false;
1360     }
1361   }
1362
1363   // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1364   // which can happen here if TailBB is unanalyzable and is merged, so
1365   // explicitly remove BBI1 and BBI2 as successors.
1366   BBI.BB->removeSuccessor(BBI1->BB);
1367   BBI.BB->removeSuccessor(BBI2->BB);
1368   RemoveExtraEdges(BBI);
1369
1370   // Update block info.
1371   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1372   InvalidatePreds(BBI.BB);
1373
1374   // FIXME: Must maintain LiveIns.
1375   return true;
1376 }
1377
1378 /// PredicateBlock - Predicate instructions from the start of the block to the
1379 /// specified end with the specified condition.
1380 void IfConverter::PredicateBlock(BBInfo &BBI,
1381                                  MachineBasicBlock::iterator E,
1382                                  SmallVectorImpl<MachineOperand> &Cond,
1383                                  SmallSet<unsigned, 4> &Redefs) {
1384   for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1385     if (I->isDebugValue() || TII->isPredicated(I))
1386       continue;
1387     if (!TII->PredicateInstruction(I, Cond)) {
1388 #ifndef NDEBUG
1389       dbgs() << "Unable to predicate " << *I << "!\n";
1390 #endif
1391       llvm_unreachable(0);
1392     }
1393
1394     // If the predicated instruction now redefines a register as the result of
1395     // if-conversion, add an implicit kill.
1396     UpdatePredRedefs(I, Redefs, TRI, true);
1397   }
1398
1399   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1400
1401   BBI.IsAnalyzed = false;
1402   BBI.NonPredSize = 0;
1403
1404   ++NumIfConvBBs;
1405 }
1406
1407 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1408 /// the destination block. Skip end of block branches if IgnoreBr is true.
1409 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1410                                         SmallVectorImpl<MachineOperand> &Cond,
1411                                         SmallSet<unsigned, 4> &Redefs,
1412                                         bool IgnoreBr) {
1413   MachineFunction &MF = *ToBBI.BB->getParent();
1414
1415   for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1416          E = FromBBI.BB->end(); I != E; ++I) {
1417     const TargetInstrDesc &TID = I->getDesc();
1418     // Do not copy the end of the block branches.
1419     if (IgnoreBr && TID.isBranch())
1420       break;
1421
1422     MachineInstr *MI = MF.CloneMachineInstr(I);
1423     ToBBI.BB->insert(ToBBI.BB->end(), MI);
1424     ToBBI.NonPredSize++;
1425     unsigned ExtraPredCost = 0;
1426     unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
1427     if (NumCycles > 1)
1428       ToBBI.ExtraCost += NumCycles-1;
1429     ToBBI.ExtraCost2 += ExtraPredCost;
1430
1431     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1432       if (!TII->PredicateInstruction(MI, Cond)) {
1433 #ifndef NDEBUG
1434         dbgs() << "Unable to predicate " << *I << "!\n";
1435 #endif
1436         llvm_unreachable(0);
1437       }
1438     }
1439
1440     // If the predicated instruction now redefines a register as the result of
1441     // if-conversion, add an implicit kill.
1442     UpdatePredRedefs(MI, Redefs, TRI, true);
1443   }
1444
1445   if (!IgnoreBr) {
1446     std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1447                                            FromBBI.BB->succ_end());
1448     MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1449     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1450
1451     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1452       MachineBasicBlock *Succ = Succs[i];
1453       // Fallthrough edge can't be transferred.
1454       if (Succ == FallThrough)
1455         continue;
1456       ToBBI.BB->addSuccessor(Succ);
1457     }
1458   }
1459
1460   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1461             std::back_inserter(ToBBI.Predicate));
1462   std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1463
1464   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1465   ToBBI.IsAnalyzed = false;
1466
1467   ++NumDupBBs;
1468 }
1469
1470 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1471 /// This will leave FromBB as an empty block, so remove all of its
1472 /// successor edges except for the fall-through edge.  If AddEdges is true,
1473 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1474 /// ToBBI.
1475 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1476   ToBBI.BB->splice(ToBBI.BB->end(),
1477                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1478
1479   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1480                                          FromBBI.BB->succ_end());
1481   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1482   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1483
1484   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1485     MachineBasicBlock *Succ = Succs[i];
1486     // Fallthrough edge can't be transferred.
1487     if (Succ == FallThrough)
1488       continue;
1489     FromBBI.BB->removeSuccessor(Succ);
1490     if (AddEdges)
1491       ToBBI.BB->addSuccessor(Succ);
1492   }
1493
1494   // Now FromBBI always falls through to the next block!
1495   if (NBB && !FromBBI.BB->isSuccessor(NBB))
1496     FromBBI.BB->addSuccessor(NBB);
1497
1498   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1499             std::back_inserter(ToBBI.Predicate));
1500   FromBBI.Predicate.clear();
1501
1502   ToBBI.NonPredSize += FromBBI.NonPredSize;
1503   ToBBI.ExtraCost += FromBBI.ExtraCost;
1504   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1505   FromBBI.NonPredSize = 0;
1506   FromBBI.ExtraCost = 0;
1507   FromBBI.ExtraCost2 = 0;
1508
1509   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1510   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1511   ToBBI.IsAnalyzed = false;
1512   FromBBI.IsAnalyzed = false;
1513 }