8702bb30802bf74009423d5d650576f3c7d2cf84
[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 #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     /// ClobbersPredicate- True if BB would modify the predicate (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.BB->pred_size() > 1) {
403     if (TrueBBI.CannotBeCopied ||
404         TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
405       return false;
406     Dups = TrueBBI.NonPredSize;
407   }
408
409   return !blockAlwaysFallThrough(TrueBBI) && TrueBBI.BrCond.size() == 0;
410 }
411
412 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
413 /// with their common predecessor) forms a valid triangle shape for ifcvt.
414 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
415 /// branches to the false branch rather than the other way around. It also
416 /// returns the number of instructions that the ifcvt would need to duplicate
417 /// if performed in 'Dups'.
418 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
419                                 bool FalseBranch, unsigned &Dups) const {
420   Dups = 0;
421   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
422     return false;
423
424   if (TrueBBI.BB->pred_size() > 1) {
425     if (TrueBBI.CannotBeCopied)
426       return false;
427
428     unsigned Size = TrueBBI.NonPredSize;
429     if (TrueBBI.IsBrAnalyzable) {
430       if (TrueBBI.TrueBB && TrueBBI.BrCond.size() == 0)
431         // End with an unconditional branch. It will be removed.
432         --Size;
433       else {
434         MachineBasicBlock *FExit = FalseBranch
435           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
436         if (FExit)
437           // Require a conditional branch
438           ++Size;
439       }
440     }
441     if (Size > TLI->getIfCvtDupBlockSizeLimit())
442       return false;
443     Dups = Size;
444   }
445
446   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
447   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
448     MachineFunction::iterator I = TrueBBI.BB;
449     if (++I == TrueBBI.BB->getParent()->end())
450       return false;
451     TExit = I;
452   }
453   return TExit && TExit == FalseBBI.BB;
454 }
455
456 static
457 MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
458                                                const TargetInstrInfo *TII) {
459   MachineBasicBlock::iterator I = BB->end();
460   while (I != BB->begin()) {
461     --I;
462     const TargetInstrDescriptor *TID = I->getInstrDescriptor();
463     if ((TID->Flags & M_BRANCH_FLAG) == 0)
464       break;
465   }
466   return I;
467 }
468
469 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
470 /// with their common predecessor) forms a valid diamond shape for ifcvt.
471 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
472                                unsigned &Dups1, unsigned &Dups2) const {
473   Dups1 = Dups2 = 0;
474   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
475       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
476     return false;
477
478   MachineBasicBlock *TT = TrueBBI.TrueBB;
479   MachineBasicBlock *FT = FalseBBI.TrueBB;
480
481   if (!TT && blockAlwaysFallThrough(TrueBBI))
482     TT = getNextBlock(TrueBBI.BB);
483   if (!FT && blockAlwaysFallThrough(FalseBBI))
484     FT = getNextBlock(FalseBBI.BB);
485   if (TT != FT)
486     return false;
487   if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
488     return false;
489   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
490     return false;
491
492   // FIXME: Allow true block to have an early exit?
493   if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
494       (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
495     return false;
496
497   MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
498   MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
499   while (TI != TrueBBI.BB->end() && FI != FalseBBI.BB->end()) {
500     if (!TI->isIdenticalTo(FI))
501       break;
502     ++Dups1;
503     ++TI;
504     ++FI;
505   }
506
507   TI = firstNonBranchInst(TrueBBI.BB, TII);
508   FI = firstNonBranchInst(FalseBBI.BB, TII);
509   while (TI != TrueBBI.BB->begin() && FI != FalseBBI.BB->begin()) {
510     if (!TI->isIdenticalTo(FI))
511       break;
512     ++Dups2;
513     --TI;
514     --FI;
515   }
516
517   return true;
518 }
519
520 /// ScanInstructions - Scan all the instructions in the block to determine if
521 /// the block is predicable. In most cases, that means all the instructions
522 /// in the block has M_PREDICABLE flag. Also checks if the block contains any
523 /// instruction which can clobber a predicate (e.g. condition code register).
524 /// If so, the block is not predicable unless it's the last instruction.
525 void IfConverter::ScanInstructions(BBInfo &BBI) {
526   if (BBI.IsDone)
527     return;
528
529   // First analyze the end of BB branches.
530   BBI.TrueBB = BBI.FalseBB = NULL;
531   BBI.BrCond.clear();
532   BBI.IsBrAnalyzable =
533     !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
534   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
535
536   if (BBI.BrCond.size()) {
537     // No false branch. This BB must end with a conditional branch and a
538     // fallthrough.
539     if (!BBI.FalseBB)
540       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);  
541     assert(BBI.FalseBB && "Expected to find the fallthrough block!");
542   }
543
544   // Then scan all the instructions.
545   BBI.NonPredSize = 0;
546   BBI.ClobbersPred = false;
547   bool SeenCondBr = false;
548   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
549        I != E; ++I) {
550     if (!BBI.CannotBeCopied && !TII->CanBeDuplicated(I))
551       BBI.CannotBeCopied = true;
552
553     const TargetInstrDescriptor *TID = I->getInstrDescriptor();
554     bool isPredicated = TII->isPredicated(I);
555     bool isCondBr = BBI.IsBrAnalyzable &&
556       (TID->Flags & M_BRANCH_FLAG) != 0 && (TID->Flags & M_BARRIER_FLAG) == 0;
557
558     if (!isPredicated && !isCondBr)
559       BBI.NonPredSize++;
560
561     if (BBI.ClobbersPred && !isPredicated) {
562       // Predicate modification instruction should end the block (except for
563       // already predicated instructions and end of block branches).
564       if (isCondBr) {
565         SeenCondBr = true;
566
567         // Conditional branches is not predicable. But it may be eliminated.
568         continue;
569       }
570
571       // Predicate may have been modified, the subsequent (currently)
572       // unpredocated instructions cannot be correctly predicated.
573       BBI.IsUnpredicable = true;
574       return;
575     }
576
577     if (TID->Flags & M_CLOBBERS_PRED)
578       BBI.ClobbersPred = true;
579
580     if ((TID->Flags & M_PREDICABLE) == 0) {
581       BBI.IsUnpredicable = true;
582       return;
583     }
584   }
585 }
586
587 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
588 /// predicated by the specified predicate.
589 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
590                                       std::vector<MachineOperand> &Pred,
591                                       bool isTriangle, bool RevBranch) {
592   // If the block is dead or unpredicable, then it cannot be predicated.
593   if (BBI.IsDone || BBI.IsUnpredicable)
594     return false;
595
596   // If it is already predicated, check if its predicate subsumes the new
597   // predicate.
598   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
599     return false;
600
601   if (BBI.BrCond.size()) {
602     if (!isTriangle)
603       return false;
604
605     // Test predicate subsumsion.
606     std::vector<MachineOperand> RevPred(Pred);
607     std::vector<MachineOperand> Cond(BBI.BrCond);
608     if (RevBranch) {
609       if (TII->ReverseBranchCondition(Cond))
610         return false;
611     }
612     if (TII->ReverseBranchCondition(RevPred) ||
613         !TII->SubsumesPredicate(Cond, RevPred))
614       return false;
615   }
616
617   return true;
618 }
619
620 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
621 /// the specified block. Record its successors and whether it looks like an
622 /// if-conversion candidate.
623 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
624                                              std::vector<IfcvtToken*> &Tokens) {
625   BBInfo &BBI = BBAnalysis[BB->getNumber()];
626
627   if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
628     return BBI;
629
630   BBI.BB = BB;
631   BBI.IsBeingAnalyzed = true;
632
633   ScanInstructions(BBI);
634
635   // Unanalyable or ends with fallthrough or unconditional branch.
636   if (!BBI.IsBrAnalyzable || BBI.BrCond.size() == 0) {
637     BBI.IsBeingAnalyzed = false;
638     BBI.IsAnalyzed = true;
639     return BBI;
640   }
641
642   // Do not ifcvt if either path is a back edge to the entry block.
643   if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
644     BBI.IsBeingAnalyzed = false;
645     BBI.IsAnalyzed = true;
646     return BBI;
647   }
648
649   BBInfo &TrueBBI  = AnalyzeBlock(BBI.TrueBB, Tokens);
650   BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
651
652   if (TrueBBI.IsDone && FalseBBI.IsDone) {
653     BBI.IsBeingAnalyzed = false;
654     BBI.IsAnalyzed = true;
655     return BBI;
656   }
657
658   std::vector<MachineOperand> RevCond(BBI.BrCond);
659   bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
660
661   unsigned Dups = 0;
662   unsigned Dups2 = 0;
663   bool TNeedSub = TrueBBI.Predicate.size() > 0;
664   bool FNeedSub = FalseBBI.Predicate.size() > 0;
665   bool Enqueued = false;
666   if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
667       MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
668       MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
669       FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
670       FeasibilityAnalysis(FalseBBI, RevCond)) {
671     // Diamond:
672     //   EBB
673     //   / \_
674     //  |   |
675     // TBB FBB
676     //   \ /
677     //  TailBB
678     // Note TailBB can be empty.
679     Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
680                                     Dups2));
681     Enqueued = true;
682   }
683
684   if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
685       MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
686       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
687     // Triangle:
688     //   EBB
689     //   | \_
690     //   |  |
691     //   | TBB
692     //   |  /
693     //   FBB
694     Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
695     Enqueued = true;
696   }
697   
698   if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
699       MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
700       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
701     Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
702     Enqueued = true;
703   }
704
705   if (ValidSimple(TrueBBI, Dups) &&
706       MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
707       FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
708     // Simple (split, no rejoin):
709     //   EBB
710     //   | \_
711     //   |  |
712     //   | TBB---> exit
713     //   |    
714     //   FBB
715     Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
716     Enqueued = true;
717   }
718
719   if (CanRevCond) {
720     // Try the other path...
721     if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
722         MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
723         FeasibilityAnalysis(FalseBBI, RevCond, true)) {
724       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
725       Enqueued = true;
726     }
727
728     if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
729         MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
730         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
731       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
732       Enqueued = true;
733     }
734
735     if (ValidSimple(FalseBBI, Dups) &&
736         MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
737         FeasibilityAnalysis(FalseBBI, RevCond)) {
738       Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
739       Enqueued = true;
740     }
741   }
742
743   BBI.IsEnqueued = Enqueued;
744   BBI.IsBeingAnalyzed = false;
745   BBI.IsAnalyzed = true;
746   return BBI;
747 }
748
749 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
750 /// candidates. It returns true if any CFG restructuring is done to expose more
751 /// if-conversion opportunities.
752 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
753                                 std::vector<IfcvtToken*> &Tokens) {
754   bool Change = false;
755   std::set<MachineBasicBlock*> Visited;
756   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
757     for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
758            E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
759       MachineBasicBlock *BB = *I;
760       AnalyzeBlock(BB, Tokens);
761     }
762   }
763
764   // Sort to favor more complex ifcvt scheme.
765   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
766
767   return Change;
768 }
769
770 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
771 /// that all the intervening blocks are empty (given BB can fall through to its
772 /// next block).
773 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
774   MachineFunction::iterator I = BB;
775   MachineFunction::iterator TI = ToBB;
776   MachineFunction::iterator E = BB->getParent()->end();
777   while (++I != TI)
778     if (I == E || !I->empty())
779       return false;
780   return true;
781 }
782
783 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
784 /// to determine if it can be if-converted. If predecessor is already enqueued,
785 /// dequeue it!
786 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
787   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
788          E = BB->pred_end(); PI != E; ++PI) {
789     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
790     if (PBBI.IsDone || PBBI.BB == BB)
791       continue;
792     PBBI.IsAnalyzed = false;
793     PBBI.IsEnqueued = false;
794   }
795 }
796
797 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
798 ///
799 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
800                                const TargetInstrInfo *TII) {
801   std::vector<MachineOperand> NoCond;
802   TII->InsertBranch(*BB, ToBB, NULL, NoCond);
803 }
804
805 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
806 /// successors.
807 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
808   MachineBasicBlock *TBB = NULL, *FBB = NULL;
809   std::vector<MachineOperand> Cond;
810   if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
811     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
812 }
813
814 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
815 ///
816 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
817   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
818   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
819   BBInfo *CvtBBI = &TrueBBI;
820   BBInfo *NextBBI = &FalseBBI;
821
822   std::vector<MachineOperand> Cond(BBI.BrCond);
823   if (Kind == ICSimpleFalse)
824     std::swap(CvtBBI, NextBBI);
825
826   if (CvtBBI->IsDone ||
827       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
828     // Something has changed. It's no longer safe to predicate this block.
829     BBI.IsAnalyzed = false;
830     CvtBBI->IsAnalyzed = false;
831     return false;
832   }
833
834   if (Kind == ICSimpleFalse)
835     TII->ReverseBranchCondition(Cond);
836
837   if (CvtBBI->BB->pred_size() > 1) {
838     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
839     // Copy instructions in the true block, predicate them add them to
840     // the entry block.
841     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
842   } else {
843     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
844
845     // Merge converted block into entry block.
846     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
847     MergeBlocks(BBI, *CvtBBI);
848   }
849
850   bool IterIfcvt = true;
851   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
852     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
853     BBI.HasFallThrough = false;
854     // Now ifcvt'd block will look like this:
855     // BB:
856     // ...
857     // t, f = cmp
858     // if t op
859     // b BBf
860     //
861     // We cannot further ifcvt this block because the unconditional branch
862     // will have to be predicated on the new condition, that will not be
863     // available if cmp executes.
864     IterIfcvt = false;
865   }
866
867   RemoveExtraEdges(BBI);
868
869   // Update block info. BB can be iteratively if-converted.
870   if (!IterIfcvt)
871     BBI.IsDone = true;
872   InvalidatePreds(BBI.BB);
873   CvtBBI->IsDone = true;
874
875   // FIXME: Must maintain LiveIns.
876   return true;
877 }
878
879 /// IfConvertTriangle - If convert a triangle sub-CFG.
880 ///
881 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
882   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
883   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
884   BBInfo *CvtBBI = &TrueBBI;
885   BBInfo *NextBBI = &FalseBBI;
886
887   std::vector<MachineOperand> Cond(BBI.BrCond);
888   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
889     std::swap(CvtBBI, NextBBI);
890
891   if (CvtBBI->IsDone ||
892       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
893     // Something has changed. It's no longer safe to predicate this block.
894     BBI.IsAnalyzed = false;
895     CvtBBI->IsAnalyzed = false;
896     return false;
897   }
898
899   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
900     TII->ReverseBranchCondition(Cond);
901
902   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
903     ReverseBranchCondition(*CvtBBI);
904     // BB has been changed, modify its predecessors (except for this
905     // one) so they don't get ifcvt'ed based on bad intel.
906     for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
907            E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
908       MachineBasicBlock *PBB = *PI;
909       if (PBB == BBI.BB)
910         continue;
911       BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
912       if (PBBI.IsEnqueued) {
913         PBBI.IsAnalyzed = false;
914         PBBI.IsEnqueued = false;
915       }
916     }
917   }
918
919   bool HasEarlyExit = CvtBBI->FalseBB != NULL;
920   bool DupBB = CvtBBI->BB->pred_size() > 1;
921   if (DupBB) {
922     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
923     // Copy instructions in the true block, predicate them add them to
924     // the entry block.
925     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
926   } else {
927     // Predicate the 'true' block after removing its branch.
928     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
929     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
930   }
931
932   if (!DupBB) {
933     // Now merge the entry of the triangle with the true block.
934     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
935     MergeBlocks(BBI, *CvtBBI);
936   }
937
938   // If 'true' block has a 'false' successor, add an exit branch to it.
939   if (HasEarlyExit) {
940     std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
941     if (TII->ReverseBranchCondition(RevCond))
942       assert(false && "Unable to reverse branch condition!");
943     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
944     BBI.BB->addSuccessor(CvtBBI->FalseBB);
945   }
946
947   // Merge in the 'false' block if the 'false' block has no other
948   // predecessors. Otherwise, add a unconditional branch from to 'false'.
949   bool FalseBBDead = false;
950   bool IterIfcvt = true;
951   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
952   if (!isFallThrough) {
953     // Only merge them if the true block does not fallthrough to the false
954     // block. By not merging them, we make it possible to iteratively
955     // ifcvt the blocks.
956     if (!HasEarlyExit &&
957         NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
958       MergeBlocks(BBI, *NextBBI);
959       FalseBBDead = true;
960     } else {
961       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
962       BBI.HasFallThrough = false;
963     }
964     // Mixed predicated and unpredicated code. This cannot be iteratively
965     // predicated.
966     IterIfcvt = false;
967   }
968
969   RemoveExtraEdges(BBI);
970
971   // Update block info. BB can be iteratively if-converted.
972   if (!IterIfcvt) 
973     BBI.IsDone = true;
974   InvalidatePreds(BBI.BB);
975   CvtBBI->IsDone = true;
976   if (FalseBBDead)
977     NextBBI->IsDone = true;
978
979   // FIXME: Must maintain LiveIns.
980   return true;
981 }
982
983 /// IfConvertDiamond - If convert a diamond sub-CFG.
984 ///
985 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
986                                    unsigned NumDups1, unsigned NumDups2) {
987   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
988   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
989   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
990   // True block must fall through or ended with unanalyzable terminator.
991   if (!TailBB) {
992     if (blockAlwaysFallThrough(TrueBBI))
993       TailBB = FalseBBI.TrueBB;
994     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
995   }
996
997   if (TrueBBI.IsDone || FalseBBI.IsDone ||
998       TrueBBI.BB->pred_size() > 1 ||
999       FalseBBI.BB->pred_size() > 1) {
1000     // Something has changed. It's no longer safe to predicate these blocks.
1001     BBI.IsAnalyzed = false;
1002     TrueBBI.IsAnalyzed = false;
1003     FalseBBI.IsAnalyzed = false;
1004     return false;
1005   }
1006
1007   // Merge the 'true' and 'false' blocks by copying the instructions
1008   // from the 'false' block to the 'true' block. That is, unless the true
1009   // block would clobber the predicate, in that case, do the opposite.
1010   BBInfo *BBI1 = &TrueBBI;
1011   BBInfo *BBI2 = &FalseBBI;
1012   std::vector<MachineOperand> RevCond(BBI.BrCond);
1013   TII->ReverseBranchCondition(RevCond);
1014   std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
1015   std::vector<MachineOperand> *Cond2 = &RevCond;
1016
1017   // Figure out the more profitable ordering.
1018   bool DoSwap = false;
1019   if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1020     DoSwap = true;
1021   else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1022     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1023       DoSwap = true;
1024   }
1025   if (DoSwap) {
1026     std::swap(BBI1, BBI2);
1027     std::swap(Cond1, Cond2);
1028   }
1029
1030   // Remove the conditional branch from entry to the blocks.
1031   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1032
1033   // Remove the duplicated instructions at the beginnings of both paths.
1034   MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1035   MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1036   BBI1->NonPredSize -= NumDups1;
1037   BBI2->NonPredSize -= NumDups1;
1038   while (NumDups1 != 0) {
1039     ++DI1;
1040     ++DI2;
1041     --NumDups1;
1042   }
1043   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1044   BBI2->BB->erase(BBI2->BB->begin(), DI2);
1045
1046   // Predicate the 'true' block after removing its branch.
1047   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1048   DI1 = BBI1->BB->end();
1049   for (unsigned i = 0; i != NumDups2; ++i)
1050     --DI1;
1051   BBI1->BB->erase(DI1, BBI1->BB->end());
1052   PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1);
1053
1054   // Predicate the 'false' block.
1055   BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1056   DI2 = BBI2->BB->end();
1057   while (NumDups2 != 0) {
1058     --DI2;
1059     --NumDups2;
1060   }
1061   PredicateBlock(*BBI2, DI2, *Cond2);
1062
1063   // Merge the true block into the entry of the diamond.
1064   MergeBlocks(BBI, *BBI1);
1065   MergeBlocks(BBI, *BBI2);
1066
1067   // If the if-converted block fallthrough or unconditionally branch into the
1068   // tail block, and the tail block does not have other predecessors, then
1069   // fold the tail block in as well. Otherwise, unless it falls through to the
1070   // tail, add a unconditional branch to it.
1071   if (TailBB) {
1072     BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1073     if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1074       BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1075       MergeBlocks(BBI, TailBBI);
1076       TailBBI.IsDone = true;
1077     } else {
1078       InsertUncondBranch(BBI.BB, TailBB, TII);
1079       BBI.HasFallThrough = false;
1080     }
1081   }
1082
1083   RemoveExtraEdges(BBI);
1084
1085   // Update block info.
1086   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1087   InvalidatePreds(BBI.BB);
1088
1089   // FIXME: Must maintain LiveIns.
1090   return true;
1091 }
1092
1093 /// PredicateBlock - Predicate instructions from the start of the block to the
1094 /// specified end with the specified condition.
1095 void IfConverter::PredicateBlock(BBInfo &BBI,
1096                                  MachineBasicBlock::iterator E,
1097                                  std::vector<MachineOperand> &Cond) {
1098   for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1099     if (TII->isPredicated(I))
1100       continue;
1101     if (!TII->PredicateInstruction(I, Cond)) {
1102       cerr << "Unable to predicate " << *I << "!\n";
1103       abort();
1104     }
1105   }
1106
1107   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1108
1109   BBI.IsAnalyzed = false;
1110   BBI.NonPredSize = 0;
1111
1112   NumIfConvBBs++;
1113 }
1114
1115 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1116 /// the destination block. Skip end of block branches if IgnoreBr is true.
1117 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1118                                         std::vector<MachineOperand> &Cond,
1119                                         bool IgnoreBr) {
1120   for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1121          E = FromBBI.BB->end(); I != E; ++I) {
1122     const TargetInstrDescriptor *TID = I->getInstrDescriptor();
1123     bool isPredicated = TII->isPredicated(I);
1124     // Do not copy the end of the block branches.
1125     if (IgnoreBr && !isPredicated && (TID->Flags & M_BRANCH_FLAG) != 0)
1126       break;
1127
1128     MachineInstr *MI = I->clone();
1129     ToBBI.BB->insert(ToBBI.BB->end(), MI);
1130     ToBBI.NonPredSize++;
1131
1132     if (!isPredicated)
1133       if (!TII->PredicateInstruction(MI, Cond)) {
1134         cerr << "Unable to predicate " << *MI << "!\n";
1135         abort();
1136       }
1137   }
1138
1139   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1140                                          FromBBI.BB->succ_end());
1141   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1142   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1143
1144   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1145     MachineBasicBlock *Succ = Succs[i];
1146     // Fallthrough edge can't be transferred.
1147     if (Succ == FallThrough)
1148       continue;
1149     if (!ToBBI.BB->isSuccessor(Succ))
1150       ToBBI.BB->addSuccessor(Succ);
1151   }
1152
1153   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1154             std::back_inserter(ToBBI.Predicate));
1155   std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1156
1157   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1158   ToBBI.IsAnalyzed = false;
1159
1160   NumDupBBs++;
1161 }
1162
1163 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1164 ///
1165 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1166   ToBBI.BB->splice(ToBBI.BB->end(),
1167                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1168
1169   // Redirect all branches to FromBB to ToBB.
1170   std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1171                                          FromBBI.BB->pred_end());
1172   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1173     MachineBasicBlock *Pred = Preds[i];
1174     if (Pred == ToBBI.BB)
1175       continue;
1176     Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1177   }
1178  
1179   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1180                                          FromBBI.BB->succ_end());
1181   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1182   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1183
1184   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1185     MachineBasicBlock *Succ = Succs[i];
1186     // Fallthrough edge can't be transferred.
1187     if (Succ == FallThrough)
1188       continue;
1189     FromBBI.BB->removeSuccessor(Succ);
1190     if (!ToBBI.BB->isSuccessor(Succ))
1191       ToBBI.BB->addSuccessor(Succ);
1192   }
1193
1194   // Now FromBBI always fall through to the next block!
1195   if (NBB && !FromBBI.BB->isSuccessor(NBB))
1196     FromBBI.BB->addSuccessor(NBB);
1197
1198   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1199             std::back_inserter(ToBBI.Predicate));
1200   FromBBI.Predicate.clear();
1201
1202   ToBBI.NonPredSize += FromBBI.NonPredSize;
1203   FromBBI.NonPredSize = 0;
1204
1205   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1206   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1207   ToBBI.IsAnalyzed = false;
1208   FromBBI.IsAnalyzed = false;
1209 }