Really turn if-converter loose:
[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> DisableSimpleF("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> DisableTriangleR("disable-ifcvt-triangle-rev", 
40                                  cl::init(false), cl::Hidden);
41   cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false", 
42                                  cl::init(false), cl::Hidden);
43   cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev", 
44                                   cl::init(false), cl::Hidden);
45   cl::opt<bool> DisableDiamond("disable-ifcvt-diamond", 
46                                cl::init(false), cl::Hidden);
47 }
48
49 STATISTIC(NumSimple,       "Number of simple if-conversions performed");
50 STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
51 STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
52 STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
53 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
54 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
55 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
56 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
57 STATISTIC(NumDupBBs,       "Number of duplicated blocks");
58
59 namespace {
60   class IfConverter : public MachineFunctionPass {
61     enum IfcvtKind {
62       ICNotClassfied,  // BB data valid, but not classified.
63       ICSimpleFalse,   // Same as ICSimple, but on the false path.
64       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
65       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
66       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
67       ICTriangleFalse, // Same as ICTriangle, but on the false path.
68       ICTriangle,      // BB is entry of a triangle sub-CFG.
69       ICDiamond        // BB is entry of a diamond sub-CFG.
70     };
71
72     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
73     /// if-conversion feasibility analysis. This includes results from
74     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
75     /// classification, and common tail block of its successors (if it's a
76     /// diamond shape), its size, whether it's predicable, and whether any
77     /// instruction can clobber the 'would-be' predicate.
78     ///
79     /// IsDone          - True if BB is not to be considered for ifcvt.
80     /// IsBeingAnalyzed - True if BB is currently being analyzed.
81     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
82     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
83     /// IsBrAnalyzable  - True if AnalyzeBranch() returns false.
84     /// HasFallThrough  - True if BB may fallthrough to the following BB.
85     /// IsUnpredicable  - True if BB is known to be unpredicable.
86     /// ClobbersPredicate- True if BB would modify the predicate (e.g. has
87     ///                   cmp, call, etc.)
88     /// NonPredSize     - Number of non-predicated instructions.
89     /// BB              - Corresponding MachineBasicBlock.
90     /// TrueBB / FalseBB- See AnalyzeBranch().
91     /// BrCond          - Conditions for end of block conditional branches.
92     /// Predicate       - Predicate used in the BB.
93     struct BBInfo {
94       bool IsDone          : 1;
95       bool IsBeingAnalyzed : 1;
96       bool IsAnalyzed      : 1;
97       bool IsEnqueued      : 1;
98       bool IsBrAnalyzable  : 1;
99       bool HasFallThrough  : 1;
100       bool IsUnpredicable  : 1;
101       bool CannotBeCopied  : 1;
102       bool ClobbersPred    : 1;
103       unsigned NonPredSize;
104       MachineBasicBlock *BB;
105       MachineBasicBlock *TrueBB;
106       MachineBasicBlock *FalseBB;
107       std::vector<MachineOperand> BrCond;
108       std::vector<MachineOperand> Predicate;
109       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
110                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
111                  HasFallThrough(false), IsUnpredicable(false),
112                  CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
113                  BB(0), TrueBB(0), FalseBB(0) {}
114     };
115
116     /// IfcvtToken - Record information about pending if-conversions to attemp:
117     /// BBI             - Corresponding BBInfo.
118     /// Kind            - Type of block. See IfcvtKind.
119     /// NeedSubsumsion  - True if the to be predicated BB has already been
120     ///                   predicated.
121     /// Duplicates      - Number of instructions that would be duplicated due
122     ///                   to this if-conversion.
123     struct IfcvtToken {
124       BBInfo &BBI;
125       IfcvtKind Kind;
126       bool NeedSubsumsion;
127       unsigned Duplicates;
128       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d)
129         : BBI(b), Kind(k), NeedSubsumsion(s), Duplicates(d) {}
130     };
131
132     /// Roots - Basic blocks that do not have successors. These are the starting
133     /// points of Graph traversal.
134     std::vector<MachineBasicBlock*> Roots;
135
136     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
137     /// basic block number.
138     std::vector<BBInfo> BBAnalysis;
139
140     const TargetLowering *TLI;
141     const TargetInstrInfo *TII;
142     bool MadeChange;
143   public:
144     static char ID;
145     IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
146
147     virtual bool runOnMachineFunction(MachineFunction &MF);
148     virtual const char *getPassName() const { return "If converter"; }
149
150   private:
151     bool ReverseBranchCondition(BBInfo &BBI);
152     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
153     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
154                        bool FalseBranch, unsigned &Dups) const;
155     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
156     void ScanInstructions(BBInfo &BBI);
157     BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
158                          std::vector<IfcvtToken*> &Tokens);
159     bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
160                              bool isTriangle = false, bool RevBranch = false);
161     bool AnalyzeBlocks(MachineFunction &MF,
162                        std::vector<IfcvtToken*> &Tokens);
163     void ReTryPreds(MachineBasicBlock *BB);
164     void RemoveExtraEdges(BBInfo &BBI);
165     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
166     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
167     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind);
168     void PredicateBlock(BBInfo &BBI,
169                         std::vector<MachineOperand> &Cond,
170                         bool IgnoreTerm = false);
171     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
172                                std::vector<MachineOperand> &Cond,
173                                bool IgnoreBr = false);
174     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
175
176     // blockAlwaysFallThrough - Block ends without a terminator.
177     bool blockAlwaysFallThrough(BBInfo &BBI) const {
178       return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
179     }
180
181     // IfcvtTokenCmp - Used to sort if-conversion candidates.
182     static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
183       // Favors subsumsion.
184       if (C1->NeedSubsumsion == false && C2->NeedSubsumsion == true)
185         return true;
186       else if (C1->NeedSubsumsion == C2->NeedSubsumsion) {
187         if (C1->Duplicates > C2->Duplicates)
188           return true;
189         else if (C1->Duplicates == C2->Duplicates) {
190           // Favors diamond over triangle, etc.
191           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
192             return true;
193           else if (C1->Kind == C2->Kind)
194             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
195         }
196       }
197       return false;
198     }
199   };
200
201   char IfConverter::ID = 0;
202 }
203
204 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
205
206 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
207   TLI = MF.getTarget().getTargetLowering();
208   TII = MF.getTarget().getInstrInfo();
209   if (!TII) return false;
210
211   static int FnNum = -1;
212   DOUT << "\nIfcvt: function (" << ++FnNum <<  ") \'"
213        << MF.getFunction()->getName() << "\'";
214
215   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
216     DOUT << " skipped\n";
217     return false;
218   }
219   DOUT << "\n";
220
221   MF.RenumberBlocks();
222   BBAnalysis.resize(MF.getNumBlockIDs());
223
224   // Look for root nodes, i.e. blocks without successors.
225   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
226     if (I->succ_size() == 0)
227       Roots.push_back(I);
228
229   std::vector<IfcvtToken*> Tokens;
230   MadeChange = false;
231   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
232     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
233   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
234     // Do an intial analysis for each basic block and finding all the potential
235     // candidates to perform if-convesion.
236     bool Change = AnalyzeBlocks(MF, Tokens);
237     while (!Tokens.empty()) {
238       IfcvtToken *Token = Tokens.back();
239       Tokens.pop_back();
240       BBInfo &BBI = Token->BBI;
241       IfcvtKind Kind = Token->Kind;
242
243       // If the block has been evicted out of the queue or it has already been
244       // marked dead (due to it being predicated), then skip it.
245       if (BBI.IsDone)
246         BBI.IsEnqueued = false;
247       if (!BBI.IsEnqueued)
248         continue;
249
250       BBI.IsEnqueued = false;
251
252       bool RetVal = false;
253       switch (Kind) {
254       default: assert(false && "Unexpected!");
255         break;
256       case ICSimple:
257       case ICSimpleFalse: {
258         bool isFalse = Kind == ICSimpleFalse;
259         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
260         DOUT << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"")
261              << "): BB#" << BBI.BB->getNumber() << " ("
262              << ((Kind == ICSimpleFalse)
263                  ? BBI.FalseBB->getNumber()
264                  : BBI.TrueBB->getNumber()) << ") ";
265         RetVal = IfConvertSimple(BBI, Kind);
266         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
267         if (RetVal)
268           if (isFalse) NumSimpleFalse++;
269           else         NumSimple++;
270        break;
271       }
272       case ICTriangle:
273       case ICTriangleRev:
274       case ICTriangleFalse:
275       case ICTriangleFRev: {
276         bool isFalse = Kind == ICTriangleFalse;
277         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
278         if (DisableTriangle && !isFalse && !isRev) break;
279         if (DisableTriangleR && !isFalse && isRev) break;
280         if (DisableTriangleF && isFalse && !isRev) break;
281         if (DisableTriangleFR && isFalse && isRev) break;
282         DOUT << "Ifcvt (Triangle";
283         if (isFalse)
284           DOUT << " false";
285         if (isRev)
286           DOUT << " rev";
287         DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
288              << BBI.TrueBB->getNumber() << ",F:"
289              << BBI.FalseBB->getNumber() << ") ";
290         RetVal = IfConvertTriangle(BBI, Kind);
291         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
292         if (RetVal) {
293           if (isFalse) {
294             if (isRev) NumTriangleFRev++;
295             else       NumTriangleFalse++;
296           } else {
297             if (isRev) NumTriangleRev++;
298             else       NumTriangle++;
299           }
300         }
301         break;
302       }
303       case ICDiamond: {
304         if (DisableDiamond) break;
305         DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
306              << BBI.TrueBB->getNumber() << ",F:"
307              << BBI.FalseBB->getNumber() << ") ";
308         RetVal = IfConvertDiamond(BBI, Kind);
309         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
310         if (RetVal) NumDiamonds++;
311         break;
312       }
313       }
314
315       Change |= RetVal;
316
317       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
318         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
319       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
320         break;
321     }
322
323     if (!Change)
324       break;
325     MadeChange |= Change;
326   }
327
328   // Delete tokens in case of early exit.
329   while (!Tokens.empty()) {
330     IfcvtToken *Token = Tokens.back();
331     Tokens.pop_back();
332     delete Token;
333   }
334
335   Tokens.clear();
336   Roots.clear();
337   BBAnalysis.clear();
338
339   return MadeChange;
340 }
341
342 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
343 /// its 'true' successor.
344 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
345                                          MachineBasicBlock *TrueBB) {
346   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
347          E = BB->succ_end(); SI != E; ++SI) {
348     MachineBasicBlock *SuccBB = *SI;
349     if (SuccBB != TrueBB)
350       return SuccBB;
351   }
352   return NULL;
353 }
354
355 /// ReverseBranchCondition - Reverse the condition of the end of the block
356 /// branchs. Swap block's 'true' and 'false' successors.
357 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
358   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
359     TII->RemoveBranch(*BBI.BB);
360     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
361     std::swap(BBI.TrueBB, BBI.FalseBB);
362     return true;
363   }
364   return false;
365 }
366
367 /// getNextBlock - Returns the next block in the function blocks ordering. If
368 /// it is the end, returns NULL.
369 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
370   MachineFunction::iterator I = BB;
371   MachineFunction::iterator E = BB->getParent()->end();
372   if (++I == E)
373     return NULL;
374   return I;
375 }
376
377 /// ValidSimple - Returns true if the 'true' block (along with its
378 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
379 /// number of instructions that the ifcvt would need to duplicate if performed
380 /// in Dups.
381 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
382   Dups = 0;
383   if (TrueBBI.IsBeingAnalyzed)
384     return false;
385
386   if (TrueBBI.BB->pred_size() > 1) {
387     if (TrueBBI.CannotBeCopied ||
388         TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
389       return false;
390     Dups = TrueBBI.NonPredSize;
391   }
392
393   return !blockAlwaysFallThrough(TrueBBI) && TrueBBI.BrCond.size() == 0;
394 }
395
396 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
397 /// with their common predecessor) forms a valid triangle shape for ifcvt.
398 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
399 /// branches to the false branch rather than the other way around. It also
400 /// returns the number of instructions that the ifcvt would need to duplicate
401 /// if performed in 'Dups'.
402 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
403                                 bool FalseBranch, unsigned &Dups) const {
404   Dups = 0;
405   if (TrueBBI.IsBeingAnalyzed)
406     return false;
407
408   if (TrueBBI.BB->pred_size() > 1) {
409     if (TrueBBI.CannotBeCopied)
410       return false;
411
412     unsigned Size = TrueBBI.NonPredSize;
413     if (TrueBBI.IsBrAnalyzable) {
414       if (TrueBBI.TrueBB && TrueBBI.BrCond.size() == 0)
415         // End with an unconditional branch. It will be removed.
416         --Size;
417       else {
418         MachineBasicBlock *FExit = FalseBranch
419           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
420         if (FExit)
421           // Require a conditional branch
422           ++Size;
423       }
424     }
425     if (Size > TLI->getIfCvtDupBlockSizeLimit())
426       return false;
427     Dups = Size;
428   }
429
430   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
431   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
432     MachineFunction::iterator I = TrueBBI.BB;
433     if (++I == TrueBBI.BB->getParent()->end())
434       return false;
435     TExit = I;
436   }
437   return TExit && TExit == FalseBBI.BB;
438 }
439
440 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
441 /// with their common predecessor) forms a valid diamond shape for ifcvt.
442 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
443   if (TrueBBI.IsBeingAnalyzed || FalseBBI.IsBeingAnalyzed)
444     return false;
445
446   MachineBasicBlock *TT = TrueBBI.TrueBB;
447   MachineBasicBlock *FT = FalseBBI.TrueBB;
448
449   if (!TT && blockAlwaysFallThrough(TrueBBI))
450     TT = getNextBlock(TrueBBI.BB);
451   if (!FT && blockAlwaysFallThrough(FalseBBI))
452     FT = getNextBlock(FalseBBI.BB);
453   if (TT != FT)
454     return false;
455   if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
456     return false;
457   // FIXME: Allow false block to have an early exit?
458   return (TrueBBI.BB->pred_size() == 1 &&
459           FalseBBI.BB->pred_size() == 1 &&
460           !TrueBBI.FalseBB && !FalseBBI.FalseBB);
461 }
462
463 /// ScanInstructions - Scan all the instructions in the block to determine if
464 /// the block is predicable. In most cases, that means all the instructions
465 /// in the block has M_PREDICABLE flag. Also checks if the block contains any
466 /// instruction which can clobber a predicate (e.g. condition code register).
467 /// If so, the block is not predicable unless it's the last instruction.
468 void IfConverter::ScanInstructions(BBInfo &BBI) {
469   if (BBI.IsDone)
470     return;
471
472   // First analyze the end of BB branches.
473   BBI.TrueBB = BBI.FalseBB = NULL;
474   BBI.BrCond.clear();
475   BBI.IsBrAnalyzable =
476     !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
477   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
478
479   if (BBI.BrCond.size()) {
480     // No false branch. This BB must end with a conditional branch and a
481     // fallthrough.
482     if (!BBI.FalseBB)
483       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);  
484     assert(BBI.FalseBB && "Expected to find the fallthrough block!");
485   }
486
487   // Then scan all the instructions.
488   BBI.NonPredSize = 0;
489   BBI.ClobbersPred = false;
490   bool SeenCondBr = false;
491   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
492        I != E; ++I) {
493     if (!BBI.CannotBeCopied && !TII->CanBeDuplicated(I))
494       BBI.CannotBeCopied = true;
495
496     const TargetInstrDescriptor *TID = I->getInstrDescriptor();
497     bool isPredicated = TII->isPredicated(I);
498     bool isCondBr = BBI.IsBrAnalyzable &&
499       (TID->Flags & M_BRANCH_FLAG) != 0 && (TID->Flags & M_BARRIER_FLAG) == 0;
500
501     if (!isPredicated && !isCondBr)
502       BBI.NonPredSize++;
503
504     if (BBI.ClobbersPred && !isPredicated) {
505       // Predicate modification instruction should end the block (except for
506       // already predicated instructions and end of block branches).
507       if (isCondBr) {
508         SeenCondBr = true;
509
510         // Conditional branches is not predicable. But it may be eliminated.
511         continue;
512       }
513
514       // Predicate may have been modified, the subsequent (currently)
515       // unpredocated instructions cannot be correctly predicated.
516       BBI.IsUnpredicable = true;
517       return;
518     }
519
520     if (TID->Flags & M_CLOBBERS_PRED)
521       BBI.ClobbersPred = true;
522
523     if ((TID->Flags & M_PREDICABLE) == 0) {
524       BBI.IsUnpredicable = true;
525       return;
526     }
527   }
528 }
529
530 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
531 /// predicated by the specified predicate.
532 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
533                                       std::vector<MachineOperand> &Pred,
534                                       bool isTriangle, bool RevBranch) {
535   // If the block is dead or unpredicable, then it cannot be predicated.
536   if (BBI.IsDone || BBI.IsUnpredicable)
537     return false;
538
539   // Check predication threshold.
540   if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
541     return false;
542
543   // If it is already predicated, check if its predicate subsumes the new
544   // predicate.
545   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
546     return false;
547
548   if (BBI.BrCond.size()) {
549     if (!isTriangle)
550       return false;
551
552     // Test predicate subsumsion.
553     std::vector<MachineOperand> RevPred(Pred);
554     std::vector<MachineOperand> Cond(BBI.BrCond);
555     if (RevBranch) {
556       if (TII->ReverseBranchCondition(Cond))
557         return false;
558     }
559     if (TII->ReverseBranchCondition(RevPred) ||
560         !TII->SubsumesPredicate(Cond, RevPred))
561       return false;
562   }
563
564   return true;
565 }
566
567 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
568 /// the specified block. Record its successors and whether it looks like an
569 /// if-conversion candidate.
570 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
571                                              std::vector<IfcvtToken*> &Tokens) {
572   BBInfo &BBI = BBAnalysis[BB->getNumber()];
573
574   if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
575     return BBI;
576
577   BBI.BB = BB;
578   BBI.IsBeingAnalyzed = true;
579
580   ScanInstructions(BBI);
581
582   // Unanalyable or ends with fallthrough or unconditional branch.
583   if (!BBI.IsBrAnalyzable || BBI.BrCond.size() == 0) {
584     BBI.IsBeingAnalyzed = false;
585     BBI.IsAnalyzed = true;
586     return BBI;
587   }
588
589   // Do not ifcvt if either path is a back edge to the entry block.
590   if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
591     BBI.IsBeingAnalyzed = false;
592     BBI.IsAnalyzed = true;
593     return BBI;
594   }
595
596   BBInfo &TrueBBI  = AnalyzeBlock(BBI.TrueBB, Tokens);
597   BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
598
599   if (TrueBBI.IsDone && FalseBBI.IsDone) {
600     BBI.IsBeingAnalyzed = false;
601     BBI.IsAnalyzed = true;
602     return BBI;
603   }
604
605   std::vector<MachineOperand> RevCond(BBI.BrCond);
606   bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
607
608   unsigned Dups = 0;
609   bool TNeedSub = TrueBBI.Predicate.size() > 0;
610   bool FNeedSub = FalseBBI.Predicate.size() > 0;
611   bool Enqueued = false;
612   if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
613       !(TrueBBI.ClobbersPred && FalseBBI.ClobbersPred) &&
614       FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
615       FeasibilityAnalysis(FalseBBI, RevCond)) {
616     // Diamond:
617     //   EBB
618     //   / \_
619     //  |   |
620     // TBB FBB
621     //   \ /
622     //  TailBB
623     // Note TailBB can be empty.
624     Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups));
625     Enqueued = true;
626   }
627
628   if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
629       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
630     // Triangle:
631     //   EBB
632     //   | \_
633     //   |  |
634     //   | TBB
635     //   |  /
636     //   FBB
637     Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
638     Enqueued = true;
639   }
640   
641   if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
642       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
643     Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
644     Enqueued = true;
645   }
646
647   if (ValidSimple(TrueBBI, Dups) &&
648       FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
649     // Simple (split, no rejoin):
650     //   EBB
651     //   | \_
652     //   |  |
653     //   | TBB---> exit
654     //   |    
655     //   FBB
656     Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
657     Enqueued = true;
658   }
659
660   if (CanRevCond) {
661     // Try the other path...
662     if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
663         FeasibilityAnalysis(FalseBBI, RevCond, true)) {
664       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
665       Enqueued = true;
666     }
667
668     if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
669         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
670       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
671       Enqueued = true;
672     }
673
674     if (ValidSimple(FalseBBI, Dups) &&
675         FeasibilityAnalysis(FalseBBI, RevCond)) {
676       Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
677       Enqueued = true;
678     }
679   }
680
681   BBI.IsEnqueued = Enqueued;
682   BBI.IsBeingAnalyzed = false;
683   BBI.IsAnalyzed = true;
684   return BBI;
685 }
686
687 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
688 /// candidates. It returns true if any CFG restructuring is done to expose more
689 /// if-conversion opportunities.
690 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
691                                 std::vector<IfcvtToken*> &Tokens) {
692   bool Change = false;
693   std::set<MachineBasicBlock*> Visited;
694   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
695     for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
696            E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
697       MachineBasicBlock *BB = *I;
698       AnalyzeBlock(BB, Tokens);
699     }
700   }
701
702   // Sort to favor more complex ifcvt scheme.
703   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
704
705   return Change;
706 }
707
708 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
709 /// that all the intervening blocks are empty (given BB can fall through to its
710 /// next block).
711 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
712   MachineFunction::iterator I = BB;
713   MachineFunction::iterator TI = ToBB;
714   MachineFunction::iterator E = BB->getParent()->end();
715   while (++I != TI)
716     if (I == E || !I->empty())
717       return false;
718   return true;
719 }
720
721 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
722 /// to determine if it can be if-converted. If predecessor is already
723 /// enqueud, dequeue it!
724 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
725   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
726          E = BB->pred_end(); PI != E; ++PI) {
727     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
728     if (PBBI.IsDone || PBBI.BB == BB)
729       continue;
730     PBBI.IsAnalyzed = false;
731     PBBI.IsEnqueued = false;
732   }
733 }
734
735 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
736 ///
737 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
738                                const TargetInstrInfo *TII) {
739   std::vector<MachineOperand> NoCond;
740   TII->InsertBranch(*BB, ToBB, NULL, NoCond);
741 }
742
743 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
744 /// successors.
745 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
746   MachineBasicBlock *TBB = NULL, *FBB = NULL;
747   std::vector<MachineOperand> Cond;
748   bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
749   bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
750   if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
751     if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
752           (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
753       BBI.BB->removeSuccessor(BBI.TrueBB);
754   if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
755     if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
756           (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
757       BBI.BB->removeSuccessor(BBI.FalseBB);
758 }
759
760 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
761 ///
762 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
763   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
764   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
765   BBInfo *CvtBBI = &TrueBBI;
766   BBInfo *NextBBI = &FalseBBI;
767
768   std::vector<MachineOperand> Cond(BBI.BrCond);
769   if (Kind == ICSimpleFalse)
770     std::swap(CvtBBI, NextBBI);
771
772   if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
773     // Something has changed. It's no longer safe to predicate this block.
774     BBI.IsAnalyzed = false;
775     CvtBBI->IsAnalyzed = false;
776     return false;
777   }
778
779   if (Kind == ICSimpleFalse)
780     TII->ReverseBranchCondition(Cond);
781
782   if (CvtBBI->BB->pred_size() > 1) {
783     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
784     // Copy instructions in the true block, predicate them add them to
785     // the entry block.
786     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
787   } else {
788     PredicateBlock(*CvtBBI, Cond);
789
790     // Merge converted block into entry block.
791     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
792     MergeBlocks(BBI, *CvtBBI);
793   }
794
795   bool IterIfcvt = true;
796   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
797     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
798     BBI.HasFallThrough = false;
799     // Now ifcvt'd block will look like this:
800     // BB:
801     // ...
802     // t, f = cmp
803     // if t op
804     // b BBf
805     //
806     // We cannot further ifcvt this block because the unconditional branch
807     // will have to be predicated on the new condition, that will not be
808     // available if cmp executes.
809     IterIfcvt = false;
810   }
811
812   RemoveExtraEdges(BBI);
813
814   // Update block info. BB can be iteratively if-converted.
815   if (!IterIfcvt)
816     BBI.IsDone = true;
817   ReTryPreds(BBI.BB);
818   CvtBBI->IsDone = true;
819
820   // FIXME: Must maintain LiveIns.
821   return true;
822 }
823
824 /// IfConvertTriangle - If convert a triangle sub-CFG.
825 ///
826 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
827   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
828   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
829   BBInfo *CvtBBI = &TrueBBI;
830   BBInfo *NextBBI = &FalseBBI;
831
832   std::vector<MachineOperand> Cond(BBI.BrCond);
833   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
834     std::swap(CvtBBI, NextBBI);
835
836   if (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1) {
837     // Something has changed. It's no longer safe to predicate this block.
838     BBI.IsAnalyzed = false;
839     CvtBBI->IsAnalyzed = false;
840     return false;
841   }
842
843   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
844     TII->ReverseBranchCondition(Cond);
845
846   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
847     ReverseBranchCondition(*CvtBBI);
848     // BB has been changed, modify its predecessors (except for this
849     // one) so they don't get ifcvt'ed based on bad intel.
850     for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
851            E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
852       MachineBasicBlock *PBB = *PI;
853       if (PBB == BBI.BB)
854         continue;
855       BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
856       if (PBBI.IsEnqueued) {
857         PBBI.IsAnalyzed = false;
858         PBBI.IsEnqueued = false;
859       }
860     }
861   }
862
863   bool HasEarlyExit = CvtBBI->FalseBB != NULL;
864   bool DupBB = CvtBBI->BB->pred_size() > 1;
865   if (DupBB) {
866     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
867     // Copy instructions in the true block, predicate them add them to
868     // the entry block.
869     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
870   } else {
871     // Predicate the 'true' block after removing its branch.
872     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
873     PredicateBlock(*CvtBBI, Cond);
874   }
875
876   // If 'true' block has a 'false' successor, add an exit branch to it.
877   if (HasEarlyExit) {
878     std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
879     if (TII->ReverseBranchCondition(RevCond))
880       assert(false && "Unable to reverse branch condition!");
881     if (DupBB) {
882       TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
883       BBI.BB->addSuccessor(CvtBBI->FalseBB);
884     } else {
885       TII->InsertBranch(*CvtBBI->BB, CvtBBI->FalseBB, NULL, RevCond);
886     }
887   }
888
889   if (!DupBB) {
890     // Now merge the entry of the triangle with the true block.
891     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
892     MergeBlocks(BBI, *CvtBBI);
893   }
894
895   // Merge in the 'false' block if the 'false' block has no other
896   // predecessors. Otherwise, add a unconditional branch from to 'false'.
897   bool FalseBBDead = false;
898   bool IterIfcvt = true;
899   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
900   if (!isFallThrough) {
901     // Only merge them if the true block does not fallthrough to the false
902     // block. By not merging them, we make it possible to iteratively
903     // ifcvt the blocks.
904     if (!HasEarlyExit && NextBBI->BB->pred_size() == 1) {
905       MergeBlocks(BBI, *NextBBI);
906       FalseBBDead = true;
907     } else {
908       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
909       BBI.HasFallThrough = false;
910     }
911     // Mixed predicated and unpredicated code. This cannot be iteratively
912     // predicated.
913     IterIfcvt = false;
914   }
915
916   RemoveExtraEdges(BBI);
917
918   // Update block info. BB can be iteratively if-converted.
919   if (!IterIfcvt) 
920     BBI.IsDone = true;
921   ReTryPreds(BBI.BB);
922   CvtBBI->IsDone = true;
923   if (FalseBBDead)
924     NextBBI->IsDone = true;
925
926   // FIXME: Must maintain LiveIns.
927   return true;
928 }
929
930 /// IfConvertDiamond - If convert a diamond sub-CFG.
931 ///
932 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind) {
933   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
934   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
935   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
936
937   SmallVector<MachineInstr*, 2> Dups;
938   if (!TailBB) {
939     // No common merge block. Check if the terminators (e.g. return) are
940     // the same or predicable.
941     MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
942     MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
943     while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
944       if (TT->isIdenticalTo(FT))
945         Dups.push_back(TT);  // Will erase these later.
946       else if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0 ||
947                (FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
948         return false; // Can't if-convert. Abort!
949       ++TT;
950       ++FT;
951     }
952
953     // One of the two pathes have more terminators, make sure they are
954     // all predicable.
955     while (TT != BBI.TrueBB->end()) {
956       if ((TT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
957         return false; // Can't if-convert. Abort!
958       ++TT;
959     }
960     while (FT != BBI.FalseBB->end()) {
961       if ((FT->getInstrDescriptor()->Flags & M_PREDICABLE) == 0)
962         return false; // Can't if-convert. Abort!
963       ++FT;
964     }
965   }
966
967   // Remove the duplicated instructions from the 'true' block.
968   for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
969     Dups[i]->eraseFromParent();
970     --TrueBBI.NonPredSize;
971   }
972     
973   // Merge the 'true' and 'false' blocks by copying the instructions
974   // from the 'false' block to the 'true' block. That is, unless the true
975   // block would clobber the predicate, in that case, do the opposite.
976   BBInfo *BBI1 = &TrueBBI;
977   BBInfo *BBI2 = &FalseBBI;
978   std::vector<MachineOperand> RevCond(BBI.BrCond);
979   TII->ReverseBranchCondition(RevCond);
980   std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
981   std::vector<MachineOperand> *Cond2 = &RevCond;
982   // Check the 'true' and 'false' blocks if either isn't ended with a branch.
983   // Either the block fallthrough to another block or it ends with a
984   // return. If it's the former, add a branch to its successor.
985   bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size() > 0;
986   bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size() > 0; 
987
988   // Figure out the more profitable ordering.
989   bool DoSwap = false;
990   if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
991     DoSwap = true;
992   else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
993     if (!NeedBr1 && NeedBr2)
994       DoSwap = true;
995     else if (NeedBr1 == NeedBr2) {
996       if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
997         DoSwap = true;
998     }
999   }
1000   if (DoSwap) {
1001     std::swap(BBI1, BBI2);
1002     std::swap(Cond1, Cond2);
1003     std::swap(NeedBr1, NeedBr2);
1004   }
1005
1006   // Predicate the 'true' block after removing its branch.
1007   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1008   PredicateBlock(*BBI1, *Cond1);
1009
1010   // Add an early exit branch if needed.
1011   if (NeedBr1)
1012     TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
1013
1014   // Predicate the 'false' block.
1015   PredicateBlock(*BBI2, *Cond2, true);
1016
1017   // Add an unconditional branch from 'false' to to 'false' successor if it
1018   // will not be the fallthrough block.
1019   if (NeedBr2 && !NeedBr1) {
1020     // If BBI2 isn't going to be merged in, then the existing fallthrough
1021     // or branch is fine.
1022     if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
1023       InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
1024       BBI2->HasFallThrough = false;
1025     }
1026   }
1027
1028   // Keep them as two separate blocks if there is an early exit.
1029   if (!NeedBr1)
1030     MergeBlocks(*BBI1, *BBI2);
1031
1032   // Remove the conditional branch from entry to the blocks.
1033   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1034
1035   // Merge the combined block into the entry of the diamond.
1036   MergeBlocks(BBI, *BBI1);
1037
1038   // 'True' and 'false' aren't combined, see if we need to add a unconditional
1039   // branch to the 'false' block.
1040   if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
1041     InsertUncondBranch(BBI.BB, BBI2->BB, TII);
1042     BBI1->HasFallThrough = false;
1043   }
1044
1045   // If the if-converted block fallthrough or unconditionally branch into the
1046   // tail block, and the tail block does not have other predecessors, then
1047   // fold the tail block in as well.
1048   BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
1049   if (TailBB &&
1050       TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
1051     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1052     BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1053     MergeBlocks(*CvtBBI, TailBBI);
1054     TailBBI.IsDone = true;
1055   }
1056
1057   RemoveExtraEdges(BBI);
1058
1059   // Update block info.
1060   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1061
1062   // FIXME: Must maintain LiveIns.
1063   return true;
1064 }
1065
1066 /// PredicateBlock - Predicate every instruction in the block with the specified
1067 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
1068 void IfConverter::PredicateBlock(BBInfo &BBI,
1069                                  std::vector<MachineOperand> &Cond,
1070                                  bool IgnoreTerm) {
1071   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
1072        I != E; ++I) {
1073     if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
1074       continue;
1075     if (TII->isPredicated(I))
1076       continue;
1077     if (!TII->PredicateInstruction(I, Cond)) {
1078       cerr << "Unable to predicate " << *I << "!\n";
1079       abort();
1080     }
1081   }
1082
1083   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1084
1085   BBI.IsAnalyzed = false;
1086   BBI.NonPredSize = 0;
1087
1088   NumIfConvBBs++;
1089 }
1090
1091 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1092 /// the destination block. Skip end of block branches if IgnoreBr is true.
1093 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1094                                         std::vector<MachineOperand> &Cond,
1095                                         bool IgnoreBr) {
1096   for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1097          E = FromBBI.BB->end(); I != E; ++I) {
1098     const TargetInstrDescriptor *TID = I->getInstrDescriptor();
1099     bool isPredicated = TII->isPredicated(I);
1100     // Do not copy the end of the block branches.
1101     if (IgnoreBr && !isPredicated && (TID->Flags & M_BRANCH_FLAG) != 0)
1102       break;
1103
1104     MachineInstr *MI = I->clone();
1105     ToBBI.BB->insert(ToBBI.BB->end(), MI);
1106     ToBBI.NonPredSize++;
1107
1108     if (!isPredicated)
1109       if (!TII->PredicateInstruction(MI, Cond)) {
1110         cerr << "Unable to predicate " << *MI << "!\n";
1111         abort();
1112       }
1113   }
1114
1115   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1116             std::back_inserter(ToBBI.Predicate));
1117   std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1118
1119   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1120   ToBBI.IsAnalyzed = false;
1121
1122   NumDupBBs++;
1123 }
1124
1125 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1126 ///
1127 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1128   ToBBI.BB->splice(ToBBI.BB->end(),
1129                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1130
1131   // Redirect all branches to FromBB to ToBB.
1132   std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1133                                          FromBBI.BB->pred_end());
1134   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1135     MachineBasicBlock *Pred = Preds[i];
1136     if (Pred == ToBBI.BB)
1137       continue;
1138     Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1139   }
1140  
1141   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1142                                          FromBBI.BB->succ_end());
1143   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1144   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1145
1146   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1147     MachineBasicBlock *Succ = Succs[i];
1148     // Fallthrough edge can't be transferred.
1149     if (Succ == FallThrough)
1150       continue;
1151     FromBBI.BB->removeSuccessor(Succ);
1152     if (!ToBBI.BB->isSuccessor(Succ))
1153       ToBBI.BB->addSuccessor(Succ);
1154   }
1155
1156   // Now FromBBI always fall through to the next block!
1157   if (NBB)
1158     FromBBI.BB->addSuccessor(NBB);
1159
1160   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1161             std::back_inserter(ToBBI.Predicate));
1162   FromBBI.Predicate.clear();
1163
1164   ToBBI.NonPredSize += FromBBI.NonPredSize;
1165   FromBBI.NonPredSize = 0;
1166
1167   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1168   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1169   ToBBI.IsAnalyzed = false;
1170   FromBBI.IsAnalyzed = false;
1171 }