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/Debug.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
27 STATISTIC(NumSimple, "Number of simple if-conversions performed");
28 STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
29 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
30 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
31 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
34 class IfConverter : public MachineFunctionPass {
36 ICNotAnalyzed, // BB has not been analyzed.
37 ICReAnalyze, // BB must be re-analyzed.
38 ICNotClassfied, // BB data valid, but not classified.
39 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
40 ICSimpleFalse, // Same as ICSimple, but on the false path.
41 ICTriangle, // BB is entry of a triangle sub-CFG.
42 ICDiamond, // BB is entry of a diamond sub-CFG.
43 ICChild, // BB is part of the sub-CFG that'll be predicated.
44 ICDead // BB has been converted and merged, it's now dead.
47 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
48 /// if-conversion feasibility analysis. This includes results from
49 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
50 /// classification, and common tail block of its successors (if it's a
51 /// diamond shape), its size, whether it's predicable, and whether any
52 /// instruction can clobber the 'would-be' predicate.
54 /// Kind - Type of block. See BBICKind.
55 /// NonPredSize - Number of non-predicated instructions.
56 /// IsAnalyzable - True if AnalyzeBranch() returns false.
57 /// ModifyPredicate - FIXME: Not used right now. True if BB would modify
58 /// the predicate (e.g. has cmp, call, etc.)
59 /// BB - Corresponding MachineBasicBlock.
60 /// TrueBB / FalseBB- See AnalyzeBranch().
61 /// BrCond - Conditions for end of block conditional branches.
62 /// Predicate - Predicate used in the BB.
68 MachineBasicBlock *BB;
69 MachineBasicBlock *TrueBB;
70 MachineBasicBlock *FalseBB;
71 MachineBasicBlock *TailBB;
72 std::vector<MachineOperand> BrCond;
73 std::vector<MachineOperand> Predicate;
74 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
75 IsAnalyzable(false), ModifyPredicate(false),
76 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
79 /// Roots - Basic blocks that do not have successors. These are the starting
80 /// points of Graph traversal.
81 std::vector<MachineBasicBlock*> Roots;
83 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
84 /// basic block number.
85 std::vector<BBInfo> BBAnalysis;
87 const TargetLowering *TLI;
88 const TargetInstrInfo *TII;
92 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
94 virtual bool runOnMachineFunction(MachineFunction &MF);
95 virtual const char *getPassName() const { return "If converter"; }
98 bool ReverseBranchCondition(BBInfo &BBI);
99 void StructuralAnalysis(MachineBasicBlock *BB);
100 bool FeasibilityAnalysis(BBInfo &BBI,
101 std::vector<MachineOperand> &Cond,
102 bool IgnoreTerm = false);
103 bool AttemptRestructuring(BBInfo &BBI);
104 bool AnalyzeBlocks(MachineFunction &MF,
105 std::vector<BBInfo*> &Candidates);
106 void ReTryPreds(MachineBasicBlock *BB);
107 bool IfConvertSimple(BBInfo &BBI);
108 bool IfConvertTriangle(BBInfo &BBI);
109 bool IfConvertDiamond(BBInfo &BBI);
110 void PredicateBlock(BBInfo &BBI,
111 std::vector<MachineOperand> &Cond,
112 bool IgnoreTerm = false);
113 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
115 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
116 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
117 // Favor diamond over triangle, etc.
118 return (unsigned)C1->Kind < (unsigned)C2->Kind;
121 char IfConverter::ID = 0;
124 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
126 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
127 TLI = MF.getTarget().getTargetLowering();
128 TII = MF.getTarget().getInstrInfo();
129 if (!TII) return false;
131 DOUT << "\nIfcvt: function \'" << MF.getFunction()->getName() << "\'\n";
134 BBAnalysis.resize(MF.getNumBlockIDs());
136 // Look for root nodes, i.e. blocks without successors.
137 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
138 if (I->succ_size() == 0)
141 std::vector<BBInfo*> Candidates;
144 // Do an intial analysis for each basic block and finding all the potential
145 // candidates to perform if-convesion.
146 bool Change = AnalyzeBlocks(MF, Candidates);
147 while (!Candidates.empty()) {
148 BBInfo &BBI = *Candidates.back();
149 Candidates.pop_back();
153 default: assert(false && "Unexpected!");
156 // One or more of 'children' have been modified, abort!
158 // Block has been already been if-converted, abort!
162 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
163 << "): BB#" << BBI.BB->getNumber() << " ";
164 RetVal = IfConvertSimple(BBI);
165 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
167 if (BBI.Kind == ICSimple) NumSimple++;
171 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " ";
172 RetVal = IfConvertTriangle(BBI);
173 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
174 if (RetVal) NumTriangle++;
177 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " ";
178 RetVal = IfConvertDiamond(BBI);
179 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
180 if (RetVal) NumDiamonds++;
188 MadeChange |= Change;
197 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
198 MachineBasicBlock *TrueBB) {
199 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
200 E = BB->succ_end(); SI != E; ++SI) {
201 MachineBasicBlock *SuccBB = *SI;
202 if (SuccBB != TrueBB)
208 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
209 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
210 TII->RemoveBranch(*BBI.BB);
211 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
212 std::swap(BBI.TrueBB, BBI.FalseBB);
218 /// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
219 /// the specified block. Record its successors and whether it looks like an
220 /// if-conversion candidate.
221 void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
222 BBInfo &BBI = BBAnalysis[BB->getNumber()];
224 if (BBI.Kind == ICReAnalyze) {
226 BBI.TrueBB = BBI.FalseBB = NULL;
228 if (BBI.Kind != ICNotAnalyzed)
229 return; // Already analyzed.
231 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
234 // Look for 'root' of a simple (non-nested) triangle or diamond.
235 BBI.Kind = ICNotClassfied;
237 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
238 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
240 // Do not ifcvt if either path is a back edge to the entry block.
241 if (BBI.TrueBB == BB || BBI.FalseBB == BB)
244 StructuralAnalysis(BBI.TrueBB);
245 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
247 // No false branch. This BB must end with a conditional branch and a
250 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
251 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
253 StructuralAnalysis(BBI.FalseBB);
254 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
256 // Look for more opportunities to if-convert a triangle. Try to restructure
257 // the CFG to form a triangle with the 'false' path.
258 std::vector<MachineOperand> RevCond(BBI.BrCond);
259 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
260 if (FalseBBI.FalseBB) {
261 if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB)
263 std::vector<MachineOperand> Cond(BBI.BrCond);
265 FalseBBI.TrueBB && FalseBBI.BB->pred_size() == 1 &&
266 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
267 std::vector<MachineOperand> FalseCond(FalseBBI.BrCond);
268 if (FalseBBI.TrueBB == BBI.TrueBB &&
269 TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
270 // Reverse 'true' and 'false' paths.
271 ReverseBranchCondition(BBI);
272 BBI.Kind = ICTriangle;
273 FalseBBI.Kind = ICChild;
274 } else if (FalseBBI.FalseBB == BBI.TrueBB &&
275 !TII->ReverseBranchCondition(FalseCond) &&
276 TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
277 // Reverse 'false' block's 'true' and 'false' paths and then
278 // reverse 'true' and 'false' paths.
279 ReverseBranchCondition(FalseBBI);
280 ReverseBranchCondition(BBI);
281 BBI.Kind = ICTriangle;
282 FalseBBI.Kind = ICChild;
285 } else if (TrueBBI.TrueBB == FalseBBI.TrueBB && CanRevCond &&
286 TrueBBI.BB->pred_size() == 1 &&
287 FalseBBI.BB->pred_size() == 1 &&
288 // Check the 'true' and 'false' blocks if either isn't ended with
289 // a branch. If the block does not fallthrough to another block
290 // then we need to add a branch to its successor.
291 !(TrueBBI.ModifyPredicate &&
292 !TrueBBI.TrueBB && TrueBBI.BB->succ_size()) &&
293 !(FalseBBI.ModifyPredicate &&
294 !FalseBBI.TrueBB && FalseBBI.BB->succ_size()) &&
295 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
296 FeasibilityAnalysis(FalseBBI, RevCond)) {
304 // Note TailBB can be empty.
305 BBI.Kind = ICDiamond;
306 TrueBBI.Kind = FalseBBI.Kind = ICChild;
307 BBI.TailBB = TrueBBI.TrueBB;
309 // FIXME: Consider duplicating if BB is small.
310 bool TryTriangle = TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB &&
311 TrueBBI.BB->pred_size() == 1;
312 bool TrySimple = TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
313 if ((TryTriangle || TrySimple) &&
314 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
323 BBI.Kind = ICTriangle;
324 TrueBBI.Kind = ICChild;
326 // Simple (split, no rejoin):
334 TrueBBI.Kind = ICChild;
336 } else if (FalseBBI.BrCond.size() == 0 && FalseBBI.BB->pred_size() == 1) {
337 // Try the other path...
338 std::vector<MachineOperand> RevCond(BBI.BrCond);
339 if (!TII->ReverseBranchCondition(RevCond) &&
340 FeasibilityAnalysis(FalseBBI, RevCond)) {
341 if (FalseBBI.TrueBB && FalseBBI.TrueBB == BBI.TrueBB &&
342 FalseBBI.BB->pred_size() == 1) {
343 // Reverse 'true' and 'false' paths.
344 ReverseBranchCondition(BBI);
345 BBI.Kind = ICTriangle;
346 FalseBBI.Kind = ICChild;
348 BBI.Kind = ICSimpleFalse;
349 FalseBBI.Kind = ICChild;
357 /// FeasibilityAnalysis - Determine if the block is predicable. In most
358 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
359 /// Also checks if the block contains any instruction which can clobber a
360 /// predicate (e.g. condition code register). If so, the block is not
361 /// predicable unless it's the last instruction. If IgnoreTerm is true then
362 /// all the terminator instructions are skipped.
363 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
364 std::vector<MachineOperand> &Cond,
366 // If the block is dead, or it is going to be the entry block of a sub-CFG
367 // that will be if-converted, then it cannot be predicated.
368 if (BBI.Kind != ICNotAnalyzed &&
369 BBI.Kind != ICNotClassfied &&
373 // Check predication threshold.
374 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
377 // If it is already predicated, check if its predicate subsumes the new
379 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
382 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
384 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
386 // TODO: check if instruction clobbers predicate.
387 if (!I->isPredicable())
394 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
395 /// expose more if-conversion opportunities. e.g.
417 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
421 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
422 /// candidates. It returns true if any CFG restructuring is done to expose more
423 /// if-conversion opportunities.
424 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
425 std::vector<BBInfo*> &Candidates) {
427 std::set<MachineBasicBlock*> Visited;
428 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
429 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
430 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
431 MachineBasicBlock *BB = *I;
432 StructuralAnalysis(BB);
433 BBInfo &BBI = BBAnalysis[BB->getNumber()];
439 Candidates.push_back(&BBI);
442 Change |= AttemptRestructuring(BBI);
448 // Sort to favor more complex ifcvt scheme.
449 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
454 /// isNextBlock - Returns true either if ToBB the next block after BB or
455 /// that all the intervening blocks are empty.
456 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
457 MachineFunction::iterator I = BB;
458 MachineFunction::iterator TI = ToBB;
459 MachineFunction::iterator E = BB->getParent()->end();
461 if (I == E || !I->empty())
466 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
467 /// to determine if it can be if-converted.
468 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
469 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
470 E = BB->pred_end(); PI != E; ++PI) {
471 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
472 PBBI.Kind = ICReAnalyze;
476 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
478 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
479 const TargetInstrInfo *TII) {
480 std::vector<MachineOperand> NoCond;
481 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
484 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
486 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
487 bool ReverseCond = BBI.Kind == ICSimpleFalse;
489 BBI.Kind = ICNotClassfied;
491 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
492 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
493 BBInfo *CvtBBI = &TrueBBI;
494 BBInfo *NextBBI = &FalseBBI;
496 std::vector<MachineOperand> Cond(BBI.BrCond);
498 std::swap(CvtBBI, NextBBI);
499 TII->ReverseBranchCondition(Cond);
502 PredicateBlock(*CvtBBI, Cond);
503 // If the 'true' block ends without a branch, add a conditional branch
504 // to its successor unless that happens to be the 'false' block.
505 if (CvtBBI->IsAnalyzable && CvtBBI->TrueBB == NULL) {
506 assert(CvtBBI->BB->succ_size() == 1 && "Unexpected!");
507 MachineBasicBlock *SuccBB = *CvtBBI->BB->succ_begin();
508 if (SuccBB != NextBBI->BB)
509 TII->InsertBranch(*CvtBBI->BB, SuccBB, NULL, Cond);
512 // Merge converted block into entry block. Also add an unconditional branch
513 // to the 'false' branch.
514 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
515 MergeBlocks(BBI, *CvtBBI);
516 if (!isNextBlock(BBI.BB, NextBBI->BB))
517 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
518 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
520 // Update block info. BB can be iteratively if-converted.
521 BBI.Kind = ICReAnalyze;
523 CvtBBI->Kind = ICDead;
525 // FIXME: Must maintain LiveIns.
529 /// IfConvertTriangle - If convert a triangle sub-CFG.
531 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
532 BBI.Kind = ICNotClassfied;
534 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
536 // Predicate the 'true' block after removing its branch.
537 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
538 PredicateBlock(TrueBBI, BBI.BrCond);
540 // If 'true' block has a 'false' successor, add an exit branch to it.
541 bool HasEarlyExit = TrueBBI.FalseBB != NULL;
543 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
544 if (TII->ReverseBranchCondition(RevCond))
545 assert(false && "Unable to reverse branch condition!");
546 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
549 // Join the 'true' and 'false' blocks if the 'false' block has no other
550 // predecessors. Otherwise, add a unconditional branch from 'true' to 'false'.
551 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
552 bool FalseBBDead = false;
553 if (!HasEarlyExit && FalseBBI.BB->pred_size() == 2) {
554 MergeBlocks(TrueBBI, FalseBBI);
556 } else if (!isNextBlock(TrueBBI.BB, FalseBBI.BB))
557 InsertUncondBranch(TrueBBI.BB, FalseBBI.BB, TII);
559 // Now merge the entry of the triangle with the true block.
560 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
561 MergeBlocks(BBI, TrueBBI);
562 std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
563 std::back_inserter(BBI.Predicate));
565 // Update block info. BB can be iteratively if-converted.
566 BBI.Kind = ICReAnalyze;
568 TrueBBI.Kind = ICDead;
570 FalseBBI.Kind = ICDead;
572 // FIXME: Must maintain LiveIns.
576 /// IfConvertDiamond - If convert a diamond sub-CFG.
578 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
579 BBI.Kind = ICNotClassfied;
581 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
582 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
584 SmallVector<MachineInstr*, 2> Dups;
586 // No common merge block. Check if the terminators (e.g. return) are
587 // the same or predicable.
588 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
589 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
590 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
591 if (TT->isIdenticalTo(FT))
592 Dups.push_back(TT); // Will erase these later.
593 else if (!TT->isPredicable() && !FT->isPredicable())
594 return false; // Can't if-convert. Abort!
599 // One of the two pathes have more terminators, make sure they are
601 while (TT != BBI.TrueBB->end()) {
602 if (!TT->isPredicable()) {
603 return false; // Can't if-convert. Abort!
607 while (FT != BBI.FalseBB->end()) {
608 if (!FT->isPredicable()) {
609 return false; // Can't if-convert. Abort!
615 // Remove the duplicated instructions from the 'true' block.
616 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
617 Dups[i]->eraseFromParent();
618 --TrueBBI.NonPredSize;
621 // Merge the 'true' and 'false' blocks by copying the instructions
622 // from the 'false' block to the 'true' block. That is, unless the true
623 // block would clobber the predicate, in that case, do the opposite.
624 BBInfo *BBI1 = &TrueBBI;
625 BBInfo *BBI2 = &FalseBBI;
626 std::vector<MachineOperand> RevCond(BBI.BrCond);
627 TII->ReverseBranchCondition(RevCond);
628 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
629 std::vector<MachineOperand> *Cond2 = &RevCond;
630 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
631 // Either the block fallthrough to another block or it ends with a
632 // return. If it's the former, add a branch to its successor.
633 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
634 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
636 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
637 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
638 NeedBr1 && !NeedBr2)) {
639 std::swap(BBI1, BBI2);
640 std::swap(Cond1, Cond2);
641 std::swap(NeedBr1, NeedBr2);
644 // Predicate the 'true' block after removing its branch.
645 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
646 PredicateBlock(*BBI1, *Cond1);
648 // Add an early exit branch if needed.
650 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
652 // Predicate the 'false' block.
653 PredicateBlock(*BBI2, *Cond2, true);
655 // Add an unconditional branch from 'false' to to 'false' successor if it
656 // will not be the fallthrough block.
657 if (NeedBr2 && !isNextBlock(BBI2->BB, *BBI2->BB->succ_begin()))
658 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
660 // Keep them as two separate blocks if there is an early exit.
662 MergeBlocks(*BBI1, *BBI2);
664 // Remove the conditional branch from entry to the blocks.
665 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
667 // Merge the combined block into the entry of the diamond.
668 MergeBlocks(BBI, *BBI1);
670 // 'True' and 'false' aren't combined, see if we need to add a unconditional
671 // branch to the 'false' block.
672 if (NeedBr1 && !isNextBlock(BBI.BB, BBI2->BB))
673 InsertUncondBranch(BBI1->BB, BBI2->BB, TII);
675 // If the if-converted block fallthrough or unconditionally branch into the
676 // tail block, and the tail block does not have other predecessors, then
677 // fold the tail block in as well.
678 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
680 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
681 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
682 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
683 MergeBlocks(*CvtBBI, TailBBI);
684 TailBBI.Kind = ICDead;
687 // Update block info.
688 TrueBBI.Kind = ICDead;
689 FalseBBI.Kind = ICDead;
691 // FIXME: Must maintain LiveIns.
695 /// PredicateBlock - Predicate every instruction in the block with the specified
696 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
697 void IfConverter::PredicateBlock(BBInfo &BBI,
698 std::vector<MachineOperand> &Cond,
700 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
702 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
704 if (TII->isPredicated(I))
706 if (!TII->PredicateInstruction(I, Cond)) {
707 cerr << "Unable to predicate " << *I << "!\n";
716 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
718 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
719 for (MachineBasicBlock::pred_iterator I = FromBB->pred_begin(),
720 E = FromBB->pred_end(); I != E; ++I) {
721 MachineBasicBlock *Pred = *I;
722 Pred->removeSuccessor(FromBB);
723 if (!Pred->isSuccessor(ToBB))
724 Pred->addSuccessor(ToBB);
728 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
730 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
731 for (MachineBasicBlock::succ_iterator I = FromBB->succ_begin(),
732 E = FromBB->succ_end(); I != E; ++I) {
733 MachineBasicBlock *Succ = *I;
734 FromBB->removeSuccessor(Succ);
735 if (!ToBB->isSuccessor(Succ))
736 ToBB->addSuccessor(Succ);
740 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
742 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
743 ToBBI.BB->splice(ToBBI.BB->end(),
744 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
746 // If FromBBI is previously a successor, remove it from ToBBI's successor
747 // list and update its TrueBB / FalseBB field if needed.
748 if (ToBBI.BB->isSuccessor(FromBBI.BB))
749 ToBBI.BB->removeSuccessor(FromBBI.BB);
751 // Redirect all branches to FromBB to ToBB.
752 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
753 FromBBI.BB->pred_end());
754 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
755 Preds[i]->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
757 // Transfer preds / succs and update size.
758 TransferPreds(ToBBI.BB, FromBBI.BB);
759 TransferSuccs(ToBBI.BB, FromBBI.BB);
760 ToBBI.NonPredSize += FromBBI.NonPredSize;
761 FromBBI.NonPredSize = 0;