blob: 57f6a8df5e2cba06778367357ad9488ff3014795 [file] [log] [blame]
Evan Cheng4e654852007-05-16 02:00:57 +00001//===-- 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/TargetMachine.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/ADT/Statistic.h"
22using namespace llvm;
23
24STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
25
26namespace {
27 class IfConverter : public MachineFunctionPass {
28 enum BBICKind {
29 ICInvalid, // BB data invalid.
30 ICNotClassfied, // BB data valid, but not classified.
31 ICTriangle, // BB is part of a triangle sub-CFG.
32 ICDiamond, // BB is part of a diamond sub-CFG.
33 ICTriangleEntry, // BB is entry of a triangle sub-CFG.
34 ICDiamondEntry // BB is entry of a diamond sub-CFG.
35 };
36
37 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
38 /// if-conversion feasibility analysis. This includes results from
39 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
40 /// classification, and common merge block of its successors (if it's a
41 /// diamond shape).
42 struct BBInfo {
43 BBICKind Kind;
44 MachineBasicBlock *EBB;
45 MachineBasicBlock *TBB;
46 MachineBasicBlock *FBB;
47 MachineBasicBlock *CMBB;
48 std::vector<MachineOperand> Cond;
49 BBInfo() : Kind(ICInvalid), EBB(0), TBB(0), FBB(0), CMBB(0) {}
50 };
51
52 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
53 /// basic block number.
54 std::vector<BBInfo> BBAnalysis;
55
56 const TargetInstrInfo *TII;
57 bool MadeChange;
58 public:
59 static char ID;
60 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
61
62 virtual bool runOnMachineFunction(MachineFunction &MF);
63 virtual const char *getPassName() const { return "If converter"; }
64
65 private:
66 void AnalyzeBlock(MachineBasicBlock *BB);
67 void InitialFunctionAnalysis(MachineFunction &MF,
68 std::vector<int> &Candidates);
69 bool IfConvertDiamond(BBInfo &BBI);
70 bool IfConvertTriangle(BBInfo &BBI);
71 bool isBlockPredicatable(MachineBasicBlock *BB,
72 bool IgnoreTerm = false) const;
73 void PredicateBlock(MachineBasicBlock *BB,
74 std::vector<MachineOperand> &Cond,
75 bool IgnoreTerm = false);
76 void MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB);
77 };
78 char IfConverter::ID = 0;
79}
80
81FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
82
83bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
84 TII = MF.getTarget().getInstrInfo();
85 if (!TII) return false;
86
87 MadeChange = false;
88
89 MF.RenumberBlocks();
90 unsigned NumBBs = MF.getNumBlockIDs();
91 BBAnalysis.resize(NumBBs);
92
93 std::vector<int> Candidates;
94 // Do an intial analysis for each basic block and finding all the potential
95 // candidates to perform if-convesion.
96 InitialFunctionAnalysis(MF, Candidates);
97
98 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
99 BBInfo &BBI = BBAnalysis[i];
100 switch (BBI.Kind) {
101 default: assert(false && "Unexpected!");
102 break;
103 case ICTriangleEntry:
104 MadeChange |= IfConvertTriangle(BBI);
105 break;
106 case ICDiamondEntry:
107 MadeChange |= IfConvertDiamond(BBI);
108 break;
109 }
110 }
111 return MadeChange;
112}
113
114static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
115 MachineBasicBlock *TBB) {
116 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
117 E = BB->succ_end(); SI != E; ++SI) {
118 MachineBasicBlock *SuccBB = *SI;
119 if (SuccBB != TBB)
120 return SuccBB;
121 }
122 return NULL;
123}
124
125void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
126 BBInfo &BBI = BBAnalysis[BB->getNumber()];
127
128 if (BBI.Kind != ICInvalid)
129 return; // Always analyzed.
130 BBI.EBB = BB;
131
132 // Look for 'root' of a simple (non-nested) triangle or diamond.
133 BBI.Kind = ICNotClassfied;
134 if (TII->AnalyzeBranch(*BB, BBI.TBB, BBI.FBB, BBI.Cond)
135 || !BBI.TBB || BBI.Cond.size() == 0)
136 return;
137 AnalyzeBlock(BBI.TBB);
138 BBInfo &TBBI = BBAnalysis[BBI.TBB->getNumber()];
139 if (TBBI.Kind != ICNotClassfied)
140 return;
141
142 if (!BBI.FBB)
143 BBI.FBB = findFalseBlock(BB, BBI.TBB);
144 AnalyzeBlock(BBI.FBB);
145 BBInfo &FBBI = BBAnalysis[BBI.FBB->getNumber()];
146 if (FBBI.Kind != ICNotClassfied)
147 return;
148
149 // TODO: Only handle very simple cases for now.
150 if (TBBI.FBB || FBBI.FBB || TBBI.Cond.size() > 1 || FBBI.Cond.size() > 1)
151 return;
152
153 if (TBBI.TBB && TBBI.TBB == BBI.FBB) {
154 // Triangle:
155 // EBB
156 // | \_
157 // | |
158 // | TBB
159 // | /
160 // FBB
161 BBI.Kind = ICTriangleEntry;
162 TBBI.Kind = FBBI.Kind = ICTriangle;
163 } else if (TBBI.TBB == FBBI.TBB) {
164 // Diamond:
165 // EBB
166 // / \_
167 // | |
168 // TBB FBB
169 // \ /
170 // MBB
171 // Note MBB can be empty in case both TBB and FBB are return blocks.
172 BBI.Kind = ICDiamondEntry;
173 TBBI.Kind = FBBI.Kind = ICDiamond;
174 BBI.CMBB = TBBI.TBB;
175 }
176 return;
177}
178
179void IfConverter::InitialFunctionAnalysis(MachineFunction &MF,
180 std::vector<int> &Candidates) {
181 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
182 MachineBasicBlock *BB = I;
183 AnalyzeBlock(BB);
184 BBInfo &BBI = BBAnalysis[BB->getNumber()];
185 if (BBI.Kind == ICTriangleEntry || BBI.Kind == ICDiamondEntry)
186 Candidates.push_back(BB->getNumber());
187 }
188}
189
190bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
191 if (isBlockPredicatable(BBI.TBB, true)) {
192 // Predicate the 'true' block after removing its branch.
193 TII->RemoveBranch(*BBI.TBB);
194 PredicateBlock(BBI.TBB, BBI.Cond);
195
196 // Join the 'true' and 'false' blocks by copying the instructions
197 // from the 'false' block to the 'true' block.
198 MergeBlocks(BBI.TBB, BBI.FBB);
199
200 // Adjust entry block, it should have but a single unconditional
201 // branch.
202 BBI.EBB->removeSuccessor(BBI.FBB);
203 TII->RemoveBranch(*BBI.EBB);
204 std::vector<MachineOperand> NoCond;
205 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
206
207 // FIXME: Must maintain LiveIns.
208 NumIfConvBBs++;
209 return true;
210 }
211 return false;
212}
213
214bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
215 if (isBlockPredicatable(BBI.TBB, true) &&
216 isBlockPredicatable(BBI.FBB, true)) {
217 std::vector<MachineInstr*> Dups;
218 if (!BBI.CMBB) {
219 // No common merge block. Check if the terminators (e.g. return) are
220 // the same or predicatable.
221 MachineBasicBlock::iterator TT = BBI.TBB->getFirstTerminator();
222 MachineBasicBlock::iterator FT = BBI.FBB->getFirstTerminator();
223 while (TT != BBI.TBB->end() && FT != BBI.FBB->end()) {
224 if (TT->isIdenticalTo(FT))
225 Dups.push_back(TT); // Will erase these later.
226 else if (!TII->isPredicatable(TT) && !TII->isPredicatable(FT))
227 return false; // Can't if-convert. Abort!
228 ++TT;
229 ++FT;
230 }
231
232 while (TT != BBI.TBB->end())
233 if (!TII->isPredicatable(TT))
234 return false; // Can't if-convert. Abort!
235 while (FT != BBI.FBB->end())
236 if (!TII->isPredicatable(FT))
237 return false; // Can't if-convert. Abort!
238 }
239
240 // Remove the duplicated instructions from the 'true' block.
241 for (unsigned i = 0, e = Dups.size(); i != e; ++i)
242 Dups[i]->eraseFromParent();
243
244 // Predicate the 'true' block after removing its branch.
245 TII->RemoveBranch(*BBI.TBB);
246 PredicateBlock(BBI.TBB, BBI.Cond);
247
248 // Predicate the 'false' block.
249 std::vector<MachineOperand> NewCond(BBI.Cond);
250 TII->ReverseBranchCondition(NewCond);
251 PredicateBlock(BBI.FBB, NewCond, true);
252
253 // Join the 'true' and 'false' blocks by copying the instructions
254 // from the 'false' block to the 'true' block.
255 MergeBlocks(BBI.TBB, BBI.FBB);
256
257 // Adjust entry block, it should have but a single unconditional
258 // branch .
259 BBI.EBB->removeSuccessor(BBI.FBB);
260 TII->RemoveBranch(*BBI.EBB);
261 std::vector<MachineOperand> NoCond;
262 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
263
264 // FIXME: Must maintain LiveIns.
265 NumIfConvBBs += 2;
266 return true;
267 }
268 return false;
269}
270
271/// isBlockPredicatable - Returns true if the block is predicatable. In most
272/// cases, that means all the instructions in the block has M_PREDICATED flag.
273/// If IgnoreTerm is true, assume all the terminator instructions can be
274/// converted or deleted.
275bool IfConverter::isBlockPredicatable(MachineBasicBlock *BB,
276 bool IgnoreTerm) const {
277 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
278 I != E; ++I) {
279 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
280 continue;
281 if (!TII->isPredicatable(I))
282 return false;
283 }
284 return true;
285}
286
287/// PredicateBlock - Predicate every instruction in the block with the specified
288/// condition. If IgnoreTerm is true, skip over all terminator instructions.
289void IfConverter::PredicateBlock(MachineBasicBlock *BB,
290 std::vector<MachineOperand> &Cond,
291 bool IgnoreTerm) {
292 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
293 I != E; ++I) {
294 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
295 continue;
296 TII->PredicateInstruction(&*I, Cond);
297 }
298}
299
300/// MergeBlocks - Move all instructions from FBB to the end of TBB.
301///
302void IfConverter::MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB) {
303 TBB->splice(TBB->end(), FBB, FBB->begin(), FBB->end());
304}