9efceb08e56b530d0875aff22e443c4e32fe1362
[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/Debug.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
25 using namespace llvm;
26
27 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
28
29 namespace {
30   class IfConverter : public MachineFunctionPass {
31     enum BBICKind {
32       ICNotAnalyzed,   // BB has not been analyzed.
33       ICReAnalyze,     // BB must be re-analyzed.
34       ICNotClassfied,  // BB data valid, but not classified.
35       ICEarlyExit,     // BB is entry of an early-exit sub-CFG.
36       ICEarlyExitFalse,// Same as ICEarlyExit, but on the false path.
37       ICTriangle,      // BB is entry of a triangle sub-CFG.
38       ICDiamond,       // BB is entry of a diamond sub-CFG.
39       ICChild,         // BB is part of the sub-CFG that'll be predicated.
40       ICDead           // BB has been converted and merged, it's now dead.
41     };
42
43     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
44     /// if-conversion feasibility analysis. This includes results from
45     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
46     /// classification, and common tail block of its successors (if it's a
47     /// diamond shape), its size, whether it's predicable, and whether any
48     /// instruction can clobber the 'would-be' predicate.
49     ///
50     /// Kind            - Type of block. See BBICKind.
51     /// NonPredSize     - Number of non-predicated instructions.
52     /// isPredicable    - Is it predicable. (FIXME: Remove.)
53     /// hasEarlyExit    - Ends with a return, indirect jump or br to jumptable.
54     /// ModifyPredicate - FIXME: Not used right now. True if BB would modify
55     ///                   the predicate (e.g. has cmp, call, etc.)
56     /// BB              - Corresponding MachineBasicBlock.
57     /// TrueBB / FalseBB- See AnalyzeBranch().
58     /// BrCond          - Conditions for end of block conditional branches.
59     /// Predicate       - Predicate used in the BB.
60     struct BBInfo {
61       BBICKind Kind;
62       unsigned NonPredSize;
63       bool isPredicable;
64       bool hasEarlyExit;
65       bool ModifyPredicate;
66       MachineBasicBlock *BB;
67       MachineBasicBlock *TrueBB;
68       MachineBasicBlock *FalseBB;
69       MachineBasicBlock *TailBB;
70       std::vector<MachineOperand> BrCond;
71       std::vector<MachineOperand> Predicate;
72       BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0), isPredicable(false),
73                  hasEarlyExit(false), ModifyPredicate(false),
74                  BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
75     };
76
77     /// Roots - Basic blocks that do not have successors. These are the starting
78     /// points of Graph traversal.
79     std::vector<MachineBasicBlock*> Roots;
80
81     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
82     /// basic block number.
83     std::vector<BBInfo> BBAnalysis;
84
85     const TargetLowering *TLI;
86     const TargetInstrInfo *TII;
87     bool MadeChange;
88   public:
89     static char ID;
90     IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
91
92     virtual bool runOnMachineFunction(MachineFunction &MF);
93     virtual const char *getPassName() const { return "If converter"; }
94
95   private:
96     void StructuralAnalysis(MachineBasicBlock *BB);
97     void FeasibilityAnalysis(BBInfo &BBI,
98                              std::vector<MachineOperand> &Cond);
99     bool AttemptRestructuring(BBInfo &BBI);
100     bool AnalyzeBlocks(MachineFunction &MF,
101                        std::vector<BBInfo*> &Candidates);
102     void ReTryPreds(MachineBasicBlock *BB);
103     bool IfConvertEarlyExit(BBInfo &BBI);
104     bool IfConvertTriangle(BBInfo &BBI);
105     bool IfConvertDiamond(BBInfo &BBI);
106     void PredicateBlock(BBInfo &BBI,
107                         std::vector<MachineOperand> &Cond,
108                         bool IgnoreTerm = false);
109     void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
110
111     // IfcvtCandidateCmp - Used to sort if-conversion candidates.
112     static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
113       // Favor diamond over triangle, etc.
114       return (unsigned)C1->Kind < (unsigned)C2->Kind;
115     }
116   };
117   char IfConverter::ID = 0;
118 }
119
120 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
121
122 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
123   TLI = MF.getTarget().getTargetLowering();
124   TII = MF.getTarget().getInstrInfo();
125   if (!TII) return false;
126
127   DOUT << "\nIfcvt: function \'" << MF.getFunction()->getName() << "\'\n";
128
129   MF.RenumberBlocks();
130   BBAnalysis.resize(MF.getNumBlockIDs());
131
132   // Look for root nodes, i.e. blocks without successors.
133   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
134     if (I->succ_size() == 0)
135       Roots.push_back(I);
136
137   std::vector<BBInfo*> Candidates;
138   MadeChange = false;
139   while (true) {
140     bool Change = false;
141
142     // Do an intial analysis for each basic block and finding all the potential
143     // candidates to perform if-convesion.
144     Change |= AnalyzeBlocks(MF, Candidates);
145     while (!Candidates.empty()) {
146       BBInfo &BBI = *Candidates.back();
147       Candidates.pop_back();
148       switch (BBI.Kind) {
149       default: assert(false && "Unexpected!");
150         break;
151       case ICReAnalyze:
152         // One or more of 'childrean' have been modified, abort!
153         break;
154       case ICEarlyExit:
155       case ICEarlyExitFalse:
156         DOUT << "Ifcvt (Early exit): BB#" << BBI.BB->getNumber() << "\n";
157         Change |= IfConvertEarlyExit(BBI);
158         break;
159       case ICTriangle:
160         DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << "\n";
161         Change |= IfConvertTriangle(BBI);
162         break;
163       case ICDiamond:
164         DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << "\n";
165         Change |= IfConvertDiamond(BBI);
166         break;
167       }
168     }
169
170     MadeChange |= Change;
171     if (!Change)
172       break;
173   }
174
175   Roots.clear();
176   BBAnalysis.clear();
177
178   return MadeChange;
179 }
180
181 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
182                                          MachineBasicBlock *TrueBB) {
183   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
184          E = BB->succ_end(); SI != E; ++SI) {
185     MachineBasicBlock *SuccBB = *SI;
186     if (SuccBB != TrueBB)
187       return SuccBB;
188   }
189   return NULL;
190 }
191
192 /// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
193 /// the specified block. Record its successors and whether it looks like an
194 /// if-conversion candidate.
195 void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
196   BBInfo &BBI = BBAnalysis[BB->getNumber()];
197
198   if (BBI.Kind != ICReAnalyze) {
199     if (BBI.Kind != ICNotAnalyzed)
200       return;  // Already analyzed.
201     BBI.BB = BB;
202     BBI.NonPredSize = std::distance(BB->begin(), BB->end());
203   }
204
205   // Look for 'root' of a simple (non-nested) triangle or diamond.
206   BBI.Kind = ICNotClassfied;
207   bool CanAnalyze = !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB,
208                                         BBI.BrCond);
209   // Does it end with a return, indirect jump, or jumptable branch?
210   BBI.hasEarlyExit = TII->BlockHasNoFallThrough(*BB) && !BBI.TrueBB;
211   if (!CanAnalyze || !BBI.TrueBB || BBI.BrCond.size() == 0)
212     return;
213
214   // Not a candidate if 'true' block is going to be if-converted.
215   StructuralAnalysis(BBI.TrueBB);
216   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
217
218   // TODO: Only handle very simple cases for now.
219   if (TrueBBI.FalseBB || TrueBBI.BrCond.size())
220     return;
221
222   // No false branch. This BB must end with a conditional branch and a
223   // fallthrough.
224   if (!BBI.FalseBB)
225     BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);  
226   assert(BBI.FalseBB && "Expected to find the fallthrough block!");
227
228   // Not a candidate if 'false' block is going to be if-converted.
229   StructuralAnalysis(BBI.FalseBB);
230   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
231
232   // TODO: Only handle very simple cases for now.
233   if (FalseBBI.FalseBB || FalseBBI.BrCond.size())
234     return;
235
236   unsigned TrueNumPreds  = BBI.TrueBB->pred_size();
237   unsigned FalseNumPreds = BBI.FalseBB->pred_size();
238   if ((TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
239       !(FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
240     BBI.Kind = ICEarlyExit;
241     TrueBBI.Kind = ICChild;
242   } else if (!(TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
243              (FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
244     BBI.Kind = ICEarlyExitFalse;
245     FalseBBI.Kind = ICChild;
246   } else if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
247     // Triangle:
248     //   EBB
249     //   | \_
250     //   |  |
251     //   | TBB
252     //   |  /
253     //   FBB
254     BBI.Kind = ICTriangle;
255     TrueBBI.Kind = FalseBBI.Kind = ICChild;
256   } else if (TrueBBI.TrueBB == FalseBBI.TrueBB &&
257              TrueNumPreds <= 1 && FalseNumPreds <= 1) {
258     // Diamond:
259     //   EBB
260     //   / \_
261     //  |   |
262     // TBB FBB
263     //   \ /
264     //  TailBB
265     // Note MBB can be empty in case both TBB and FBB are return blocks.
266     BBI.Kind = ICDiamond;
267     TrueBBI.Kind = FalseBBI.Kind = ICChild;
268     BBI.TailBB = TrueBBI.TrueBB;
269   }
270   return;
271 }
272
273 /// FeasibilityAnalysis - Determine if the block is predicable. In most
274 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
275 /// Also checks if the block contains any instruction which can clobber a
276 /// predicate (e.g. condition code register). If so, the block is not
277 /// predicable unless it's the last instruction. Note, this function assumes
278 /// all the terminator instructions can be converted or deleted so it ignore
279 /// them.
280 void IfConverter::FeasibilityAnalysis(BBInfo &BBI,
281                                       std::vector<MachineOperand> &Cond) {
282   if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
283     return;
284
285   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
286        I != E; ++I) {
287     // TODO: check if instruction clobbers predicate.
288     if (!I->isPredicable())
289       return;
290   }
291
292   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
293     return;
294
295   BBI.isPredicable = true;
296 }
297
298 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
299 /// expose more if-conversion opportunities. e.g.
300 ///
301 ///                cmp
302 ///                b le BB1
303 ///                /  \____
304 ///               /        |
305 ///             cmp        |
306 ///             b eq BB1   |
307 ///              /  \____  |
308 ///             /        \ |
309 ///                      BB1
310 ///  ==>
311 ///
312 ///                cmp
313 ///                b eq BB1
314 ///                /  \____
315 ///               /        |
316 ///             cmp        |
317 ///             b le BB1   |
318 ///              /  \____  |
319 ///             /        \ |
320 ///                      BB1
321 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
322   return false;
323 }
324
325 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
326 /// candidates. It returns true if any CFG restructuring is done to expose more
327 /// if-conversion opportunities.
328 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
329                                 std::vector<BBInfo*> &Candidates) {
330   bool Change = false;
331   std::set<MachineBasicBlock*> Visited;
332   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
333     for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
334            E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
335       MachineBasicBlock *BB = *I;
336       StructuralAnalysis(BB);
337       BBInfo &BBI = BBAnalysis[BB->getNumber()];
338       switch (BBI.Kind) {
339         case ICEarlyExit:
340         case ICEarlyExitFalse:
341         case ICTriangle:
342         case ICDiamond:
343           Candidates.push_back(&BBI);
344           break;
345         default:
346           Change |= AttemptRestructuring(BBI);
347           break;
348       }
349     }
350   }
351
352   // Sort to favor more complex ifcvt scheme.
353   std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
354
355   return Change;
356 }
357
358 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
359 ///
360 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
361    std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
362                                          FromBB->pred_end());
363     for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
364       MachineBasicBlock *Pred = Preds[i];
365       Pred->removeSuccessor(FromBB);
366       if (!Pred->isSuccessor(ToBB))
367         Pred->addSuccessor(ToBB);
368     }
369 }
370
371 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
372 ///
373 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
374    std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
375                                          FromBB->succ_end());
376     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
377       MachineBasicBlock *Succ = Succs[i];
378       FromBB->removeSuccessor(Succ);
379       if (!ToBB->isSuccessor(Succ))
380         ToBB->addSuccessor(Succ);
381     }
382 }
383
384 /// isNextBlock - Returns true if ToBB the next basic block after BB.
385 ///
386 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
387   MachineFunction::iterator Fallthrough = BB;
388   return MachineFunction::iterator(ToBB) == ++Fallthrough;
389 }
390
391 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
392 /// to determine if it can be if-converted.
393 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
394   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
395          E = BB->pred_end(); PI != E; ++PI) {
396     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
397     PBBI.Kind = ICReAnalyze;
398   }
399 }
400
401 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
402 ///
403 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
404                                const TargetInstrInfo *TII) {
405   std::vector<MachineOperand> NoCond;
406   TII->InsertBranch(*BB, ToBB, NULL, NoCond);
407 }
408
409 /// IfConvertEarlyExit - If convert a early exit sub-CFG.
410 ///
411 bool IfConverter::IfConvertEarlyExit(BBInfo &BBI) {
412   bool ReverseCond = BBI.Kind == ICEarlyExitFalse;
413
414   BBI.Kind = ICNotClassfied;
415
416   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
417   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
418   BBInfo *CvtBBI = &TrueBBI;
419   BBInfo *NextBBI = &FalseBBI;
420
421   std::vector<MachineOperand> NewCond(BBI.BrCond);
422   if (ReverseCond) {
423     std::swap(CvtBBI, NextBBI);
424     TII->ReverseBranchCondition(NewCond);
425   }
426   FeasibilityAnalysis(*CvtBBI, NewCond);
427   if (!CvtBBI->isPredicable)
428     return false;
429
430   PredicateBlock(*CvtBBI, NewCond);
431
432   // Merge converted block into entry block. Also convert the end of the
433   // block conditional branch (to the non-converted block) into an
434   // unconditional one.
435   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
436   MergeBlocks(BBI, *CvtBBI);
437   if (!isNextBlock(BBI.BB, NextBBI->BB))
438     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
439   std::copy(NewCond.begin(), NewCond.end(), std::back_inserter(BBI.Predicate));
440
441   // Update block info. BB can be iteratively if-converted.
442   BBI.Kind = ICNotAnalyzed;
443   BBI.TrueBB = BBI.FalseBB = NULL;
444   BBI.BrCond.clear();
445   TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
446   ReTryPreds(BBI.BB);
447   CvtBBI->Kind = ICDead;
448
449   // FIXME: Must maintain LiveIns.
450   NumIfConvBBs++;
451   return true;
452 }
453
454 /// IfConvertTriangle - If convert a triangle sub-CFG.
455 ///
456 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
457   BBI.Kind = ICNotClassfied;
458
459   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
460   FeasibilityAnalysis(TrueBBI, BBI.BrCond);
461   if (!TrueBBI.isPredicable)
462     return false;
463
464   // FIXME: Consider duplicating if BB is small.
465   if (BBI.TrueBB->pred_size() > 1)
466     return false;
467
468   // Predicate the 'true' block after removing its branch.
469   TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
470   PredicateBlock(TrueBBI, BBI.BrCond);
471
472   // If 'true' block has a 'false' successor, add a early exit branch to it.
473   if (TrueBBI.FalseBB) {
474     std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
475     if (TII->ReverseBranchCondition(RevCond))
476       assert(false && "Unable to reverse branch condition!");
477     TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
478   }
479
480   // Join the 'true' and 'false' blocks if the 'false' block has no other
481   // predecessors. Otherwise, add a unconditional branch from 'true' to 'false'.
482   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
483   if (FalseBBI.BB->pred_size() == 2)
484     MergeBlocks(TrueBBI, FalseBBI);
485   else
486     InsertUncondBranch(TrueBBI.BB, FalseBBI.BB, TII);
487
488   // Now merge the entry of the triangle with the true block.
489   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
490   MergeBlocks(BBI, TrueBBI);
491   std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
492             std::back_inserter(BBI.Predicate));
493
494   // Update block info. BB can be iteratively if-converted.
495   BBI.Kind = ICNotClassfied;
496   BBI.TrueBB = BBI.FalseBB = NULL;
497   BBI.BrCond.clear();
498   TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
499   ReTryPreds(BBI.BB);
500   TrueBBI.Kind = ICDead;
501
502   // FIXME: Must maintain LiveIns.
503   NumIfConvBBs++;
504   return true;
505 }
506
507 /// IfConvertDiamond - If convert a diamond sub-CFG.
508 ///
509 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
510   BBI.Kind = ICNotClassfied;
511
512   bool TrueNeedBr;
513   bool FalseNeedBr;
514   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
515   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
516   FeasibilityAnalysis(TrueBBI, BBI.BrCond);
517   std::vector<MachineOperand> RevCond(BBI.BrCond);
518   TII->ReverseBranchCondition(RevCond);
519   FeasibilityAnalysis(FalseBBI, RevCond);
520
521   SmallVector<MachineInstr*, 2> Dups;
522   bool Proceed = TrueBBI.isPredicable && FalseBBI.isPredicable;
523   if (Proceed) {
524     // Check the 'true' and 'false' blocks if either isn't ended with a branch.
525     // Either the block fallthrough to another block or it ends with a
526     // return. If it's the former, add a branch to its successor.
527     TrueNeedBr  = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
528     FalseNeedBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
529     if (TrueNeedBr && TrueBBI.ModifyPredicate) {
530       TrueBBI.isPredicable = false;
531       Proceed = false;
532     }
533     if (FalseNeedBr && FalseBBI.ModifyPredicate) {
534       FalseBBI.isPredicable = false;
535       Proceed = false;
536     }
537
538     if (Proceed) {
539       if (!BBI.TailBB) {
540         // No common merge block. Check if the terminators (e.g. return) are
541         // the same or predicable.
542         MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
543         MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
544         while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
545           if (TT->isIdenticalTo(FT))
546             Dups.push_back(TT);  // Will erase these later.
547           else if (!TT->isPredicable() && !FT->isPredicable()) {
548             Proceed = false;
549             break; // Can't if-convert. Abort!
550           }
551           ++TT;
552           ++FT;
553         }
554
555         // One of the two pathes have more terminators, make sure they are
556         // all predicable.
557         while (Proceed && TT != BBI.TrueBB->end())
558           if (!TT->isPredicable()) {
559             Proceed = false;
560             break; // Can't if-convert. Abort!
561           }
562         while (Proceed && FT != BBI.FalseBB->end())
563           if (!FT->isPredicable()) {
564             Proceed = false;
565             break; // Can't if-convert. Abort!
566           }
567       }
568     }
569   }
570
571   if (!Proceed)
572     return false;
573
574   // Remove the duplicated instructions from the 'true' block.
575   for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
576     Dups[i]->eraseFromParent();
577     --TrueBBI.NonPredSize;
578   }
579     
580   // Predicate the 'true' block after removing its branch.
581   TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
582   PredicateBlock(TrueBBI, BBI.BrCond);
583
584   // Predicate the 'false' block.
585   PredicateBlock(FalseBBI, RevCond, true);
586
587   // Merge the 'true' and 'false' blocks by copying the instructions
588   // from the 'false' block to the 'true' block. That is, unless the true
589   // block would clobber the predicate, in that case, do the opposite.
590   BBInfo *CvtBBI;
591   if (!TrueBBI.ModifyPredicate) {
592     // Add a conditional branch from 'true' to 'true' successor if needed.
593     if (TrueNeedBr)
594       TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL,
595                         BBI.BrCond);
596     // Add an unconditional branch from 'false' to to 'false' successor if it
597     // will not be the fallthrough block.
598     if (FalseNeedBr &&
599         !isNextBlock(BBI.BB, *BBI.FalseBB->succ_begin()))
600       InsertUncondBranch(BBI.FalseBB, *BBI.FalseBB->succ_begin(), TII);
601     MergeBlocks(TrueBBI, FalseBBI);
602     CvtBBI = &TrueBBI;
603   } else {
604     // Add a conditional branch from 'false' to 'false' successor if needed.
605     if (FalseNeedBr)
606       TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
607                         RevCond);
608     // Add an unconditional branch from 'true' to to 'true' successor if it
609     // will not be the fallthrough block.
610     if (TrueNeedBr &&
611         !isNextBlock(BBI.BB, *BBI.TrueBB->succ_begin()))
612       InsertUncondBranch(BBI.TrueBB, *BBI.TrueBB->succ_begin(), TII);
613     MergeBlocks(FalseBBI, TrueBBI);
614     CvtBBI = &FalseBBI;
615   }
616
617   // Remove the conditional branch from entry to the blocks.
618   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
619
620   bool OkToIfcvt = true;
621   // Merge the combined block into the entry of the diamond if the entry
622   // block is its only predecessor. Otherwise, insert an unconditional
623   // branch from entry to the if-converted block.
624   if (CvtBBI->BB->pred_size() == 1) {
625     MergeBlocks(BBI, *CvtBBI);
626     CvtBBI = &BBI;
627     OkToIfcvt = false;
628   } else
629     InsertUncondBranch(BBI.BB, CvtBBI->BB, TII);
630
631   // If the if-converted block fallthrough or unconditionally branch into the
632   // tail block, and the tail block does not have other predecessors, then
633   // fold the tail block in as well.
634   if (BBI.TailBB &&
635       BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
636     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
637     BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
638     MergeBlocks(*CvtBBI, TailBBI);
639     TailBBI.Kind = ICDead;
640   }
641
642   // Update block info. BB may be iteratively if-converted.
643   if (OkToIfcvt) {
644     BBI.Kind = ICNotClassfied;
645     BBI.TrueBB = BBI.FalseBB = NULL;
646     BBI.BrCond.clear();
647     TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
648     ReTryPreds(BBI.BB);
649   }
650   TrueBBI.Kind = ICDead;
651   FalseBBI.Kind = ICDead;
652
653   // FIXME: Must maintain LiveIns.
654   NumIfConvBBs += 2;
655   return true;
656 }
657
658 /// PredicateBlock - Predicate every instruction in the block with the specified
659 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
660 void IfConverter::PredicateBlock(BBInfo &BBI,
661                                  std::vector<MachineOperand> &Cond,
662                                  bool IgnoreTerm) {
663   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
664        I != E; ++I) {
665     MachineInstr *MI = I;
666     if (IgnoreTerm && TII->isTerminatorInstr(MI->getOpcode()))
667       continue;
668     if (TII->isPredicated(MI))
669       continue;
670     if (!TII->PredicateInstruction(MI, Cond)) {
671       cerr << "Unable to predicate " << *I << "!\n";
672       abort();
673     }
674   }
675
676   BBI.NonPredSize = 0;
677 }
678
679 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
680 ///
681 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
682   ToBBI.BB->splice(ToBBI.BB->end(),
683                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
684
685   // If FromBBI is previously a successor, remove it from ToBBI's successor
686   // list and update its TrueBB / FalseBB field if needed.
687   if (ToBBI.BB->isSuccessor(FromBBI.BB))
688     ToBBI.BB->removeSuccessor(FromBBI.BB);
689
690   // Transfer preds / succs and update size.
691   TransferPreds(ToBBI.BB, FromBBI.BB);
692   TransferSuccs(ToBBI.BB, FromBBI.BB);
693   ToBBI.NonPredSize += FromBBI.NonPredSize;
694   FromBBI.NonPredSize = 0;
695 }