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