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 "ifcvt"
15 #include "llvm/Function.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/Statistic.h"
29 // Hidden options for help debugging.
30 cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31 cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32 cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33 cl::opt<bool> DisableSimple("disable-ifcvt-simple",
34 cl::init(false), cl::Hidden);
35 cl::opt<bool> DisableSimpleFalse("disable-ifcvt-simple-false",
36 cl::init(false), cl::Hidden);
37 cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
38 cl::init(false), cl::Hidden);
39 cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
40 cl::init(false), cl::Hidden);
43 STATISTIC(NumSimple, "Number of simple if-conversions performed");
44 STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
45 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
46 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
47 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
50 class IfConverter : public MachineFunctionPass {
52 ICNotAnalyzed, // BB has not been analyzed.
53 ICReAnalyze, // BB must be re-analyzed.
54 ICNotClassfied, // BB data valid, but not classified.
55 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
56 ICSimpleFalse, // Same as ICSimple, but on the false path.
57 ICTriangle, // BB is entry of a triangle sub-CFG.
58 ICDiamond, // BB is entry of a diamond sub-CFG.
59 ICChild, // BB is part of the sub-CFG that'll be predicated.
60 ICDead // BB cannot be if-converted again.
63 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
64 /// if-conversion feasibility analysis. This includes results from
65 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
66 /// classification, and common tail block of its successors (if it's a
67 /// diamond shape), its size, whether it's predicable, and whether any
68 /// instruction can clobber the 'would-be' predicate.
70 /// Kind - Type of block. See BBICKind.
71 /// NonPredSize - Number of non-predicated instructions.
72 /// IsAnalyzable - True if AnalyzeBranch() returns false.
73 /// ModifyPredicate - True if BB would modify the predicate (e.g. has
75 /// BB - Corresponding MachineBasicBlock.
76 /// TrueBB / FalseBB- See AnalyzeBranch().
77 /// BrCond - Conditions for end of block conditional branches.
78 /// Predicate - Predicate used in the BB.
85 MachineBasicBlock *BB;
86 MachineBasicBlock *TrueBB;
87 MachineBasicBlock *FalseBB;
88 MachineBasicBlock *TailBB;
89 std::vector<MachineOperand> BrCond;
90 std::vector<MachineOperand> Predicate;
91 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
92 IsAnalyzable(false), hasFallThrough(false),
93 ModifyPredicate(false),
94 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
97 /// Roots - Basic blocks that do not have successors. These are the starting
98 /// points of Graph traversal.
99 std::vector<MachineBasicBlock*> Roots;
101 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
102 /// basic block number.
103 std::vector<BBInfo> BBAnalysis;
105 const TargetLowering *TLI;
106 const TargetInstrInfo *TII;
110 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
112 virtual bool runOnMachineFunction(MachineFunction &MF);
113 virtual const char *getPassName() const { return "If converter"; }
116 bool ReverseBranchCondition(BBInfo &BBI);
117 bool ValidSimple(BBInfo &TrueBBI) const;
118 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
119 bool FalseBranch = false) const;
120 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
121 void ScanInstructions(BBInfo &BBI);
122 void AnalyzeBlock(MachineBasicBlock *BB);
123 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
124 bool isTriangle = false, bool RevBranch = false);
125 bool AttemptRestructuring(BBInfo &BBI);
126 bool AnalyzeBlocks(MachineFunction &MF,
127 std::vector<BBInfo*> &Candidates);
128 void ReTryPreds(MachineBasicBlock *BB);
129 void RemoveExtraEdges(BBInfo &BBI);
130 bool IfConvertSimple(BBInfo &BBI);
131 bool IfConvertTriangle(BBInfo &BBI);
132 bool IfConvertDiamond(BBInfo &BBI);
133 void PredicateBlock(BBInfo &BBI,
134 std::vector<MachineOperand> &Cond,
135 bool IgnoreTerm = false);
136 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
138 // blockAlwaysFallThrough - Block ends without a terminator.
139 bool blockAlwaysFallThrough(BBInfo &BBI) const {
140 return BBI.IsAnalyzable && BBI.TrueBB == NULL;
143 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
144 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
145 // Favor diamond over triangle, etc.
146 return (unsigned)C1->Kind < (unsigned)C2->Kind;
149 char IfConverter::ID = 0;
152 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
154 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
155 TLI = MF.getTarget().getTargetLowering();
156 TII = MF.getTarget().getInstrInfo();
157 if (!TII) return false;
159 static int FnNum = -1;
160 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
161 << MF.getFunction()->getName() << "\'";
163 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
164 DOUT << " skipped\n";
170 BBAnalysis.resize(MF.getNumBlockIDs());
172 // Look for root nodes, i.e. blocks without successors.
173 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
174 if (I->succ_size() == 0)
177 std::vector<BBInfo*> Candidates;
179 while (IfCvtLimit == -1 || (int)NumIfConvBBs < IfCvtLimit) {
180 // Do an intial analysis for each basic block and finding all the potential
181 // candidates to perform if-convesion.
182 bool Change = AnalyzeBlocks(MF, Candidates);
183 while (!Candidates.empty()) {
184 BBInfo &BBI = *Candidates.back();
185 Candidates.pop_back();
189 default: assert(false && "Unexpected!");
192 // One or more of 'children' have been modified, abort!
194 // Block has been already been if-converted, abort!
197 case ICSimpleFalse: {
198 bool isRev = BBI.Kind == ICSimpleFalse;
199 if ((isRev && DisableSimpleFalse) || (!isRev && DisableSimple)) break;
200 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
201 << "): BB#" << BBI.BB->getNumber() << " ("
202 << ((BBI.Kind == ICSimpleFalse)
203 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
204 RetVal = IfConvertSimple(BBI);
205 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
207 if (isRev) NumSimpleRev++;
212 if (DisableTriangle) break;
213 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " (T:"
214 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
216 RetVal = IfConvertTriangle(BBI);
217 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
218 if (RetVal) NumTriangle++;
221 if (DisableDiamond) break;
222 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
223 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
225 DOUT << "," << BBI.TailBB->getNumber() ;
227 RetVal = IfConvertDiamond(BBI);
228 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
229 if (RetVal) NumDiamonds++;
234 if (IfCvtLimit != -1 && (int)NumIfConvBBs > IfCvtLimit)
240 MadeChange |= Change;
249 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
250 MachineBasicBlock *TrueBB) {
251 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
252 E = BB->succ_end(); SI != E; ++SI) {
253 MachineBasicBlock *SuccBB = *SI;
254 if (SuccBB != TrueBB)
260 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
261 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
262 TII->RemoveBranch(*BBI.BB);
263 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
264 std::swap(BBI.TrueBB, BBI.FalseBB);
270 /// ValidSimple - Returns true if the 'true' block (along with its
271 /// predecessor) forms a valid simple shape for ifcvt.
272 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
273 return !blockAlwaysFallThrough(TrueBBI) &&
274 TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
277 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
278 /// with their common predecessor) forms a valid triangle shape for ifcvt.
279 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
280 bool FalseBranch) const {
281 if (TrueBBI.BB->pred_size() != 1)
284 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
285 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
286 MachineFunction::iterator I = TrueBBI.BB;
287 if (++I == TrueBBI.BB->getParent()->end())
291 return TExit && TExit == FalseBBI.BB;
294 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
295 /// with their common predecessor) forms a valid diamond shape for ifcvt.
296 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
297 // FIXME: Also look for fallthrough
298 return (TrueBBI.TrueBB == FalseBBI.TrueBB &&
299 TrueBBI.BB->pred_size() == 1 &&
300 FalseBBI.BB->pred_size() == 1 &&
301 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
304 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
305 /// the specified block. Record its successors and whether it looks like an
306 /// if-conversion candidate.
307 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
308 BBInfo &BBI = BBAnalysis[BB->getNumber()];
310 if (BBI.Kind == ICReAnalyze) {
312 BBI.TrueBB = BBI.FalseBB = NULL;
314 if (BBI.Kind != ICNotAnalyzed)
315 return; // Already analyzed.
317 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
320 // Look for 'root' of a simple (non-nested) triangle or diamond.
321 BBI.Kind = ICNotClassfied;
323 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
324 BBI.hasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
325 // Unanalyable or ends with fallthrough or unconditional branch.
326 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
328 // Do not ifcvt if either path is a back edge to the entry block.
329 if (BBI.TrueBB == BB || BBI.FalseBB == BB)
332 AnalyzeBlock(BBI.TrueBB);
333 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
335 // No false branch. This BB must end with a conditional branch and a
338 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
339 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
341 AnalyzeBlock(BBI.FalseBB);
342 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
344 // If both paths are dead, then forget about it.
345 if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
350 // Look for more opportunities to if-convert a triangle. Try to restructure
351 // the CFG to form a triangle with the 'false' path.
352 std::vector<MachineOperand> RevCond(BBI.BrCond);
353 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
355 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
356 !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
357 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
358 FeasibilityAnalysis(FalseBBI, RevCond)) {
366 // Note TailBB can be empty.
367 BBI.Kind = ICDiamond;
368 TrueBBI.Kind = FalseBBI.Kind = ICChild;
369 BBI.TailBB = TrueBBI.TrueBB;
371 // FIXME: Consider duplicating if BB is small.
372 if (ValidTriangle(TrueBBI, FalseBBI) &&
373 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
381 BBI.Kind = ICTriangle;
382 TrueBBI.Kind = ICChild;
383 } else if (ValidSimple(TrueBBI) &&
384 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
385 // Simple (split, no rejoin):
393 TrueBBI.Kind = ICChild;
394 } else if (CanRevCond) {
395 // Try the other path...
396 if (ValidTriangle(FalseBBI, TrueBBI) &&
397 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
398 // Reverse 'true' and 'false' paths.
399 ReverseBranchCondition(BBI);
400 BBI.Kind = ICTriangle;
401 FalseBBI.Kind = ICChild;
402 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
403 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
404 ReverseBranchCondition(FalseBBI);
405 ReverseBranchCondition(BBI);
406 BBI.Kind = ICTriangle;
407 FalseBBI.Kind = ICChild;
408 } else if (ValidSimple(FalseBBI) &&
409 FeasibilityAnalysis(FalseBBI, RevCond)) {
410 BBI.Kind = ICSimpleFalse;
411 FalseBBI.Kind = ICChild;
418 /// FeasibilityAnalysis - Determine if the block is predicable. In most
419 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
420 /// Also checks if the block contains any instruction which can clobber a
421 /// predicate (e.g. condition code register). If so, the block is not
422 /// predicable unless it's the last instruction.
423 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
424 std::vector<MachineOperand> &Pred,
425 bool isTriangle, bool RevBranch) {
426 // If the block is dead, or it is going to be the entry block of a sub-CFG
427 // that will be if-converted, then it cannot be predicated.
428 if (BBI.Kind != ICNotAnalyzed &&
429 BBI.Kind != ICNotClassfied &&
433 // Check predication threshold.
434 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
437 // If it is already predicated, check if its predicate subsumes the new
439 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
442 bool SeenPredMod = false;
443 bool SeenCondBr = false;
444 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
446 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
448 // Predicate modification instruction should end the block (except for
449 // already predicated instructions and end of block branches).
450 if (!TII->isPredicated(I)) {
451 // This is the 'true' block of a triangle, i.e. its 'true' block is
452 // the same as the 'false' block of the entry. So false positive
454 if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
455 (TID->Flags & M_BRANCH_FLAG) != 0 &&
456 (TID->Flags & M_BARRIER_FLAG) == 0) {
457 // This is the first conditional branch, test predicate subsumsion.
458 std::vector<MachineOperand> RevPred(Pred);
459 std::vector<MachineOperand> Cond(BBI.BrCond);
461 if (TII->ReverseBranchCondition(Cond))
464 if (TII->ReverseBranchCondition(RevPred) ||
465 !TII->SubsumesPredicate(Cond, RevPred))
468 continue; // Conditional branches is not predicable.
474 if (TID->Flags & M_CLOBBERS_PRED) {
475 BBI.ModifyPredicate = true;
479 if (!I->isPredicable())
486 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
487 /// expose more if-conversion opportunities. e.g.
509 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
513 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
514 /// candidates. It returns true if any CFG restructuring is done to expose more
515 /// if-conversion opportunities.
516 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
517 std::vector<BBInfo*> &Candidates) {
519 std::set<MachineBasicBlock*> Visited;
520 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
521 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
522 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
523 MachineBasicBlock *BB = *I;
525 BBInfo &BBI = BBAnalysis[BB->getNumber()];
531 Candidates.push_back(&BBI);
534 Change |= AttemptRestructuring(BBI);
540 // Sort to favor more complex ifcvt scheme.
541 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
546 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
547 /// that all the intervening blocks are empty (given BB can fall through to its
549 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
550 MachineFunction::iterator I = BB;
551 MachineFunction::iterator TI = ToBB;
552 MachineFunction::iterator E = BB->getParent()->end();
554 if (I == E || !I->empty())
559 /// getNextBlock - Returns the next block in the function blocks ordering. If
560 /// it is the end, returns NULL.
561 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
562 MachineFunction::iterator I = BB;
563 MachineFunction::iterator E = BB->getParent()->end();
569 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
570 /// to determine if it can be if-converted.
571 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
572 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
573 E = BB->pred_end(); PI != E; ++PI) {
574 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
575 if (PBBI.Kind == ICNotClassfied)
576 PBBI.Kind = ICReAnalyze;
580 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
582 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
583 const TargetInstrInfo *TII) {
584 std::vector<MachineOperand> NoCond;
585 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
588 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
590 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
591 MachineBasicBlock *TBB = NULL, *FBB = NULL;
592 std::vector<MachineOperand> Cond;
593 bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
594 bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
595 if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
596 if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
597 (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
598 BBI.BB->removeSuccessor(BBI.TrueBB);
599 if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
600 if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
601 (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
602 BBI.BB->removeSuccessor(BBI.FalseBB);
605 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
607 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
608 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
609 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
610 BBInfo *CvtBBI = &TrueBBI;
611 BBInfo *NextBBI = &FalseBBI;
613 std::vector<MachineOperand> Cond(BBI.BrCond);
614 if (BBI.Kind == ICSimpleFalse) {
615 std::swap(CvtBBI, NextBBI);
616 TII->ReverseBranchCondition(Cond);
619 PredicateBlock(*CvtBBI, Cond);
621 // Merge converted block into entry block.
622 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
623 MergeBlocks(BBI, *CvtBBI);
625 bool IterIfcvt = true;
626 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
627 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
628 BBI.hasFallThrough = false;
629 // Now ifcvt'd block will look like this:
636 // We cannot further ifcvt this block because the unconditional branch
637 // will have to be predicated on the new condition, that will not be
638 // available if cmp executes.
642 RemoveExtraEdges(BBI);
644 // Update block info. BB can be iteratively if-converted.
646 BBI.Kind = ICReAnalyze;
650 CvtBBI->Kind = ICDead;
652 // FIXME: Must maintain LiveIns.
656 /// IfConvertTriangle - If convert a triangle sub-CFG.
658 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
659 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
661 // Predicate the 'true' block after removing its branch.
662 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
663 PredicateBlock(TrueBBI, BBI.BrCond);
665 // If 'true' block has a 'false' successor, add an exit branch to it.
666 bool HasEarlyExit = TrueBBI.FalseBB != NULL;
668 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
669 if (TII->ReverseBranchCondition(RevCond))
670 assert(false && "Unable to reverse branch condition!");
671 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
674 // Now merge the entry of the triangle with the true block.
675 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
676 MergeBlocks(BBI, TrueBBI);
678 // Merge in the 'false' block if the 'false' block has no other
679 // predecessors. Otherwise, add a unconditional branch from to 'false'.
680 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
681 bool FalseBBDead = false;
682 bool IterIfcvt = true;
683 bool isFallThrough = canFallThroughTo(BBI.BB, FalseBBI.BB);
684 if (!isFallThrough) {
685 // Only merge them if the true block does not fallthrough to the false
686 // block. By not merging them, we make it possible to iteratively
688 if (!HasEarlyExit && FalseBBI.BB->pred_size() == 1) {
689 MergeBlocks(BBI, FalseBBI);
692 InsertUncondBranch(BBI.BB, FalseBBI.BB, TII);
693 TrueBBI.hasFallThrough = false;
695 // Mixed predicated and unpredicated code. This cannot be iteratively
700 RemoveExtraEdges(BBI);
702 // Update block info. BB can be iteratively if-converted.
704 BBI.Kind = ICReAnalyze;
708 TrueBBI.Kind = ICDead;
710 FalseBBI.Kind = ICDead;
712 // FIXME: Must maintain LiveIns.
716 /// IfConvertDiamond - If convert a diamond sub-CFG.
718 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
719 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
720 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
722 SmallVector<MachineInstr*, 2> Dups;
724 // No common merge block. Check if the terminators (e.g. return) are
725 // the same or predicable.
726 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
727 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
728 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
729 if (TT->isIdenticalTo(FT))
730 Dups.push_back(TT); // Will erase these later.
731 else if (!TT->isPredicable() && !FT->isPredicable())
732 return false; // Can't if-convert. Abort!
737 // One of the two pathes have more terminators, make sure they are
739 while (TT != BBI.TrueBB->end()) {
740 if (!TT->isPredicable()) {
741 return false; // Can't if-convert. Abort!
745 while (FT != BBI.FalseBB->end()) {
746 if (!FT->isPredicable()) {
747 return false; // Can't if-convert. Abort!
753 // Remove the duplicated instructions from the 'true' block.
754 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
755 Dups[i]->eraseFromParent();
756 --TrueBBI.NonPredSize;
759 // Merge the 'true' and 'false' blocks by copying the instructions
760 // from the 'false' block to the 'true' block. That is, unless the true
761 // block would clobber the predicate, in that case, do the opposite.
762 BBInfo *BBI1 = &TrueBBI;
763 BBInfo *BBI2 = &FalseBBI;
764 std::vector<MachineOperand> RevCond(BBI.BrCond);
765 TII->ReverseBranchCondition(RevCond);
766 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
767 std::vector<MachineOperand> *Cond2 = &RevCond;
768 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
769 // Either the block fallthrough to another block or it ends with a
770 // return. If it's the former, add a branch to its successor.
771 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
772 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
774 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
775 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
776 NeedBr1 && !NeedBr2)) {
777 std::swap(BBI1, BBI2);
778 std::swap(Cond1, Cond2);
779 std::swap(NeedBr1, NeedBr2);
782 // Predicate the 'true' block after removing its branch.
783 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
784 PredicateBlock(*BBI1, *Cond1);
786 // Add an early exit branch if needed.
788 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
790 // Predicate the 'false' block.
791 PredicateBlock(*BBI2, *Cond2, true);
793 // Add an unconditional branch from 'false' to to 'false' successor if it
794 // will not be the fallthrough block.
795 if (NeedBr2 && !NeedBr1) {
796 // If BBI2 isn't going to be merged in, then the existing fallthrough
797 // or branch is fine.
798 if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
799 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
800 BBI2->hasFallThrough = false;
804 // Keep them as two separate blocks if there is an early exit.
806 MergeBlocks(*BBI1, *BBI2);
808 // Remove the conditional branch from entry to the blocks.
809 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
811 // Merge the combined block into the entry of the diamond.
812 MergeBlocks(BBI, *BBI1);
814 // 'True' and 'false' aren't combined, see if we need to add a unconditional
815 // branch to the 'false' block.
816 if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
817 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
818 BBI1->hasFallThrough = false;
821 // If the if-converted block fallthrough or unconditionally branch into the
822 // tail block, and the tail block does not have other predecessors, then
823 // fold the tail block in as well.
824 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
826 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
827 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
828 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
829 MergeBlocks(*CvtBBI, TailBBI);
830 TailBBI.Kind = ICDead;
833 RemoveExtraEdges(BBI);
835 // Update block info.
837 TrueBBI.Kind = ICDead;
838 FalseBBI.Kind = ICDead;
840 // FIXME: Must maintain LiveIns.
844 /// PredicateBlock - Predicate every instruction in the block with the specified
845 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
846 void IfConverter::PredicateBlock(BBInfo &BBI,
847 std::vector<MachineOperand> &Cond,
849 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
851 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
853 if (TII->isPredicated(I))
855 if (!TII->PredicateInstruction(I, Cond)) {
856 cerr << "Unable to predicate " << *I << "!\n";
862 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
867 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
869 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
870 ToBBI.BB->splice(ToBBI.BB->end(),
871 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
873 // Redirect all branches to FromBB to ToBB.
874 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
875 FromBBI.BB->pred_end());
876 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
877 MachineBasicBlock *Pred = Preds[i];
878 if (Pred == ToBBI.BB)
880 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
883 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
884 FromBBI.BB->succ_end());
885 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
886 MachineBasicBlock *FallThrough = FromBBI.hasFallThrough ? NBB : NULL;
888 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
889 MachineBasicBlock *Succ = Succs[i];
890 // Fallthrough edge can't be transferred.
891 if (Succ == FallThrough)
893 FromBBI.BB->removeSuccessor(Succ);
894 if (!ToBBI.BB->isSuccessor(Succ))
895 ToBBI.BB->addSuccessor(Succ);
898 // Now FromBBI always fall through to the next block!
900 FromBBI.BB->addSuccessor(NBB);
902 ToBBI.NonPredSize += FromBBI.NonPredSize;
903 FromBBI.NonPredSize = 0;
905 ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
906 ToBBI.hasFallThrough = FromBBI.hasFallThrough;
908 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
909 std::back_inserter(ToBBI.Predicate));
910 FromBBI.Predicate.clear();