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