1302ec2cd2166ad4e498a096e1bd2d41b6c6073f
[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 was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source 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 "llvm/Function.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/Statistic.h"
26 using namespace llvm;
27
28 namespace {
29   // Hidden options for help debugging.
30   cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31   cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32   cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33   cl::opt<bool> DisableSimple("disable-ifcvt-simple", 
34                               cl::init(false), cl::Hidden);
35   cl::opt<bool> DisableSimpleFalse("disable-ifcvt-simple-false", 
36                                    cl::init(false), cl::Hidden);
37   cl::opt<bool> DisableTriangle("disable-ifcvt-triangle", 
38                                 cl::init(false), cl::Hidden);
39   cl::opt<bool> DisableDiamond("disable-ifcvt-diamond", 
40                                cl::init(false), cl::Hidden);
41 }
42
43 STATISTIC(NumSimple,    "Number of simple if-conversions performed");
44 STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
45 STATISTIC(NumTriangle,  "Number of triangle if-conversions performed");
46 STATISTIC(NumDiamonds,  "Number of diamond if-conversions performed");
47 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
48
49 namespace {
50   class IfConverter : public MachineFunctionPass {
51     enum BBICKind {
52       ICNotAnalyzed,   // BB has not been analyzed.
53       ICReAnalyze,     // BB must be re-analyzed.
54       ICNotClassfied,  // BB data valid, but not classified.
55       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
56       ICSimpleFalse,   // Same as ICSimple, but on the false path.
57       ICTriangle,      // BB is entry of a triangle sub-CFG.
58       ICDiamond,       // BB is entry of a diamond sub-CFG.
59       ICChild,         // BB is part of the sub-CFG that'll be predicated.
60       ICDead           // BB cannot be if-converted again.
61     };
62
63     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
64     /// if-conversion feasibility analysis. This includes results from
65     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
66     /// classification, and common tail block of its successors (if it's a
67     /// diamond shape), its size, whether it's predicable, and whether any
68     /// instruction can clobber the 'would-be' predicate.
69     ///
70     /// Kind            - Type of block. See BBICKind.
71     /// NonPredSize     - Number of non-predicated instructions.
72     /// IsAnalyzable    - True if AnalyzeBranch() returns false.
73     /// ModifyPredicate - True if BB would modify the predicate (e.g. has
74     ///                   cmp, call, etc.)
75     /// BB              - Corresponding MachineBasicBlock.
76     /// TrueBB / FalseBB- See AnalyzeBranch().
77     /// BrCond          - Conditions for end of block conditional branches.
78     /// Predicate       - Predicate used in the BB.
79     struct BBInfo {
80       BBICKind Kind;
81       unsigned NonPredSize;
82       bool IsAnalyzable;
83       bool hasFallThrough;
84       bool ModifyPredicate;
85       MachineBasicBlock *BB;
86       MachineBasicBlock *TrueBB;
87       MachineBasicBlock *FalseBB;
88       MachineBasicBlock *TailBB;
89       std::vector<MachineOperand> BrCond;
90       std::vector<MachineOperand> Predicate;
91       BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
92                  IsAnalyzable(false), hasFallThrough(false),
93                  ModifyPredicate(false),
94                  BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
95     };
96
97     /// Roots - Basic blocks that do not have successors. These are the starting
98     /// points of Graph traversal.
99     std::vector<MachineBasicBlock*> Roots;
100
101     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
102     /// basic block number.
103     std::vector<BBInfo> BBAnalysis;
104
105     const TargetLowering *TLI;
106     const TargetInstrInfo *TII;
107     bool MadeChange;
108   public:
109     static char ID;
110     IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
111
112     virtual bool runOnMachineFunction(MachineFunction &MF);
113     virtual const char *getPassName() const { return "If converter"; }
114
115   private:
116     bool ReverseBranchCondition(BBInfo &BBI);
117     bool ValidSimple(BBInfo &TrueBBI) const;
118     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
119                        bool FalseBranch = false) const;
120     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
121     void ScanInstructions(BBInfo &BBI);
122     void AnalyzeBlock(MachineBasicBlock *BB);
123     bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
124                              bool isTriangle = false, bool RevBranch = false);
125     bool AttemptRestructuring(BBInfo &BBI);
126     bool AnalyzeBlocks(MachineFunction &MF,
127                        std::vector<BBInfo*> &Candidates);
128     void ReTryPreds(MachineBasicBlock *BB);
129     void RemoveExtraEdges(BBInfo &BBI);
130     bool IfConvertSimple(BBInfo &BBI);
131     bool IfConvertTriangle(BBInfo &BBI);
132     bool IfConvertDiamond(BBInfo &BBI);
133     void PredicateBlock(BBInfo &BBI,
134                         std::vector<MachineOperand> &Cond,
135                         bool IgnoreTerm = false);
136     void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
137
138     // blockAlwaysFallThrough - Block ends without a terminator.
139     bool blockAlwaysFallThrough(BBInfo &BBI) const {
140       return BBI.IsAnalyzable && BBI.TrueBB == NULL;
141     }
142
143     // IfcvtCandidateCmp - Used to sort if-conversion candidates.
144     static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
145       // Favor diamond over triangle, etc.
146       return (unsigned)C1->Kind < (unsigned)C2->Kind;
147     }
148   };
149   char IfConverter::ID = 0;
150 }
151
152 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
153
154 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
155   TLI = MF.getTarget().getTargetLowering();
156   TII = MF.getTarget().getInstrInfo();
157   if (!TII) return false;
158
159   static int FnNum = -1;
160   DOUT << "\nIfcvt: function (" << ++FnNum <<  ") \'"
161        << MF.getFunction()->getName() << "\'";
162
163   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
164     DOUT << " skipped\n";
165     return false;
166   }
167   DOUT << "\n";
168
169   MF.RenumberBlocks();
170   BBAnalysis.resize(MF.getNumBlockIDs());
171
172   // Look for root nodes, i.e. blocks without successors.
173   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
174     if (I->succ_size() == 0)
175       Roots.push_back(I);
176
177   std::vector<BBInfo*> Candidates;
178   MadeChange = false;
179   while (IfCvtLimit == -1 || (int)NumIfConvBBs < IfCvtLimit) {
180     // Do an intial analysis for each basic block and finding all the potential
181     // candidates to perform if-convesion.
182     bool Change = AnalyzeBlocks(MF, Candidates);
183     while (!Candidates.empty()) {
184       BBInfo &BBI = *Candidates.back();
185       Candidates.pop_back();
186
187       bool RetVal = false;
188       switch (BBI.Kind) {
189       default: assert(false && "Unexpected!");
190         break;
191       case ICReAnalyze:
192         // One or more of 'children' have been modified, abort!
193       case ICDead:
194         // Block has been already been if-converted, abort!
195         break;
196       case ICSimple:
197       case ICSimpleFalse: {
198         bool isRev = BBI.Kind == ICSimpleFalse;
199         if ((isRev && DisableSimpleFalse) || (!isRev && DisableSimple)) break;
200         DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
201              << "): BB#" << BBI.BB->getNumber() << " ("
202              << ((BBI.Kind == ICSimpleFalse)
203                  ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
204         RetVal = IfConvertSimple(BBI);
205         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
206         if (RetVal)
207           if (isRev) NumSimpleRev++;
208           else       NumSimple++;
209        break;
210       }
211       case ICTriangle:
212         if (DisableTriangle) break;
213         DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " (T:"
214              << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
215              << ") ";
216         RetVal = IfConvertTriangle(BBI);
217         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
218         if (RetVal) NumTriangle++;
219         break;
220       case ICDiamond:
221         if (DisableDiamond) break;
222         DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
223              << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
224         if (BBI.TailBB)
225           DOUT << "," << BBI.TailBB->getNumber() ;
226         DOUT << ") ";
227         RetVal = IfConvertDiamond(BBI);
228         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
229         if (RetVal) NumDiamonds++;
230         break;
231       }
232       Change |= RetVal;
233
234       if (IfCvtLimit != -1 && (int)NumIfConvBBs > IfCvtLimit)
235         break;
236     }
237
238     if (!Change)
239       break;
240     MadeChange |= Change;
241   }
242
243   Roots.clear();
244   BBAnalysis.clear();
245
246   return MadeChange;
247 }
248
249 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
250                                          MachineBasicBlock *TrueBB) {
251   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
252          E = BB->succ_end(); SI != E; ++SI) {
253     MachineBasicBlock *SuccBB = *SI;
254     if (SuccBB != TrueBB)
255       return SuccBB;
256   }
257   return NULL;
258 }
259
260 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
261   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
262     TII->RemoveBranch(*BBI.BB);
263     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
264     std::swap(BBI.TrueBB, BBI.FalseBB);
265     return true;
266   }
267   return false;
268 }
269
270 /// ValidSimple - Returns true if the 'true' block (along with its
271 /// predecessor) forms a valid simple shape for ifcvt.
272 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
273   return !blockAlwaysFallThrough(TrueBBI) &&
274     TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
275 }
276
277 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
278 /// with their common predecessor) forms a valid triangle shape for ifcvt.
279 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
280                                 bool FalseBranch) const {
281   if (TrueBBI.BB->pred_size() != 1)
282     return false;
283
284   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
285   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
286     MachineFunction::iterator I = TrueBBI.BB;
287     if (++I == TrueBBI.BB->getParent()->end())
288       return false;
289     TExit = I;
290   }
291   return TExit && TExit == FalseBBI.BB;
292 }
293
294 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
295 /// with their common predecessor) forms a valid diamond shape for ifcvt.
296 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
297   // FIXME: Also look for fallthrough 
298   return (TrueBBI.TrueBB == FalseBBI.TrueBB &&
299           TrueBBI.BB->pred_size() == 1 &&
300           FalseBBI.BB->pred_size() == 1 &&
301           !TrueBBI.FalseBB && !FalseBBI.FalseBB);
302 }
303
304 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
305 /// the specified block. Record its successors and whether it looks like an
306 /// if-conversion candidate.
307 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
308   BBInfo &BBI = BBAnalysis[BB->getNumber()];
309
310   if (BBI.Kind == ICReAnalyze) {
311     BBI.BrCond.clear();
312     BBI.TrueBB = BBI.FalseBB = NULL;
313   } else {
314     if (BBI.Kind != ICNotAnalyzed)
315       return;  // Already analyzed.
316     BBI.BB = BB;
317     BBI.NonPredSize = std::distance(BB->begin(), BB->end());
318   }
319
320   // Look for 'root' of a simple (non-nested) triangle or diamond.
321   BBI.Kind = ICNotClassfied;
322   BBI.IsAnalyzable =
323     !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
324   BBI.hasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
325   // Unanalyable or ends with fallthrough or unconditional branch.
326   if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
327     return;
328   // Do not ifcvt if either path is a back edge to the entry block.
329   if (BBI.TrueBB == BB || BBI.FalseBB == BB)
330     return;
331
332   AnalyzeBlock(BBI.TrueBB);
333   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
334
335   // No false branch. This BB must end with a conditional branch and a
336   // fallthrough.
337   if (!BBI.FalseBB)
338     BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);  
339   assert(BBI.FalseBB && "Expected to find the fallthrough block!");
340
341   AnalyzeBlock(BBI.FalseBB);
342   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
343
344   // If both paths are dead, then forget about it.
345   if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
346     BBI.Kind = ICDead;
347     return;
348   }
349
350   // Look for more opportunities to if-convert a triangle. Try to restructure
351   // the CFG to form a triangle with the 'false' path.
352   std::vector<MachineOperand> RevCond(BBI.BrCond);
353   bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
354
355   if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
356       !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
357       FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
358       FeasibilityAnalysis(FalseBBI, RevCond)) {
359     // Diamond:
360     //   EBB
361     //   / \_
362     //  |   |
363     // TBB FBB
364     //   \ /
365     //  TailBB
366     // Note TailBB can be empty.
367     BBI.Kind = ICDiamond;
368     TrueBBI.Kind = FalseBBI.Kind = ICChild;
369     BBI.TailBB = TrueBBI.TrueBB;
370   } else {
371     // FIXME: Consider duplicating if BB is small.
372     if (ValidTriangle(TrueBBI, FalseBBI) &&
373         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
374       // Triangle:
375       //   EBB
376       //   | \_
377       //   |  |
378       //   | TBB
379       //   |  /
380       //   FBB
381       BBI.Kind = ICTriangle;
382       TrueBBI.Kind = ICChild;
383     } else if (ValidSimple(TrueBBI) &&
384                FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
385       // Simple (split, no rejoin):
386       //   EBB
387       //   | \_
388       //   |  |
389       //   | TBB---> exit
390       //   |    
391       //   FBB
392       BBI.Kind = ICSimple;
393       TrueBBI.Kind = ICChild;
394     } else if (CanRevCond) {
395       // Try the other path...
396       if (ValidTriangle(FalseBBI, TrueBBI) &&
397           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
398         // Reverse 'true' and 'false' paths.
399         ReverseBranchCondition(BBI);
400         BBI.Kind = ICTriangle;
401         FalseBBI.Kind = ICChild;
402       } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
403                  FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
404         ReverseBranchCondition(FalseBBI);
405         ReverseBranchCondition(BBI);
406         BBI.Kind = ICTriangle;
407         FalseBBI.Kind = ICChild;
408       } else if (ValidSimple(FalseBBI) &&
409                  FeasibilityAnalysis(FalseBBI, RevCond)) {
410         BBI.Kind = ICSimpleFalse;
411         FalseBBI.Kind = ICChild;
412       }
413     }
414   }
415   return;
416 }
417
418 /// FeasibilityAnalysis - Determine if the block is predicable. In most
419 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
420 /// Also checks if the block contains any instruction which can clobber a
421 /// predicate (e.g. condition code register). If so, the block is not
422 /// predicable unless it's the last instruction.
423 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
424                                       std::vector<MachineOperand> &Pred,
425                                       bool isTriangle, bool RevBranch) {
426   // If the block is dead, or it is going to be the entry block of a sub-CFG
427   // that will be if-converted, then it cannot be predicated.
428   if (BBI.Kind != ICNotAnalyzed &&
429       BBI.Kind != ICNotClassfied &&
430       BBI.Kind != ICChild)
431     return false;
432
433   // Check predication threshold.
434   if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
435     return false;
436
437   // If it is already predicated, check if its predicate subsumes the new
438   // predicate.
439   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
440     return false;
441
442   bool SeenPredMod = false;
443   bool SeenCondBr = false;
444   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
445        I != E; ++I) {
446     const TargetInstrDescriptor *TID = I->getInstrDescriptor();
447     if (SeenPredMod) {
448       // Predicate modification instruction should end the block (except for
449       // already predicated instructions and end of block branches).
450       if (!TII->isPredicated(I)) {
451         // This is the 'true' block of a triangle, i.e. its 'true' block is
452         // the same as the 'false' block of the entry. So false positive
453         // is ok.
454         if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
455             (TID->Flags & M_BRANCH_FLAG) != 0 &&
456             (TID->Flags & M_BARRIER_FLAG) == 0) {
457           // This is the first conditional branch, test predicate subsumsion.
458           std::vector<MachineOperand> RevPred(Pred);
459           std::vector<MachineOperand> Cond(BBI.BrCond);
460           if (RevBranch) {
461             if (TII->ReverseBranchCondition(Cond))
462               return false;
463           }
464           if (TII->ReverseBranchCondition(RevPred) ||
465               !TII->SubsumesPredicate(Cond, RevPred))
466             return false;
467           SeenCondBr = true;
468           continue;  // Conditional branches is not predicable.
469         }
470         return false;
471       }
472     }
473
474     if (TID->Flags & M_CLOBBERS_PRED) {
475       BBI.ModifyPredicate = true;
476       SeenPredMod = true;
477     }
478
479     if (!I->isPredicable())
480       return false;
481   }
482
483   return true;
484 }
485
486 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
487 /// expose more if-conversion opportunities. e.g.
488 ///
489 ///                cmp
490 ///                b le BB1
491 ///                /  \____
492 ///               /        |
493 ///             cmp        |
494 ///             b eq BB1   |
495 ///              /  \____  |
496 ///             /        \ |
497 ///                      BB1
498 ///  ==>
499 ///
500 ///                cmp
501 ///                b eq BB1
502 ///                /  \____
503 ///               /        |
504 ///             cmp        |
505 ///             b le BB1   |
506 ///              /  \____  |
507 ///             /        \ |
508 ///                      BB1
509 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
510   return false;
511 }
512
513 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
514 /// candidates. It returns true if any CFG restructuring is done to expose more
515 /// if-conversion opportunities.
516 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
517                                 std::vector<BBInfo*> &Candidates) {
518   bool Change = false;
519   std::set<MachineBasicBlock*> Visited;
520   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
521     for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
522            E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
523       MachineBasicBlock *BB = *I;
524       AnalyzeBlock(BB);
525       BBInfo &BBI = BBAnalysis[BB->getNumber()];
526       switch (BBI.Kind) {
527         case ICSimple:
528         case ICSimpleFalse:
529         case ICTriangle:
530         case ICDiamond:
531           Candidates.push_back(&BBI);
532           break;
533         default:
534           Change |= AttemptRestructuring(BBI);
535           break;
536       }
537     }
538   }
539
540   // Sort to favor more complex ifcvt scheme.
541   std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
542
543   return Change;
544 }
545
546 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
547 /// that all the intervening blocks are empty (given BB can fall through to its
548 /// next block).
549 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
550   MachineFunction::iterator I = BB;
551   MachineFunction::iterator TI = ToBB;
552   MachineFunction::iterator E = BB->getParent()->end();
553   while (++I != TI)
554     if (I == E || !I->empty())
555       return false;
556   return true;
557 }
558
559 /// getNextBlock - Returns the next block in the function blocks ordering. If
560 /// it is the end, returns NULL.
561 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
562   MachineFunction::iterator I = BB;
563   MachineFunction::iterator E = BB->getParent()->end();
564   if (++I == E)
565     return NULL;
566   return I;
567 }
568
569 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
570 /// to determine if it can be if-converted.
571 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
572   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
573          E = BB->pred_end(); PI != E; ++PI) {
574     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
575     if (PBBI.Kind == ICNotClassfied)
576       PBBI.Kind = ICReAnalyze;
577   }
578 }
579
580 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
581 ///
582 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
583                                const TargetInstrInfo *TII) {
584   std::vector<MachineOperand> NoCond;
585   TII->InsertBranch(*BB, ToBB, NULL, NoCond);
586 }
587
588 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
589 /// successors.
590 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
591   MachineBasicBlock *TBB = NULL, *FBB = NULL;
592   std::vector<MachineOperand> Cond;
593   bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
594   bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
595   if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
596     if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
597           (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
598       BBI.BB->removeSuccessor(BBI.TrueBB);
599   if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
600     if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
601           (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
602       BBI.BB->removeSuccessor(BBI.FalseBB);
603 }
604
605 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
606 ///
607 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
608   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
609   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
610   BBInfo *CvtBBI = &TrueBBI;
611   BBInfo *NextBBI = &FalseBBI;
612
613   std::vector<MachineOperand> Cond(BBI.BrCond);
614   if (BBI.Kind == ICSimpleFalse) {
615     std::swap(CvtBBI, NextBBI);
616     TII->ReverseBranchCondition(Cond);
617   }
618
619   PredicateBlock(*CvtBBI, Cond);
620
621   // Merge converted block into entry block.
622   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
623   MergeBlocks(BBI, *CvtBBI);
624
625   bool IterIfcvt = true;
626   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
627     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
628     BBI.hasFallThrough = false;
629     // Now ifcvt'd block will look like this:
630     // BB:
631     // ...
632     // t, f = cmp
633     // if t op
634     // b BBf
635     //
636     // We cannot further ifcvt this block because the unconditional branch
637     // will have to be predicated on the new condition, that will not be
638     // available if cmp executes.
639     IterIfcvt = false;
640   }
641
642   RemoveExtraEdges(BBI);
643
644   // Update block info. BB can be iteratively if-converted.
645   if (IterIfcvt)
646     BBI.Kind = ICReAnalyze;
647   else
648     BBI.Kind = ICDead;
649   ReTryPreds(BBI.BB);
650   CvtBBI->Kind = ICDead;
651
652   // FIXME: Must maintain LiveIns.
653   return true;
654 }
655
656 /// IfConvertTriangle - If convert a triangle sub-CFG.
657 ///
658 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
659   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
660
661   // Predicate the 'true' block after removing its branch.
662   TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
663   PredicateBlock(TrueBBI, BBI.BrCond);
664
665   // If 'true' block has a 'false' successor, add an exit branch to it.
666   bool HasEarlyExit = TrueBBI.FalseBB != NULL;
667   if (HasEarlyExit) {
668     std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
669     if (TII->ReverseBranchCondition(RevCond))
670       assert(false && "Unable to reverse branch condition!");
671     TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
672   }
673
674   // Now merge the entry of the triangle with the true block.
675   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
676   MergeBlocks(BBI, TrueBBI);
677
678   // Merge in the 'false' block if the 'false' block has no other
679   // predecessors. Otherwise, add a unconditional branch from to 'false'.
680   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
681   bool FalseBBDead = false;
682   bool IterIfcvt = true;
683   bool isFallThrough = canFallThroughTo(BBI.BB, FalseBBI.BB);
684   if (!isFallThrough) {
685     // Only merge them if the true block does not fallthrough to the false
686     // block. By not merging them, we make it possible to iteratively
687     // ifcvt the blocks.
688     if (!HasEarlyExit && FalseBBI.BB->pred_size() == 1) {
689       MergeBlocks(BBI, FalseBBI);
690       FalseBBDead = true;
691     } else {
692       InsertUncondBranch(BBI.BB, FalseBBI.BB, TII);
693       TrueBBI.hasFallThrough = false;
694     }
695     // Mixed predicated and unpredicated code. This cannot be iteratively
696     // predicated.
697     IterIfcvt = false;
698   }
699
700   RemoveExtraEdges(BBI);
701
702   // Update block info. BB can be iteratively if-converted.
703   if (IterIfcvt) 
704     BBI.Kind = ICReAnalyze;
705   else
706     BBI.Kind = ICDead;
707   ReTryPreds(BBI.BB);
708   TrueBBI.Kind = ICDead;
709   if (FalseBBDead)
710     FalseBBI.Kind = ICDead;
711
712   // FIXME: Must maintain LiveIns.
713   return true;
714 }
715
716 /// IfConvertDiamond - If convert a diamond sub-CFG.
717 ///
718 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
719   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
720   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
721
722   SmallVector<MachineInstr*, 2> Dups;
723   if (!BBI.TailBB) {
724     // No common merge block. Check if the terminators (e.g. return) are
725     // the same or predicable.
726     MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
727     MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
728     while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
729       if (TT->isIdenticalTo(FT))
730         Dups.push_back(TT);  // Will erase these later.
731       else if (!TT->isPredicable() && !FT->isPredicable())
732         return false; // Can't if-convert. Abort!
733       ++TT;
734       ++FT;
735     }
736
737     // One of the two pathes have more terminators, make sure they are
738     // all predicable.
739     while (TT != BBI.TrueBB->end()) {
740       if (!TT->isPredicable()) {
741         return false; // Can't if-convert. Abort!
742       }
743       ++TT;
744     }
745     while (FT != BBI.FalseBB->end()) {
746       if (!FT->isPredicable()) {
747         return false; // Can't if-convert. Abort!
748       }
749       ++FT;
750     }
751   }
752
753   // Remove the duplicated instructions from the 'true' block.
754   for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
755     Dups[i]->eraseFromParent();
756     --TrueBBI.NonPredSize;
757   }
758     
759   // Merge the 'true' and 'false' blocks by copying the instructions
760   // from the 'false' block to the 'true' block. That is, unless the true
761   // block would clobber the predicate, in that case, do the opposite.
762   BBInfo *BBI1 = &TrueBBI;
763   BBInfo *BBI2 = &FalseBBI;
764   std::vector<MachineOperand> RevCond(BBI.BrCond);
765   TII->ReverseBranchCondition(RevCond);
766   std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
767   std::vector<MachineOperand> *Cond2 = &RevCond;
768   // Check the 'true' and 'false' blocks if either isn't ended with a branch.
769   // Either the block fallthrough to another block or it ends with a
770   // return. If it's the former, add a branch to its successor.
771   bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
772   bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size(); 
773
774   if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
775       (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
776        NeedBr1 && !NeedBr2)) {
777     std::swap(BBI1, BBI2);
778     std::swap(Cond1, Cond2);
779     std::swap(NeedBr1, NeedBr2);
780   }
781
782   // Predicate the 'true' block after removing its branch.
783   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
784   PredicateBlock(*BBI1, *Cond1);
785
786   // Add an early exit branch if needed.
787   if (NeedBr1)
788     TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
789
790   // Predicate the 'false' block.
791   PredicateBlock(*BBI2, *Cond2, true);
792
793   // Add an unconditional branch from 'false' to to 'false' successor if it
794   // will not be the fallthrough block.
795   if (NeedBr2 && !NeedBr1) {
796     // If BBI2 isn't going to be merged in, then the existing fallthrough
797     // or branch is fine.
798     if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
799       InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
800       BBI2->hasFallThrough = false;
801     }
802   }
803
804   // Keep them as two separate blocks if there is an early exit.
805   if (!NeedBr1)
806     MergeBlocks(*BBI1, *BBI2);
807
808   // Remove the conditional branch from entry to the blocks.
809   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
810
811   // Merge the combined block into the entry of the diamond.
812   MergeBlocks(BBI, *BBI1);
813
814   // 'True' and 'false' aren't combined, see if we need to add a unconditional
815   // branch to the 'false' block.
816   if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
817     InsertUncondBranch(BBI.BB, BBI2->BB, TII);
818     BBI1->hasFallThrough = false;
819   }
820
821   // If the if-converted block fallthrough or unconditionally branch into the
822   // tail block, and the tail block does not have other predecessors, then
823   // fold the tail block in as well.
824   BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
825   if (BBI.TailBB &&
826       BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
827     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
828     BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
829     MergeBlocks(*CvtBBI, TailBBI);
830     TailBBI.Kind = ICDead;
831   }
832
833   RemoveExtraEdges(BBI);
834
835   // Update block info.
836   BBI.Kind = ICDead;
837   TrueBBI.Kind = ICDead;
838   FalseBBI.Kind = ICDead;
839
840   // FIXME: Must maintain LiveIns.
841   return true;
842 }
843
844 /// PredicateBlock - Predicate every instruction in the block with the specified
845 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
846 void IfConverter::PredicateBlock(BBInfo &BBI,
847                                  std::vector<MachineOperand> &Cond,
848                                  bool IgnoreTerm) {
849   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
850        I != E; ++I) {
851     if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
852       continue;
853     if (TII->isPredicated(I))
854       continue;
855     if (!TII->PredicateInstruction(I, Cond)) {
856       cerr << "Unable to predicate " << *I << "!\n";
857       abort();
858     }
859   }
860
861   BBI.NonPredSize = 0;
862   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
863
864   NumIfConvBBs++;
865 }
866
867 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
868 ///
869 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
870   ToBBI.BB->splice(ToBBI.BB->end(),
871                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
872
873   // Redirect all branches to FromBB to ToBB.
874   std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
875                                          FromBBI.BB->pred_end());
876   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
877     MachineBasicBlock *Pred = Preds[i];
878     if (Pred == ToBBI.BB)
879       continue;
880     Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
881   }
882  
883   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
884                                          FromBBI.BB->succ_end());
885   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
886   MachineBasicBlock *FallThrough = FromBBI.hasFallThrough ? NBB : NULL;
887
888   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
889     MachineBasicBlock *Succ = Succs[i];
890     // Fallthrough edge can't be transferred.
891     if (Succ == FallThrough)
892       continue;
893     FromBBI.BB->removeSuccessor(Succ);
894     if (!ToBBI.BB->isSuccessor(Succ))
895       ToBBI.BB->addSuccessor(Succ);
896   }
897
898   // Now FromBBI always fall through to the next block!
899   if (NBB)
900     FromBBI.BB->addSuccessor(NBB);
901
902   ToBBI.NonPredSize += FromBBI.NonPredSize;
903   FromBBI.NonPredSize = 0;
904
905   ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
906   ToBBI.hasFallThrough = FromBBI.hasFallThrough;
907
908   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
909             std::back_inserter(ToBBI.Predicate));
910   FromBBI.Predicate.clear();
911 }