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/TargetLowering.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/ADT/Statistic.h"
25 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
28 class IfConverter : public MachineFunctionPass {
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.
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
45 MachineBasicBlock *BB;
46 MachineBasicBlock *TrueBB;
47 MachineBasicBlock *FalseBB;
48 MachineBasicBlock *TailBB;
49 std::vector<MachineOperand> Cond;
51 BBInfo() : Kind(ICInvalid), BB(0), TrueBB(0), FalseBB(0), TailBB(0), Size(0) {}
54 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
55 /// basic block number.
56 std::vector<BBInfo> BBAnalysis;
58 const TargetLowering *TLI;
59 const TargetInstrInfo *TII;
63 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
65 virtual bool runOnMachineFunction(MachineFunction &MF);
66 virtual const char *getPassName() const { return "If converter"; }
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);
80 char IfConverter::ID = 0;
83 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
85 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
86 TLI = MF.getTarget().getTargetLowering();
87 TII = MF.getTarget().getInstrInfo();
88 if (!TII) return false;
93 unsigned NumBBs = MF.getNumBlockIDs();
94 BBAnalysis.resize(NumBBs);
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);
101 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
102 BBInfo &BBI = BBAnalysis[Candidates[i]];
104 default: assert(false && "Unexpected!");
106 case ICTriangleEntry:
107 MadeChange |= IfConvertTriangle(BBI);
110 MadeChange |= IfConvertDiamond(BBI);
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)
128 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
129 BBInfo &BBI = BBAnalysis[BB->getNumber()];
131 if (BBI.Kind != ICInvalid)
132 return; // Always analyzed.
134 BBI.Size = std::distance(BB->begin(), BB->end());
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)
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)
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)
153 // No false branch. This BB must end with a conditional branch and a
156 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
157 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
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)
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)
170 // TODO: Only handle very simple cases for now.
171 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
172 TrueBBI.Cond.size() || FalseBBI.Cond.size())
175 if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
183 BBI.Kind = ICTriangleEntry;
184 TrueBBI.Kind = FalseBBI.Kind = ICTriangle;
185 } else if (TrueBBI.TrueBB == FalseBBI.TrueBB) {
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;
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;
208 BBInfo &BBI = BBAnalysis[BB->getNumber()];
209 if (BBI.Kind == ICTriangleEntry || BBI.Kind == ICDiamondEntry)
210 Candidates.push_back(BB->getNumber());
214 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
216 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
217 std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
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);
227 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
229 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
230 std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
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);
240 /// IfConvertTriangle - If convert a triangle sub-CFG.
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()];
247 // Predicate the 'true' block after removing its branch.
248 TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
249 PredicateBlock(BBI.TrueBB, BBI.Cond);
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);
256 // Now merge the entry of the triangle with the true block.
257 BBI.Size -= TII->RemoveBranch(*BBI.BB);
258 MergeBlocks(BBI, TrueBBI);
260 // Update block info.
261 TrueBBI.Kind = ICInvalid;
262 FalseBBI.Kind = ICInvalid;
264 // FIXME: Must maintain LiveIns.
271 /// IfConvertDiamond - If convert a diamond sub-CFG.
273 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
274 if (isBlockPredicable(BBI.TrueBB) && isBlockPredicable(BBI.FalseBB)) {
275 std::vector<MachineInstr*> Dups;
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!
289 // One of the two pathes have more terminators, make sure they are all
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!
299 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
300 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
302 // Remove the duplicated instructions from the 'true' block.
303 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
304 Dups[i]->eraseFromParent();
308 // Predicate the 'true' block after removing its branch.
309 TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
310 PredicateBlock(BBI.TrueBB, BBI.Cond);
312 // Predicate the 'false' block.
313 std::vector<MachineOperand> NewCond(BBI.Cond);
314 TII->ReverseBranchCondition(NewCond);
315 PredicateBlock(BBI.FalseBB, NewCond, true);
317 // Merge the 'true' and 'false' blocks by copying the instructions
318 // from the 'false' block to the 'true' block.
319 MergeBlocks(TrueBBI, FalseBBI);
321 // Remove the conditional branch from entry to the blocks.
322 BBI.Size -= TII->RemoveBranch(*BBI.BB);
324 // Merge the combined block into the entry of the diamond if the entry
325 // block is the only predecessor. Otherwise, insert an unconditional
327 BBInfo *CvtBBI = &TrueBBI;
328 if (BBI.TrueBB->pred_size() == 1) {
329 BBI.BB->removeSuccessor(BBI.TrueBB);
330 MergeBlocks(BBI, TrueBBI);
333 std::vector<MachineOperand> NoCond;
334 TII->InsertBranch(*BBI.BB, BBI.TrueBB, NULL, NoCond);
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;
347 // Update block info.
348 TrueBBI.Kind = ICInvalid;
349 FalseBBI.Kind = ICInvalid;
351 // FIXME: Must maintain LiveIns.
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())
366 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
368 if (TII->isTerminatorInstr(I->getOpcode()))
370 if (!I->isPredicable())
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,
381 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
383 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
385 if (!TII->PredicateInstruction(&*I, Cond)) {
386 cerr << "Unable to predication " << *I << "!\n";
392 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
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;