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 bool IfConvertSimple(BBInfo &BBI);
130 bool IfConvertTriangle(BBInfo &BBI);
131 bool IfConvertDiamond(BBInfo &BBI);
132 void PredicateBlock(BBInfo &BBI,
133 std::vector<MachineOperand> &Cond,
134 bool IgnoreTerm = false);
135 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
137 // blockAlwaysFallThrough - Block ends without a terminator.
138 bool blockAlwaysFallThrough(BBInfo &BBI) const {
139 return BBI.IsAnalyzable && BBI.TrueBB == NULL;
142 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
143 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
144 // Favor diamond over triangle, etc.
145 return (unsigned)C1->Kind < (unsigned)C2->Kind;
148 char IfConverter::ID = 0;
151 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
153 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
154 TLI = MF.getTarget().getTargetLowering();
155 TII = MF.getTarget().getInstrInfo();
156 if (!TII) return false;
158 static int FnNum = -1;
159 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
160 << MF.getFunction()->getName() << "\'";
162 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
163 DOUT << " skipped\n";
169 BBAnalysis.resize(MF.getNumBlockIDs());
171 // Look for root nodes, i.e. blocks without successors.
172 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
173 if (I->succ_size() == 0)
176 std::vector<BBInfo*> Candidates;
178 while (IfCvtLimit == -1 || (int)NumIfConvBBs < IfCvtLimit) {
179 // Do an intial analysis for each basic block and finding all the potential
180 // candidates to perform if-convesion.
181 bool Change = AnalyzeBlocks(MF, Candidates);
182 while (!Candidates.empty()) {
183 BBInfo &BBI = *Candidates.back();
184 Candidates.pop_back();
188 default: assert(false && "Unexpected!");
191 // One or more of 'children' have been modified, abort!
193 // Block has been already been if-converted, abort!
196 case ICSimpleFalse: {
197 bool isRev = BBI.Kind == ICSimpleFalse;
198 if ((isRev && DisableSimpleFalse) || (!isRev && DisableSimple)) break;
199 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
200 << "): BB#" << BBI.BB->getNumber() << " ("
201 << ((BBI.Kind == ICSimpleFalse)
202 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
203 RetVal = IfConvertSimple(BBI);
204 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
206 if (isRev) NumSimpleRev++;
211 if (DisableTriangle) break;
212 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " (T:"
213 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
215 RetVal = IfConvertTriangle(BBI);
216 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
217 if (RetVal) NumTriangle++;
220 if (DisableDiamond) break;
221 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
222 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
224 DOUT << "," << BBI.TailBB->getNumber() ;
226 RetVal = IfConvertDiamond(BBI);
227 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
228 if (RetVal) NumDiamonds++;
233 if (IfCvtLimit != -1 && (int)NumIfConvBBs > IfCvtLimit)
239 MadeChange |= Change;
248 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
249 MachineBasicBlock *TrueBB) {
250 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
251 E = BB->succ_end(); SI != E; ++SI) {
252 MachineBasicBlock *SuccBB = *SI;
253 if (SuccBB != TrueBB)
259 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
260 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
261 TII->RemoveBranch(*BBI.BB);
262 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
263 std::swap(BBI.TrueBB, BBI.FalseBB);
269 /// ValidSimple - Returns true if the 'true' block (along with its
270 /// predecessor) forms a valid simple shape for ifcvt.
271 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
272 return !blockAlwaysFallThrough(TrueBBI) &&
273 TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
276 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
277 /// with their common predecessor) forms a valid triangle shape for ifcvt.
278 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
279 bool FalseBranch) const {
280 if (TrueBBI.BB->pred_size() != 1)
283 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
284 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
285 MachineFunction::iterator I = TrueBBI.BB;
286 if (++I == TrueBBI.BB->getParent()->end())
290 return TExit && TExit == FalseBBI.BB;
293 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
294 /// with their common predecessor) forms a valid diamond shape for ifcvt.
295 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
296 // FIXME: Also look for fallthrough
297 return (TrueBBI.TrueBB == FalseBBI.TrueBB &&
298 TrueBBI.BB->pred_size() == 1 &&
299 FalseBBI.BB->pred_size() == 1 &&
300 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
303 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
304 /// the specified block. Record its successors and whether it looks like an
305 /// if-conversion candidate.
306 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
307 BBInfo &BBI = BBAnalysis[BB->getNumber()];
309 if (BBI.Kind == ICReAnalyze) {
311 BBI.TrueBB = BBI.FalseBB = NULL;
313 if (BBI.Kind != ICNotAnalyzed)
314 return; // Already analyzed.
316 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
319 // Look for 'root' of a simple (non-nested) triangle or diamond.
320 BBI.Kind = ICNotClassfied;
322 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
323 BBI.hasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
324 // Unanalyable or ends with fallthrough or unconditional branch.
325 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
327 // Do not ifcvt if either path is a back edge to the entry block.
328 if (BBI.TrueBB == BB || BBI.FalseBB == BB)
331 AnalyzeBlock(BBI.TrueBB);
332 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
334 // No false branch. This BB must end with a conditional branch and a
337 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
338 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
340 AnalyzeBlock(BBI.FalseBB);
341 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
343 // If both paths are dead, then forget about it.
344 if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
349 // Look for more opportunities to if-convert a triangle. Try to restructure
350 // the CFG to form a triangle with the 'false' path.
351 std::vector<MachineOperand> RevCond(BBI.BrCond);
352 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
354 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
355 !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
356 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
357 FeasibilityAnalysis(FalseBBI, RevCond)) {
365 // Note TailBB can be empty.
366 BBI.Kind = ICDiamond;
367 TrueBBI.Kind = FalseBBI.Kind = ICChild;
368 BBI.TailBB = TrueBBI.TrueBB;
370 // FIXME: Consider duplicating if BB is small.
371 if (ValidTriangle(TrueBBI, FalseBBI) &&
372 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
380 BBI.Kind = ICTriangle;
381 TrueBBI.Kind = ICChild;
382 } else if (ValidSimple(TrueBBI) &&
383 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
384 // Simple (split, no rejoin):
392 TrueBBI.Kind = ICChild;
393 } else if (CanRevCond) {
394 // Try the other path...
395 if (ValidTriangle(FalseBBI, TrueBBI) &&
396 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
397 // Reverse 'true' and 'false' paths.
398 ReverseBranchCondition(BBI);
399 BBI.Kind = ICTriangle;
400 FalseBBI.Kind = ICChild;
401 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
402 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
403 ReverseBranchCondition(FalseBBI);
404 ReverseBranchCondition(BBI);
405 BBI.Kind = ICTriangle;
406 FalseBBI.Kind = ICChild;
407 } else if (ValidSimple(FalseBBI) &&
408 FeasibilityAnalysis(FalseBBI, RevCond)) {
409 BBI.Kind = ICSimpleFalse;
410 FalseBBI.Kind = ICChild;
417 /// FeasibilityAnalysis - Determine if the block is predicable. In most
418 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
419 /// Also checks if the block contains any instruction which can clobber a
420 /// predicate (e.g. condition code register). If so, the block is not
421 /// predicable unless it's the last instruction.
422 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
423 std::vector<MachineOperand> &Pred,
424 bool isTriangle, bool RevBranch) {
425 // If the block is dead, or it is going to be the entry block of a sub-CFG
426 // that will be if-converted, then it cannot be predicated.
427 if (BBI.Kind != ICNotAnalyzed &&
428 BBI.Kind != ICNotClassfied &&
432 // Check predication threshold.
433 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
436 // If it is already predicated, check if its predicate subsumes the new
438 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
441 bool SeenPredMod = false;
442 bool SeenCondBr = false;
443 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
445 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
447 // Predicate modification instruction should end the block (except for
448 // already predicated instructions and end of block branches).
449 if (!TII->isPredicated(I)) {
450 // This is the 'true' block of a triangle, i.e. its 'true' block is
451 // the same as the 'false' block of the entry. So false positive
453 if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
454 (TID->Flags & M_BRANCH_FLAG) != 0 &&
455 (TID->Flags & M_BARRIER_FLAG) == 0) {
456 // This is the first conditional branch, test predicate subsumsion.
457 std::vector<MachineOperand> RevPred(Pred);
458 std::vector<MachineOperand> Cond(BBI.BrCond);
460 if (TII->ReverseBranchCondition(Cond))
463 if (TII->ReverseBranchCondition(RevPred) ||
464 !TII->SubsumesPredicate(Cond, RevPred))
467 continue; // Conditional branches is not predicable.
473 if (TID->Flags & M_CLOBBERS_PRED) {
474 BBI.ModifyPredicate = true;
478 if (!I->isPredicable())
485 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
486 /// expose more if-conversion opportunities. e.g.
508 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
512 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
513 /// candidates. It returns true if any CFG restructuring is done to expose more
514 /// if-conversion opportunities.
515 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
516 std::vector<BBInfo*> &Candidates) {
518 std::set<MachineBasicBlock*> Visited;
519 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
520 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
521 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
522 MachineBasicBlock *BB = *I;
524 BBInfo &BBI = BBAnalysis[BB->getNumber()];
530 Candidates.push_back(&BBI);
533 Change |= AttemptRestructuring(BBI);
539 // Sort to favor more complex ifcvt scheme.
540 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
545 /// isNextBlock - Returns true either if ToBB the next block after BB or
546 /// that all the intervening blocks are empty.
547 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
548 MachineFunction::iterator I = BB;
549 MachineFunction::iterator TI = ToBB;
550 MachineFunction::iterator E = BB->getParent()->end();
552 if (I == E || !I->empty())
557 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
558 /// to determine if it can be if-converted.
559 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
560 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
561 E = BB->pred_end(); PI != E; ++PI) {
562 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
563 PBBI.Kind = ICReAnalyze;
567 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
569 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
570 const TargetInstrInfo *TII) {
571 std::vector<MachineOperand> NoCond;
572 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
575 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
577 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
578 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
579 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
580 BBInfo *CvtBBI = &TrueBBI;
581 BBInfo *NextBBI = &FalseBBI;
583 std::vector<MachineOperand> Cond(BBI.BrCond);
584 if (BBI.Kind == ICSimpleFalse) {
585 std::swap(CvtBBI, NextBBI);
586 TII->ReverseBranchCondition(Cond);
589 PredicateBlock(*CvtBBI, Cond);
591 // Merge converted block into entry block. Also add an unconditional branch
592 // to the 'false' branch.
593 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
594 MergeBlocks(BBI, *CvtBBI);
595 BBI.BB->removeSuccessor(CvtBBI->BB);
597 bool IterIfcvt = true;
598 if (!isNextBlock(BBI.BB, NextBBI->BB)) {
599 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
600 BBI.hasFallThrough = false;
601 // Now ifcvt'd block will look like this:
608 // We cannot further ifcvt this block because the unconditional branch
609 // will have to be predicated on the new condition, that will not be
610 // available if cmp executes.
614 // Update block info. BB can be iteratively if-converted.
616 BBI.Kind = ICReAnalyze;
620 CvtBBI->Kind = ICDead;
622 // FIXME: Must maintain LiveIns.
626 /// IfConvertTriangle - If convert a triangle sub-CFG.
628 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
629 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
631 // Predicate the 'true' block after removing its branch.
632 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
633 PredicateBlock(TrueBBI, BBI.BrCond);
635 // If 'true' block has a 'false' successor, add an exit branch to it.
636 bool HasEarlyExit = TrueBBI.FalseBB != NULL;
638 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
639 if (TII->ReverseBranchCondition(RevCond))
640 assert(false && "Unable to reverse branch condition!");
641 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
644 // Now merge the entry of the triangle with the true block.
645 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
646 MergeBlocks(BBI, TrueBBI);
648 // Merge in the 'false' block if the 'false' block has no other
649 // predecessors. Otherwise, add a unconditional branch from to 'false'.
650 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
651 bool FalseBBDead = false;
652 bool IterIfcvt = true;
653 bool isFallThrough = isNextBlock(BBI.BB, FalseBBI.BB);
654 if (!isFallThrough) {
655 // Only merge them if the true block does not fallthrough to the false
656 // block. By not merging them, we make it possible to iteratively
658 if (!HasEarlyExit && FalseBBI.BB->pred_size() == 1) {
659 MergeBlocks(BBI, FalseBBI);
662 InsertUncondBranch(BBI.BB, FalseBBI.BB, TII);
663 TrueBBI.hasFallThrough = false;
665 // Mixed predicated and unpredicated code. This cannot be iteratively
670 // Remove entry to false edge if false block is merged in as well.
672 BBI.BB->removeSuccessor(FalseBBI.BB);
674 // Update block info. BB can be iteratively if-converted.
676 BBI.Kind = ICReAnalyze;
680 TrueBBI.Kind = ICDead;
682 FalseBBI.Kind = ICDead;
684 // FIXME: Must maintain LiveIns.
688 /// IfConvertDiamond - If convert a diamond sub-CFG.
690 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
691 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
692 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
694 SmallVector<MachineInstr*, 2> Dups;
696 // No common merge block. Check if the terminators (e.g. return) are
697 // the same or predicable.
698 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
699 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
700 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
701 if (TT->isIdenticalTo(FT))
702 Dups.push_back(TT); // Will erase these later.
703 else if (!TT->isPredicable() && !FT->isPredicable())
704 return false; // Can't if-convert. Abort!
709 // One of the two pathes have more terminators, make sure they are
711 while (TT != BBI.TrueBB->end()) {
712 if (!TT->isPredicable()) {
713 return false; // Can't if-convert. Abort!
717 while (FT != BBI.FalseBB->end()) {
718 if (!FT->isPredicable()) {
719 return false; // Can't if-convert. Abort!
725 // Remove the duplicated instructions from the 'true' block.
726 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
727 Dups[i]->eraseFromParent();
728 --TrueBBI.NonPredSize;
731 // Merge the 'true' and 'false' blocks by copying the instructions
732 // from the 'false' block to the 'true' block. That is, unless the true
733 // block would clobber the predicate, in that case, do the opposite.
734 BBInfo *BBI1 = &TrueBBI;
735 BBInfo *BBI2 = &FalseBBI;
736 std::vector<MachineOperand> RevCond(BBI.BrCond);
737 TII->ReverseBranchCondition(RevCond);
738 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
739 std::vector<MachineOperand> *Cond2 = &RevCond;
740 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
741 // Either the block fallthrough to another block or it ends with a
742 // return. If it's the former, add a branch to its successor.
743 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
744 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
746 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
747 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
748 NeedBr1 && !NeedBr2)) {
749 std::swap(BBI1, BBI2);
750 std::swap(Cond1, Cond2);
751 std::swap(NeedBr1, NeedBr2);
754 // Predicate the 'true' block after removing its branch.
755 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
756 PredicateBlock(*BBI1, *Cond1);
758 // Add an early exit branch if needed.
760 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
762 // Predicate the 'false' block.
763 PredicateBlock(*BBI2, *Cond2, true);
765 // Add an unconditional branch from 'false' to to 'false' successor if it
766 // will not be the fallthrough block.
767 if (NeedBr2 && !NeedBr1) {
768 // If BBI2 isn't going to be merged in, then the existing fallthrough
769 // or branch is fine.
770 if (!isNextBlock(BBI.BB, *BBI2->BB->succ_begin())) {
771 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
772 BBI2->hasFallThrough = false;
776 // Keep them as two separate blocks if there is an early exit.
778 MergeBlocks(*BBI1, *BBI2);
780 // Remove the conditional branch from entry to the blocks.
781 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
783 // Merge the combined block into the entry of the diamond.
784 MergeBlocks(BBI, *BBI1);
786 // 'True' and 'false' aren't combined, see if we need to add a unconditional
787 // branch to the 'false' block.
788 if (NeedBr1 && !isNextBlock(BBI.BB, BBI2->BB)) {
789 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
790 BBI1->hasFallThrough = false;
793 // If the if-converted block fallthrough or unconditionally branch into the
794 // tail block, and the tail block does not have other predecessors, then
795 // fold the tail block in as well.
796 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
798 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
799 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
800 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
801 MergeBlocks(*CvtBBI, TailBBI);
802 TailBBI.Kind = ICDead;
805 // Update block info.
807 TrueBBI.Kind = ICDead;
808 FalseBBI.Kind = ICDead;
810 // FIXME: Must maintain LiveIns.
814 /// PredicateBlock - Predicate every instruction in the block with the specified
815 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
816 void IfConverter::PredicateBlock(BBInfo &BBI,
817 std::vector<MachineOperand> &Cond,
819 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
821 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
823 if (TII->isPredicated(I))
825 if (!TII->PredicateInstruction(I, Cond)) {
826 cerr << "Unable to predicate " << *I << "!\n";
832 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
837 static MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
838 MachineFunction::iterator I = BB;
839 MachineFunction::iterator E = BB->getParent()->end();
845 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
847 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
848 ToBBI.BB->splice(ToBBI.BB->end(),
849 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
851 // Redirect all branches to FromBB to ToBB.
852 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
853 FromBBI.BB->pred_end());
854 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
855 MachineBasicBlock *Pred = Preds[i];
856 if (Pred == ToBBI.BB)
858 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
861 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
862 FromBBI.BB->succ_end());
863 MachineBasicBlock *FallThrough = FromBBI.hasFallThrough
864 ? getNextBlock(FromBBI.BB) : NULL;
866 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
867 MachineBasicBlock *Succ = Succs[i];
868 if (Succ == FallThrough)
870 FromBBI.BB->removeSuccessor(Succ);
871 if (!ToBBI.BB->isSuccessor(Succ))
872 ToBBI.BB->addSuccessor(Succ);
875 ToBBI.NonPredSize += FromBBI.NonPredSize;
876 FromBBI.NonPredSize = 0;
878 ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
879 ToBBI.hasFallThrough = FromBBI.hasFallThrough;
881 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
882 std::back_inserter(ToBBI.Predicate));
883 FromBBI.Predicate.clear();