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/DepthFirstIterator.h"
23 #include "llvm/ADT/Statistic.h"
26 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
29 class IfConverter : public MachineFunctionPass {
31 ICInvalid, // BB data invalid.
32 ICNotClassfied, // BB data valid, but not classified.
33 ICEarlyExit, // BB is entry of an early-exit sub-CFG.
34 ICTriangle, // BB is entry of a triangle sub-CFG.
35 ICDiamond, // BB is entry of a diamond sub-CFG.
36 ICChild, // BB is part of the sub-CFG that'll be predicated.
37 ICDead // BB has been converted and merged, it's now dead.
40 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
41 /// if-conversion feasibility analysis. This includes results from
42 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
43 /// classification, and common tail block of its successors (if it's a
44 /// diamond shape), its size, whether it's predicable, and whether any
45 /// instruction can clobber the 'would-be' predicate.
52 MachineBasicBlock *BB;
53 MachineBasicBlock *TrueBB;
54 MachineBasicBlock *FalseBB;
55 MachineBasicBlock *TailBB;
56 std::vector<MachineOperand> Cond;
57 BBInfo() : Kind(ICInvalid), Size(0), isPredicable(false),
58 ClobbersPred(false), hasEarlyExit(false),
59 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
62 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
63 /// basic block number.
64 std::vector<BBInfo> BBAnalysis;
66 const TargetLowering *TLI;
67 const TargetInstrInfo *TII;
71 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
73 virtual bool runOnMachineFunction(MachineFunction &MF);
74 virtual const char *getPassName() const { return "If converter"; }
77 void StructuralAnalysis(MachineBasicBlock *BB);
78 void FeasibilityAnalysis(BBInfo &BBI);
79 void InitialFunctionAnalysis(MachineFunction &MF,
80 std::vector<BBInfo*> &Candidates);
81 bool IfConvertEarlyExit(BBInfo &BBI);
82 bool IfConvertTriangle(BBInfo &BBI);
83 bool IfConvertDiamond(BBInfo &BBI);
84 void PredicateBlock(MachineBasicBlock *BB,
85 std::vector<MachineOperand> &Cond,
86 bool IgnoreTerm = false);
87 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
89 char IfConverter::ID = 0;
92 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
94 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
95 TLI = MF.getTarget().getTargetLowering();
96 TII = MF.getTarget().getInstrInfo();
97 if (!TII) return false;
100 unsigned NumBBs = MF.getNumBlockIDs();
101 BBAnalysis.resize(NumBBs);
103 std::vector<BBInfo*> Candidates;
104 // Do an intial analysis for each basic block and finding all the potential
105 // candidates to perform if-convesion.
106 InitialFunctionAnalysis(MF, Candidates);
109 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
110 BBInfo &BBI = *Candidates[i];
112 default: assert(false && "Unexpected!");
115 MadeChange |= IfConvertEarlyExit(BBI);
118 MadeChange |= IfConvertTriangle(BBI);
121 MadeChange |= IfConvertDiamond(BBI);
131 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
132 MachineBasicBlock *TrueBB) {
133 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
134 E = BB->succ_end(); SI != E; ++SI) {
135 MachineBasicBlock *SuccBB = *SI;
136 if (SuccBB != TrueBB)
142 /// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
143 /// the specified block. Record its successors and whether it looks like an
144 /// if-conversion candidate.
145 void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
146 BBInfo &BBI = BBAnalysis[BB->getNumber()];
148 if (BBI.Kind != ICInvalid)
149 return; // Already analyzed.
151 BBI.Size = std::distance(BB->begin(), BB->end());
153 // Look for 'root' of a simple (non-nested) triangle or diamond.
154 BBI.Kind = ICNotClassfied;
155 bool CanAnalyze = !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.Cond);
156 // Does it end with a return, indirect jump, or jumptable branch?
157 BBI.hasEarlyExit = TII->BlockHasNoFallThrough(*BB) && !BBI.TrueBB;
158 if (!CanAnalyze || !BBI.TrueBB || BBI.Cond.size() == 0)
161 // Not a candidate if 'true' block is going to be if-converted.
162 StructuralAnalysis(BBI.TrueBB);
163 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
164 if (TrueBBI.Kind != ICNotClassfied)
167 // TODO: Only handle very simple cases for now.
168 if (TrueBBI.FalseBB || TrueBBI.Cond.size())
171 // No false branch. This BB must end with a conditional branch and a
174 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
175 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
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 unsigned TrueNumPreds = BBI.TrueBB->pred_size();
188 unsigned FalseNumPreds = BBI.FalseBB->pred_size();
189 if ((TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
190 !(FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
191 BBI.Kind = ICEarlyExit;
192 TrueBBI.Kind = ICChild;
193 } else if (!(TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
194 (FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
195 BBI.Kind = ICEarlyExit;
196 FalseBBI.Kind = ICChild;
197 } else if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
205 BBI.Kind = ICTriangle;
206 TrueBBI.Kind = FalseBBI.Kind = ICChild;
207 } else if (TrueBBI.TrueBB == FalseBBI.TrueBB &&
208 TrueNumPreds <= 1 && FalseNumPreds <= 1) {
216 // Note MBB can be empty in case both TBB and FBB are return blocks.
217 BBI.Kind = ICDiamond;
218 TrueBBI.Kind = FalseBBI.Kind = ICChild;
219 BBI.TailBB = TrueBBI.TrueBB;
224 /// FeasibilityAnalysis - Determine if the block is predicable. In most
225 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
226 /// Also checks if the block contains any instruction which can clobber a
227 /// predicate (e.g. condition code register). If so, the block is not
228 /// predicable unless it's the last instruction. Note, this function assumes
229 /// all the terminator instructions can be converted or deleted so it ignore
231 void IfConverter::FeasibilityAnalysis(BBInfo &BBI) {
232 if (BBI.Size == 0 || BBI.Size > TLI->getIfCvtBlockSizeLimit())
235 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
237 // TODO: check if instruction clobbers predicate.
238 if (TII->isTerminatorInstr(I->getOpcode()))
240 if (!I->isPredicable())
244 BBI.isPredicable = true;
247 /// InitialFunctionAnalysis - Analyze all blocks and find entries for all
248 /// if-conversion candidates.
249 void IfConverter::InitialFunctionAnalysis(MachineFunction &MF,
250 std::vector<BBInfo*> &Candidates) {
251 std::set<MachineBasicBlock*> Visited;
252 MachineBasicBlock *Entry = MF.begin();
253 for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
254 E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
255 MachineBasicBlock *BB = *DFI;
256 StructuralAnalysis(BB);
257 BBInfo &BBI = BBAnalysis[BB->getNumber()];
263 Candidates.push_back(&BBI);
269 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
271 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
272 std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
274 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
275 MachineBasicBlock *Pred = Preds[i];
276 Pred->removeSuccessor(FromBB);
277 if (!Pred->isSuccessor(ToBB))
278 Pred->addSuccessor(ToBB);
282 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
284 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
285 std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
287 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
288 MachineBasicBlock *Succ = Succs[i];
289 FromBB->removeSuccessor(Succ);
290 if (!ToBB->isSuccessor(Succ))
291 ToBB->addSuccessor(Succ);
295 /// isNextBlock - Returns true if ToBB the next basic block after BB.
297 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
298 MachineFunction::iterator Fallthrough = BB;
299 return MachineFunction::iterator(ToBB) == ++Fallthrough;
302 /// IfConvertEarlyExit - If convert a early exit sub-CFG.
304 bool IfConverter::IfConvertEarlyExit(BBInfo &BBI) {
305 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
306 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
307 BBInfo *CvtBBI = &TrueBBI;
308 BBInfo *NextBBI = &FalseBBI;
309 bool ReserveCond = false;
310 if (TrueBBI.Kind != ICChild) {
311 std::swap(CvtBBI, NextBBI);
315 FeasibilityAnalysis(*CvtBBI);
316 if (!CvtBBI->isPredicable) {
317 BBI.Kind = ICNotClassfied;
321 std::vector<MachineOperand> NewCond(BBI.Cond);
323 TII->ReverseBranchCondition(NewCond);
324 PredicateBlock(CvtBBI->BB, NewCond);
326 // Merge converted block into entry block. Also convert the end of the
327 // block conditional branch (to the non-converted block) into an
328 // unconditional one.
329 BBI.Size -= TII->RemoveBranch(*BBI.BB);
330 BBI.BB->removeSuccessor(CvtBBI->BB);
331 MergeBlocks(BBI, *CvtBBI);
332 if (!isNextBlock(BBI.BB, NextBBI->BB)) {
333 std::vector<MachineOperand> NoCond;
334 TII->InsertBranch(*BBI.BB, NextBBI->BB, NULL, NoCond);
337 // Update block info.
338 CvtBBI->Kind = ICDead;
340 // FIXME: Must maintain LiveIns.
345 /// IfConvertTriangle - If convert a triangle sub-CFG.
347 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
348 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
349 FeasibilityAnalysis(TrueBBI);
351 if (!TrueBBI.isPredicable) {
352 BBI.Kind = ICNotClassfied;
356 // Predicate the 'true' block after removing its branch.
357 TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
358 PredicateBlock(BBI.TrueBB, BBI.Cond);
360 // Join the 'true' and 'false' blocks by copying the instructions
361 // from the 'false' block to the 'true' block.
362 BBI.TrueBB->removeSuccessor(BBI.FalseBB);
363 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
364 MergeBlocks(TrueBBI, FalseBBI);
366 // Now merge the entry of the triangle with the true block.
367 BBI.Size -= TII->RemoveBranch(*BBI.BB);
368 MergeBlocks(BBI, TrueBBI);
370 // Update block info.
371 TrueBBI.Kind = ICDead;
373 // FIXME: Must maintain LiveIns.
378 /// IfConvertDiamond - If convert a diamond sub-CFG.
380 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
383 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
384 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
385 FeasibilityAnalysis(TrueBBI);
386 FeasibilityAnalysis(FalseBBI);
388 SmallVector<MachineInstr*, 2> Dups;
389 bool Proceed = TrueBBI.isPredicable && FalseBBI.isPredicable;
391 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
392 // Either the block fallthrough to another block or it ends with a
393 // return. If it's the former, add a conditional branch to its successor.
394 TrueNeedCBr = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
395 FalseNeedCBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
396 if (TrueNeedCBr && TrueBBI.ClobbersPred) {
397 TrueBBI.isPredicable = false;
400 if (FalseNeedCBr && FalseBBI.ClobbersPred) {
401 FalseBBI.isPredicable = false;
407 // No common merge block. Check if the terminators (e.g. return) are
408 // the same or predicable.
409 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
410 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
411 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
412 if (TT->isIdenticalTo(FT))
413 Dups.push_back(TT); // Will erase these later.
414 else if (!TT->isPredicable() && !FT->isPredicable()) {
416 break; // Can't if-convert. Abort!
422 // One of the two pathes have more terminators, make sure they are
424 while (Proceed && TT != BBI.TrueBB->end())
425 if (!TT->isPredicable()) {
427 break; // Can't if-convert. Abort!
429 while (Proceed && FT != BBI.FalseBB->end())
430 if (!FT->isPredicable()) {
432 break; // Can't if-convert. Abort!
439 BBI.Kind = ICNotClassfied;
443 // Remove the duplicated instructions from the 'true' block.
444 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
445 Dups[i]->eraseFromParent();
449 // Predicate the 'true' block after removing its branch.
450 TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
451 PredicateBlock(BBI.TrueBB, BBI.Cond);
453 // Add a conditional branch to 'true' successor if needed.
454 if (TrueNeedCBr && TrueBBI.ClobbersPred &&
455 isNextBlock(BBI.TrueBB, *BBI.TrueBB->succ_begin()))
458 TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL, BBI.Cond);
460 // Predicate the 'false' block.
461 std::vector<MachineOperand> NewCond(BBI.Cond);
462 TII->ReverseBranchCondition(NewCond);
463 PredicateBlock(BBI.FalseBB, NewCond, true);
465 // Add a conditional branch to 'false' successor if needed.
466 if (FalseNeedCBr && !TrueBBI.ClobbersPred &&
467 isNextBlock(BBI.FalseBB, *BBI.FalseBB->succ_begin()))
468 FalseNeedCBr = false;
470 TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,NewCond);
472 // Merge the 'true' and 'false' blocks by copying the instructions
473 // from the 'false' block to the 'true' block. That is, unless the true
474 // block would clobber the predicate, in that case, do the opposite.
476 if (!TrueBBI.ClobbersPred) {
477 MergeBlocks(TrueBBI, FalseBBI);
480 MergeBlocks(FalseBBI, TrueBBI);
484 // Remove the conditional branch from entry to the blocks.
485 BBI.Size -= TII->RemoveBranch(*BBI.BB);
487 // Merge the combined block into the entry of the diamond if the entry
488 // block is its only predecessor. Otherwise, insert an unconditional
489 // branch from entry to the if-converted block.
490 if (CvtBBI->BB->pred_size() == 1) {
491 BBI.BB->removeSuccessor(CvtBBI->BB);
492 MergeBlocks(BBI, *CvtBBI);
495 std::vector<MachineOperand> NoCond;
496 TII->InsertBranch(*BBI.BB, CvtBBI->BB, NULL, NoCond);
499 // If the if-converted block fallthrough into the tail block, then
500 // fold the tail block in as well.
501 if (BBI.TailBB && CvtBBI->BB->succ_size() == 1) {
502 CvtBBI->Size -= TII->RemoveBranch(*CvtBBI->BB);
503 CvtBBI->BB->removeSuccessor(BBI.TailBB);
504 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
505 MergeBlocks(*CvtBBI, TailBBI);
506 TailBBI.Kind = ICDead;
509 // Update block info.
510 TrueBBI.Kind = ICDead;
511 FalseBBI.Kind = ICDead;
513 // FIXME: Must maintain LiveIns.
518 /// PredicateBlock - Predicate every instruction in the block with the specified
519 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
520 void IfConverter::PredicateBlock(MachineBasicBlock *BB,
521 std::vector<MachineOperand> &Cond,
523 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
525 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
527 if (!TII->PredicateInstruction(&*I, Cond)) {
528 cerr << "Unable to predication " << *I << "!\n";
534 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
536 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
537 ToBBI.BB->splice(ToBBI.BB->end(),
538 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
539 TransferPreds(ToBBI.BB, FromBBI.BB);
540 TransferSuccs(ToBBI.BB, FromBBI.BB);
541 ToBBI.Size += FromBBI.Size;