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