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
42 /// diamond shape), its size, whether it's predicable, and whether any
43 /// instruction can clobber the 'would-be' predicate.
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) {}
58 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
59 /// basic block number.
60 std::vector<BBInfo> BBAnalysis;
62 const TargetLowering *TLI;
63 const TargetInstrInfo *TII;
67 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
69 virtual bool runOnMachineFunction(MachineFunction &MF);
70 virtual const char *getPassName() const { return "If converter"; }
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);
84 char IfConverter::ID = 0;
87 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
89 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
90 TLI = MF.getTarget().getTargetLowering();
91 TII = MF.getTarget().getInstrInfo();
92 if (!TII) return false;
95 unsigned NumBBs = MF.getNumBlockIDs();
96 BBAnalysis.resize(NumBBs);
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);
104 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
105 BBInfo &BBI = BBAnalysis[Candidates[i]];
107 default: assert(false && "Unexpected!");
109 case ICTriangleEntry:
110 MadeChange |= IfConvertTriangle(BBI);
113 MadeChange |= IfConvertDiamond(BBI);
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)
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()];
140 if (BBI.Kind != ICInvalid)
141 return; // Always analyzed.
143 BBI.Size = std::distance(BB->begin(), BB->end());
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)
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)
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)
162 // TODO: Only handle very simple cases for now.
163 if (TrueBBI.FalseBB || TrueBBI.Cond.size())
166 // No false branch. This BB must end with a conditional branch and a
169 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
170 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
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)
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)
183 // TODO: Only handle very simple cases for now.
184 if (FalseBBI.FalseBB || FalseBBI.Cond.size())
187 if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
195 BBI.Kind = ICTriangleEntry;
196 TrueBBI.Kind = FalseBBI.Kind = ICTriangle;
197 } else if (TrueBBI.TrueBB == FalseBBI.TrueBB) {
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;
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
220 void IfConverter::FeasibilityAnalysis(BBInfo &BBI) {
221 if (BBI.Size == 0 || BBI.Size > TLI->getIfCvtBlockSizeLimit())
224 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
226 // TODO: check if instruction clobbers predicate.
227 if (TII->isTerminatorInstr(I->getOpcode()))
229 if (!I->isPredicable())
233 BBI.isPredicable = true;
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());
249 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
251 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
252 std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
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);
262 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
264 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
265 std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
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);
275 /// IfConvertTriangle - If convert a triangle sub-CFG.
277 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
278 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
279 FeasibilityAnalysis(TrueBBI);
281 if (TrueBBI.isPredicable) {
282 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
284 // Predicate the 'true' block after removing its branch.
285 TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
286 PredicateBlock(BBI.TrueBB, BBI.Cond);
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);
293 // Now merge the entry of the triangle with the true block.
294 BBI.Size -= TII->RemoveBranch(*BBI.BB);
295 MergeBlocks(BBI, TrueBBI);
297 // Update block info.
298 TrueBBI.Kind = ICInvalid;
299 FalseBBI.Kind = ICInvalid;
301 // FIXME: Must maintain LiveIns.
308 /// IfConvertDiamond - If convert a diamond sub-CFG.
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);
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.
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;
327 if (FalseNeedCBr && FalseBBI.ClobbersPred) {
328 FalseBBI.isPredicable = false;
334 std::vector<MachineInstr*> Dups;
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!
348 // One of the two pathes have more terminators, make sure they are all
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!
358 // Remove the duplicated instructions from the 'true' block.
359 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
360 Dups[i]->eraseFromParent();
364 // Predicate the 'true' block after removing its branch.
365 TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
366 PredicateBlock(BBI.TrueBB, BBI.Cond);
368 // Add a conditional branch to 'true' successor if needed.
370 TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL, BBI.Cond);
372 // Predicate the 'false' block.
373 std::vector<MachineOperand> NewCond(BBI.Cond);
374 TII->ReverseBranchCondition(NewCond);
375 PredicateBlock(BBI.FalseBB, NewCond, true);
377 // Add a conditional branch to 'false' successor if needed.
379 TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,NewCond);
381 // Merge the 'true' and 'false' blocks by copying the instructions
382 // from the 'false' block to the 'true' block.
383 MergeBlocks(TrueBBI, FalseBBI);
385 // Remove the conditional branch from entry to the blocks.
386 BBI.Size -= TII->RemoveBranch(*BBI.BB);
388 // Merge the combined block into the entry of the diamond if the entry
389 // block is the only predecessor. Otherwise, insert an unconditional
391 BBInfo *CvtBBI = &TrueBBI;
392 if (BBI.TrueBB->pred_size() == 1) {
393 BBI.BB->removeSuccessor(BBI.TrueBB);
394 MergeBlocks(BBI, TrueBBI);
397 std::vector<MachineOperand> NoCond;
398 TII->InsertBranch(*BBI.BB, BBI.TrueBB, NULL, NoCond);
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;
411 // Update block info.
412 TrueBBI.Kind = ICInvalid;
413 FalseBBI.Kind = ICInvalid;
415 // FIXME: Must maintain LiveIns.
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,
427 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
429 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
431 if (!TII->PredicateInstruction(&*I, Cond)) {
432 cerr << "Unable to predication " << *I << "!\n";
438 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
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;