1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the machine instruction level if-conversion pass.
12 //===----------------------------------------------------------------------===//
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"
24 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
27 class IfConverter : public MachineFunctionPass {
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.
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
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) {}
52 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
53 /// basic block number.
54 std::vector<BBInfo> BBAnalysis;
56 const TargetInstrInfo *TII;
60 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
62 virtual bool runOnMachineFunction(MachineFunction &MF);
63 virtual const char *getPassName() const { return "If converter"; }
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 isBlockPredicable(MachineBasicBlock *BB) const;
72 void PredicateBlock(MachineBasicBlock *BB,
73 std::vector<MachineOperand> &Cond,
74 bool IgnoreTerm = false);
75 void MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB);
77 char IfConverter::ID = 0;
80 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
82 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
83 TII = MF.getTarget().getInstrInfo();
84 if (!TII) return false;
89 unsigned NumBBs = MF.getNumBlockIDs();
90 BBAnalysis.resize(NumBBs);
92 std::vector<int> Candidates;
93 // Do an intial analysis for each basic block and finding all the potential
94 // candidates to perform if-convesion.
95 InitialFunctionAnalysis(MF, Candidates);
97 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
98 BBInfo &BBI = BBAnalysis[i];
100 default: assert(false && "Unexpected!");
102 case ICTriangleEntry:
103 MadeChange |= IfConvertTriangle(BBI);
106 MadeChange |= IfConvertDiamond(BBI);
113 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
114 MachineBasicBlock *TBB) {
115 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
116 E = BB->succ_end(); SI != E; ++SI) {
117 MachineBasicBlock *SuccBB = *SI;
124 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
125 BBInfo &BBI = BBAnalysis[BB->getNumber()];
127 if (BBI.Kind != ICInvalid)
128 return; // Always analyzed.
131 // Look for 'root' of a simple (non-nested) triangle or diamond.
132 BBI.Kind = ICNotClassfied;
133 if (TII->AnalyzeBranch(*BB, BBI.TBB, BBI.FBB, BBI.Cond)
134 || !BBI.TBB || BBI.Cond.size() == 0)
136 // Can't do it if 'true' block is already marked as to be if-converted.
137 AnalyzeBlock(BBI.TBB);
138 BBInfo &TBBI = BBAnalysis[BBI.TBB->getNumber()];
139 if (TBBI.Kind != ICNotClassfied)
142 // No false branch. This BB must end with a conditional branch and a
145 BBI.FBB = findFalseBlock(BB, BBI.TBB);
146 assert(BBI.FBB && "Expected to find the fallthrough block!");
148 // Can't do it if 'false' block is already marked as to be if-converted.
149 AnalyzeBlock(BBI.FBB);
150 BBInfo &FBBI = BBAnalysis[BBI.FBB->getNumber()];
151 if (FBBI.Kind != ICNotClassfied)
154 // TODO: Only handle very simple cases for now.
155 if (TBBI.FBB || FBBI.FBB || TBBI.Cond.size() > 1 || FBBI.Cond.size() > 1)
158 if (TBBI.TBB && TBBI.TBB == BBI.FBB) {
166 BBI.Kind = ICTriangleEntry;
167 TBBI.Kind = FBBI.Kind = ICTriangle;
168 } else if (TBBI.TBB == FBBI.TBB) {
176 // Note MBB can be empty in case both TBB and FBB are return blocks.
177 BBI.Kind = ICDiamondEntry;
178 TBBI.Kind = FBBI.Kind = ICDiamond;
184 /// InitialFunctionAnalysis - Analyze all blocks and find entries for all
185 /// if-conversion candidates.
186 void IfConverter::InitialFunctionAnalysis(MachineFunction &MF,
187 std::vector<int> &Candidates) {
188 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
189 MachineBasicBlock *BB = I;
191 BBInfo &BBI = BBAnalysis[BB->getNumber()];
192 if (BBI.Kind == ICTriangleEntry || BBI.Kind == ICDiamondEntry)
193 Candidates.push_back(BB->getNumber());
197 /// IfConvertTriangle - If convert a triangle sub-CFG.
199 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
200 if (isBlockPredicable(BBI.TBB)) {
201 // Predicate the 'true' block after removing its branch.
202 TII->RemoveBranch(*BBI.TBB);
203 PredicateBlock(BBI.TBB, BBI.Cond);
205 // Join the 'true' and 'false' blocks by copying the instructions
206 // from the 'false' block to the 'true' block.
207 MergeBlocks(BBI.TBB, BBI.FBB);
209 // Adjust entry block, it should have but a single unconditional
211 BBI.EBB->removeSuccessor(BBI.FBB);
212 TII->RemoveBranch(*BBI.EBB);
213 std::vector<MachineOperand> NoCond;
214 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
216 // FIXME: Must maintain LiveIns.
223 /// IfConvertDiamond - If convert a diamond sub-CFG.
225 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
226 if (isBlockPredicable(BBI.TBB) && isBlockPredicable(BBI.FBB)) {
227 std::vector<MachineInstr*> Dups;
229 // No common merge block. Check if the terminators (e.g. return) are
230 // the same or predicable.
231 MachineBasicBlock::iterator TT = BBI.TBB->getFirstTerminator();
232 MachineBasicBlock::iterator FT = BBI.FBB->getFirstTerminator();
233 while (TT != BBI.TBB->end() && FT != BBI.FBB->end()) {
234 if (TT->isIdenticalTo(FT))
235 Dups.push_back(TT); // Will erase these later.
236 else if (!TT->isPredicable() && !FT->isPredicable())
237 return false; // Can't if-convert. Abort!
241 // One of the two pathes have more terminators, make sure they are all
243 while (TT != BBI.TBB->end())
244 if (!TT->isPredicable())
245 return false; // Can't if-convert. Abort!
246 while (FT != BBI.FBB->end())
247 if (!FT->isPredicable())
248 return false; // Can't if-convert. Abort!
251 // Remove the duplicated instructions from the 'true' block.
252 for (unsigned i = 0, e = Dups.size(); i != e; ++i)
253 Dups[i]->eraseFromParent();
255 // Predicate the 'true' block after removing its branch.
256 TII->RemoveBranch(*BBI.TBB);
257 PredicateBlock(BBI.TBB, BBI.Cond);
259 // Predicate the 'false' block.
260 std::vector<MachineOperand> NewCond(BBI.Cond);
261 TII->ReverseBranchCondition(NewCond);
262 PredicateBlock(BBI.FBB, NewCond, true);
264 // Join the 'true' and 'false' blocks by copying the instructions
265 // from the 'false' block to the 'true' block.
266 MergeBlocks(BBI.TBB, BBI.FBB);
268 // Adjust entry block, it should have but a single unconditional
270 BBI.EBB->removeSuccessor(BBI.FBB);
271 TII->RemoveBranch(*BBI.EBB);
272 std::vector<MachineOperand> NoCond;
273 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
275 // FIXME: Must maintain LiveIns.
282 /// isBlockPredicable - Returns true if the block is predicable. In most
283 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
284 /// It assume all the terminator instructions can be converted or deleted.
285 bool IfConverter::isBlockPredicable(MachineBasicBlock *BB) const {
286 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
288 if (TII->isTerminatorInstr(I->getOpcode()))
290 if (!I->isPredicable())
296 /// PredicateBlock - Predicate every instruction in the block with the specified
297 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
298 void IfConverter::PredicateBlock(MachineBasicBlock *BB,
299 std::vector<MachineOperand> &Cond,
301 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
303 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
305 if (!TII->PredicateInstruction(&*I, Cond)) {
306 cerr << "Unable to predication " << *I << "!\n";
312 /// MergeBlocks - Move all instructions from FBB to the end of TBB.
314 void IfConverter::MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB) {
315 TBB->splice(TBB->end(), FBB, FBB->begin(), FBB->end());