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