75ded08b740731b00ada1d2960cc1b10b9a7474f
[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/Statistic.h"
23 using namespace llvm;
24
25 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
26
27 namespace {
28   class IfConverter : public MachineFunctionPass {
29     enum BBICKind {
30       ICInvalid,       // BB data invalid.
31       ICNotClassfied,  // BB data valid, but not classified.
32       ICTriangle,      // BB is part of a triangle sub-CFG.
33       ICDiamond,       // BB is part of a diamond sub-CFG.
34       ICTriangleEntry, // BB is entry of a triangle sub-CFG.
35       ICDiamondEntry   // BB is entry of a diamond sub-CFG.
36     };
37
38     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
39     /// if-conversion feasibility analysis. This includes results from
40     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
41     /// classification, and common tail block of its successors (if it's a
42     /// diamond shape), its size, whether it's predicable, and whether any
43     /// instruction can clobber the 'would-be' predicate.
44     struct BBInfo {
45       BBICKind Kind;
46       unsigned Size;
47       bool isPredicable;
48       bool ClobbersPred;
49       MachineBasicBlock *BB;
50       MachineBasicBlock *TrueBB;
51       MachineBasicBlock *FalseBB;
52       MachineBasicBlock *TailBB;
53       std::vector<MachineOperand> Cond;
54       BBInfo() : Kind(ICInvalid), Size(0), isPredicable(false),
55                  ClobbersPred(false), BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
56     };
57
58     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
59     /// basic block number.
60     std::vector<BBInfo> BBAnalysis;
61
62     const TargetLowering *TLI;
63     const TargetInstrInfo *TII;
64     bool MadeChange;
65   public:
66     static char ID;
67     IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
68
69     virtual bool runOnMachineFunction(MachineFunction &MF);
70     virtual const char *getPassName() const { return "If converter"; }
71
72   private:
73     void StructuralAnalysis(MachineBasicBlock *BB);
74     void FeasibilityAnalysis(BBInfo &BBI);
75     void InitialFunctionAnalysis(MachineFunction &MF,
76                                  std::vector<int> &Candidates);
77     bool IfConvertTriangle(BBInfo &BBI);
78     bool IfConvertDiamond(BBInfo &BBI);
79     void PredicateBlock(MachineBasicBlock *BB,
80                         std::vector<MachineOperand> &Cond,
81                         bool IgnoreTerm = false);
82     void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
83   };
84   char IfConverter::ID = 0;
85 }
86
87 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
88
89 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
90   TLI = MF.getTarget().getTargetLowering();
91   TII = MF.getTarget().getInstrInfo();
92   if (!TII) return false;
93
94   MF.RenumberBlocks();
95   unsigned NumBBs = MF.getNumBlockIDs();
96   BBAnalysis.resize(NumBBs);
97
98   std::vector<int> Candidates;
99   // Do an intial analysis for each basic block and finding all the potential
100   // candidates to perform if-convesion.
101   InitialFunctionAnalysis(MF, Candidates);
102
103   MadeChange = false;
104   for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
105     BBInfo &BBI = BBAnalysis[Candidates[i]];
106     switch (BBI.Kind) {
107     default: assert(false && "Unexpected!");
108       break;
109     case ICTriangleEntry:
110       MadeChange |= IfConvertTriangle(BBI);
111       break;
112     case ICDiamondEntry:
113       MadeChange |= IfConvertDiamond(BBI);
114       break;
115     }
116   }
117
118   BBAnalysis.clear();
119
120   return MadeChange;
121 }
122
123 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
124                                          MachineBasicBlock *TrueBB) {
125   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
126          E = BB->succ_end(); SI != E; ++SI) {
127     MachineBasicBlock *SuccBB = *SI;
128     if (SuccBB != TrueBB)
129       return SuccBB;
130   }
131   return NULL;
132 }
133
134 /// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
135 /// the specified block. Record its successors and whether it looks like an
136 /// if-conversion candidate.
137 void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
138   BBInfo &BBI = BBAnalysis[BB->getNumber()];
139
140   if (BBI.Kind != ICInvalid)
141     return;  // Always analyzed.
142   BBI.BB = BB;
143   BBI.Size = std::distance(BB->begin(), BB->end());
144
145   // Look for 'root' of a simple (non-nested) triangle or diamond.
146   BBI.Kind = ICNotClassfied;
147   if (TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.Cond)
148       || !BBI.TrueBB || BBI.Cond.size() == 0)
149     return;
150
151   // Not a candidate if 'true' block has another predecessor.
152   // FIXME: Use or'd predicate or predicated cmp.
153   if (BBI.TrueBB->pred_size() > 1)
154     return;
155
156   // Not a candidate if 'true' block is going to be if-converted.
157   StructuralAnalysis(BBI.TrueBB);
158   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
159   if (TrueBBI.Kind != ICNotClassfied)
160     return;
161
162   // TODO: Only handle very simple cases for now.
163   if (TrueBBI.FalseBB || TrueBBI.Cond.size())
164     return;
165
166   // No false branch. This BB must end with a conditional branch and a
167   // fallthrough.
168   if (!BBI.FalseBB)
169     BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);  
170   assert(BBI.FalseBB && "Expected to find the fallthrough block!");
171
172   // Not a candidate if 'false' block has another predecessor.
173   // FIXME: Invert condition and swap 'true' / 'false' blocks?
174   if (BBI.FalseBB->pred_size() > 1)
175     return;
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   if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
188     // Triangle:
189     //   EBB
190     //   | \_
191     //   |  |
192     //   | TBB
193     //   |  /
194     //   FBB
195     BBI.Kind = ICTriangleEntry;
196     TrueBBI.Kind = FalseBBI.Kind = ICTriangle;
197   } else if (TrueBBI.TrueBB == FalseBBI.TrueBB) {
198     // Diamond:
199     //   EBB
200     //   / \_
201     //  |   |
202     // TBB FBB
203     //   \ /
204     //  TailBB
205     // Note MBB can be empty in case both TBB and FBB are return blocks.
206     BBI.Kind = ICDiamondEntry;
207     TrueBBI.Kind = FalseBBI.Kind = ICDiamond;
208     BBI.TailBB = TrueBBI.TrueBB;
209   }
210   return;
211 }
212
213 /// FeasibilityAnalysis - Determine if the block is predicable. In most
214 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
215 /// Also checks if the block contains any instruction which can clobber a
216 /// predicate (e.g. condition code register). If so, the block is not
217 /// predicable unless it's the last instruction. Note, this function assumes
218 /// all the terminator instructions can be converted or deleted so it ignore
219 /// them.
220 void IfConverter::FeasibilityAnalysis(BBInfo &BBI) {
221   if (BBI.Size == 0 || BBI.Size > TLI->getIfCvtBlockSizeLimit())
222     return;
223
224   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
225        I != E; ++I) {
226     // TODO: check if instruction clobbers predicate.
227     if (TII->isTerminatorInstr(I->getOpcode()))
228       break;
229     if (!I->isPredicable())
230       return;
231   }
232
233   BBI.isPredicable = true;
234 }
235
236 /// InitialFunctionAnalysis - Analyze all blocks and find entries for all
237 /// if-conversion candidates.
238 void IfConverter::InitialFunctionAnalysis(MachineFunction &MF,
239                                           std::vector<int> &Candidates) {
240   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
241     MachineBasicBlock *BB = I;
242     StructuralAnalysis(BB);
243     BBInfo &BBI = BBAnalysis[BB->getNumber()];
244     if (BBI.Kind == ICTriangleEntry || BBI.Kind == ICDiamondEntry)
245       Candidates.push_back(BB->getNumber());
246   }
247 }
248
249 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
250 ///
251 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
252    std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
253                                          FromBB->pred_end());
254     for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
255       MachineBasicBlock *Pred = Preds[i];
256       Pred->removeSuccessor(FromBB);
257       if (!Pred->isSuccessor(ToBB))
258         Pred->addSuccessor(ToBB);
259     }
260 }
261
262 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
263 ///
264 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
265    std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
266                                          FromBB->succ_end());
267     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
268       MachineBasicBlock *Succ = Succs[i];
269       FromBB->removeSuccessor(Succ);
270       if (!ToBB->isSuccessor(Succ))
271         ToBB->addSuccessor(Succ);
272     }
273 }
274
275 /// IfConvertTriangle - If convert a triangle sub-CFG.
276 ///
277 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
278   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
279   FeasibilityAnalysis(TrueBBI);
280
281   if (TrueBBI.isPredicable) {
282     BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
283
284     // Predicate the 'true' block after removing its branch.
285     TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
286     PredicateBlock(BBI.TrueBB, BBI.Cond);
287
288     // Join the 'true' and 'false' blocks by copying the instructions
289     // from the 'false' block to the 'true' block.
290     BBI.TrueBB->removeSuccessor(BBI.FalseBB);
291     MergeBlocks(TrueBBI, FalseBBI);
292
293     // Now merge the entry of the triangle with the true block.
294     BBI.Size -= TII->RemoveBranch(*BBI.BB);
295     MergeBlocks(BBI, TrueBBI);
296
297     // Update block info.
298     TrueBBI.Kind = ICInvalid;
299     FalseBBI.Kind = ICInvalid;
300
301     // FIXME: Must maintain LiveIns.
302     NumIfConvBBs++;
303     return true;
304   }
305   return false;
306 }
307
308 /// IfConvertDiamond - If convert a diamond sub-CFG.
309 ///
310 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
311   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
312   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
313   FeasibilityAnalysis(TrueBBI);
314   FeasibilityAnalysis(FalseBBI);
315
316   if (TrueBBI.isPredicable && FalseBBI.isPredicable) {
317     // Check the 'true' and 'false' blocks if either isn't ended with a branch.
318     // Either the block fallthrough to another block or it ends with a
319     // return. If it's the former, add a conditional branch to its successor.
320     bool Proceed = true;
321     bool TrueNeedCBr  = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
322     bool FalseNeedCBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
323     if (TrueNeedCBr && TrueBBI.ClobbersPred) {
324       TrueBBI.isPredicable = false;
325       Proceed = false;
326     }
327     if (FalseNeedCBr && FalseBBI.ClobbersPred) {
328       FalseBBI.isPredicable = false;
329       Proceed = false;
330     }
331     if (!Proceed)
332       return false;
333
334     std::vector<MachineInstr*> Dups;
335     if (!BBI.TailBB) {
336       // No common merge block. Check if the terminators (e.g. return) are
337       // the same or predicable.
338       MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
339       MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
340       while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
341         if (TT->isIdenticalTo(FT))
342           Dups.push_back(TT);  // Will erase these later.
343         else if (!TT->isPredicable() && !FT->isPredicable())
344           return false; // Can't if-convert. Abort!
345         ++TT;
346         ++FT;
347       }
348       // One of the two pathes have more terminators, make sure they are all
349       // predicable.
350       while (TT != BBI.TrueBB->end())
351         if (!TT->isPredicable())
352           return false; // Can't if-convert. Abort!
353       while (FT != BBI.FalseBB->end())
354         if (!FT->isPredicable())
355           return false; // Can't if-convert. Abort!
356     }
357
358     // Remove the duplicated instructions from the 'true' block.
359     for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
360       Dups[i]->eraseFromParent();
361       --TrueBBI.Size;
362     }
363     
364     // Predicate the 'true' block after removing its branch.
365     TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
366     PredicateBlock(BBI.TrueBB, BBI.Cond);
367
368     // Add a conditional branch to 'true' successor if needed.
369     if (TrueNeedCBr)
370       TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL, BBI.Cond);
371
372     // Predicate the 'false' block.
373     std::vector<MachineOperand> NewCond(BBI.Cond);
374     TII->ReverseBranchCondition(NewCond);
375     PredicateBlock(BBI.FalseBB, NewCond, true);
376
377     // Add a conditional branch to 'false' successor if needed.
378     if (FalseNeedCBr)
379       TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,NewCond);
380
381     // Merge the 'true' and 'false' blocks by copying the instructions
382     // from the 'false' block to the 'true' block.
383     MergeBlocks(TrueBBI, FalseBBI);
384
385     // Remove the conditional branch from entry to the blocks.
386     BBI.Size -= TII->RemoveBranch(*BBI.BB);
387
388     // Merge the combined block into the entry of the diamond if the entry
389     // block is the only predecessor. Otherwise, insert an unconditional
390     // branch.
391     BBInfo *CvtBBI = &TrueBBI;
392     if (BBI.TrueBB->pred_size() == 1) {
393       BBI.BB->removeSuccessor(BBI.TrueBB);
394       MergeBlocks(BBI, TrueBBI);
395       CvtBBI = &BBI;
396     } else {
397       std::vector<MachineOperand> NoCond;
398       TII->InsertBranch(*BBI.BB, BBI.TrueBB, NULL, NoCond);
399     }
400
401     // If the if-converted block fallthrough into the tail block, then
402     // fold the tail block in as well.
403     if (BBI.TailBB && CvtBBI->BB->succ_size() == 1) {
404       CvtBBI->Size -= TII->RemoveBranch(*CvtBBI->BB);
405       CvtBBI->BB->removeSuccessor(BBI.TailBB);
406       BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
407       MergeBlocks(*CvtBBI, TailBBI);
408       TailBBI.Kind = ICInvalid;
409     }
410
411     // Update block info.
412     TrueBBI.Kind = ICInvalid;
413     FalseBBI.Kind = ICInvalid;
414
415     // FIXME: Must maintain LiveIns.
416     NumIfConvBBs += 2;
417     return true;
418   }
419   return false;
420 }
421
422 /// PredicateBlock - Predicate every instruction in the block with the specified
423 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
424 void IfConverter::PredicateBlock(MachineBasicBlock *BB,
425                                  std::vector<MachineOperand> &Cond,
426                                  bool IgnoreTerm) {
427   for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
428        I != E; ++I) {
429     if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
430       continue;
431     if (!TII->PredicateInstruction(&*I, Cond)) {
432       cerr << "Unable to predication " << *I << "!\n";
433       abort();
434     }
435   }
436 }
437
438 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
439 ///
440 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
441   ToBBI.BB->splice(ToBBI.BB->end(),
442                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
443   TransferPreds(ToBBI.BB, FromBBI.BB);
444   TransferSuccs(ToBBI.BB, FromBBI.BB);
445   ToBBI.Size += FromBBI.Size;
446   FromBBI.Size = 0;
447 }