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 'childrean' have been modified, abort!
160 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
161 << "): BB#" << BBI.BB->getNumber() << " ";
162 RetVal = IfConvertSimple(BBI);
163 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
165 if (BBI.Kind == ICSimple) NumSimple++;
169 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " ";
170 RetVal = IfConvertTriangle(BBI);
171 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
172 if (RetVal) NumTriangle++;
175 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " ";
176 RetVal = IfConvertDiamond(BBI);
177 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
178 if (RetVal) NumDiamonds++;
186 MadeChange |= Change;
195 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
196 MachineBasicBlock *TrueBB) {
197 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
198 E = BB->succ_end(); SI != E; ++SI) {
199 MachineBasicBlock *SuccBB = *SI;
200 if (SuccBB != TrueBB)
206 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
207 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
208 TII->RemoveBranch(*BBI.BB);
209 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
210 std::swap(BBI.TrueBB, BBI.FalseBB);
216 /// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
217 /// the specified block. Record its successors and whether it looks like an
218 /// if-conversion candidate.
219 void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
220 BBInfo &BBI = BBAnalysis[BB->getNumber()];
222 if (BBI.Kind == ICReAnalyze)
225 if (BBI.Kind != ICNotAnalyzed)
226 return; // Already analyzed.
228 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
231 // Look for 'root' of a simple (non-nested) triangle or diamond.
232 BBI.Kind = ICNotClassfied;
234 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
235 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
238 StructuralAnalysis(BBI.TrueBB);
239 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
241 // No false branch. This BB must end with a conditional branch and a
244 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
245 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
247 StructuralAnalysis(BBI.FalseBB);
248 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
250 // Look for more opportunities to if-convert a triangle. Try to restructure
251 // the CFG to form a triangle with the 'false' path.
252 std::vector<MachineOperand> RevCond(BBI.BrCond);
253 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
254 if (FalseBBI.FalseBB) {
255 if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB)
257 std::vector<MachineOperand> Cond(BBI.BrCond);
259 FalseBBI.TrueBB && FalseBBI.BB->pred_size() == 1 &&
260 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
261 std::vector<MachineOperand> FalseCond(FalseBBI.BrCond);
262 if (FalseBBI.TrueBB == BBI.TrueBB &&
263 TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
264 // Reverse 'true' and 'false' paths.
265 ReverseBranchCondition(BBI);
266 BBI.Kind = ICTriangle;
267 FalseBBI.Kind = ICChild;
268 } else if (FalseBBI.FalseBB == BBI.TrueBB &&
269 !TII->ReverseBranchCondition(FalseCond) &&
270 TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
271 // Reverse 'false' block's 'true' and 'false' paths and then
272 // reverse 'true' and 'false' paths.
273 ReverseBranchCondition(FalseBBI);
274 ReverseBranchCondition(BBI);
275 BBI.Kind = ICTriangle;
276 FalseBBI.Kind = ICChild;
279 } else if (TrueBBI.TrueBB == FalseBBI.TrueBB && CanRevCond &&
280 TrueBBI.BB->pred_size() == 1 &&
281 TrueBBI.BB->pred_size() == 1 &&
282 // Check the 'true' and 'false' blocks if either isn't ended with
283 // a branch. If the block does not fallthrough to another block
284 // then we need to add a branch to its successor.
285 !(TrueBBI.ModifyPredicate &&
286 !TrueBBI.TrueBB && TrueBBI.BB->succ_size()) &&
287 !(FalseBBI.ModifyPredicate &&
288 !FalseBBI.TrueBB && FalseBBI.BB->succ_size()) &&
289 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
290 FeasibilityAnalysis(FalseBBI, RevCond)) {
298 // Note MBB can be empty in case both TBB and FBB are return blocks.
299 BBI.Kind = ICDiamond;
300 TrueBBI.Kind = FalseBBI.Kind = ICChild;
301 BBI.TailBB = TrueBBI.TrueBB;
303 // FIXME: Consider duplicating if BB is small.
304 bool TryTriangle = TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB &&
305 BBI.TrueBB->pred_size() == 1;
306 bool TrySimple = TrueBBI.BrCond.size() == 0 && BBI.TrueBB->pred_size() == 1;
307 if ((TryTriangle || TrySimple) &&
308 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
317 BBI.Kind = ICTriangle;
318 TrueBBI.Kind = ICChild;
320 // Simple (split, no rejoin):
328 TrueBBI.Kind = ICChild;
330 } else if (FalseBBI.BrCond.size() == 0 && BBI.FalseBB->pred_size() == 1) {
331 // Try 'simple' on the other path...
332 std::vector<MachineOperand> RevCond(BBI.BrCond);
333 if (TII->ReverseBranchCondition(RevCond))
334 assert(false && "Unable to reverse branch condition!");
335 if (FeasibilityAnalysis(FalseBBI, RevCond)) {
336 BBI.Kind = ICSimpleFalse;
337 FalseBBI.Kind = ICChild;
344 /// FeasibilityAnalysis - Determine if the block is predicable. In most
345 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
346 /// Also checks if the block contains any instruction which can clobber a
347 /// predicate (e.g. condition code register). If so, the block is not
348 /// predicable unless it's the last instruction. If IgnoreTerm is true then
349 /// all the terminator instructions are skipped.
350 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
351 std::vector<MachineOperand> &Cond,
353 // If the block is dead, or it is going to be the entry block of a sub-CFG
354 // that will be if-converted, then it cannot be predicated.
355 if (BBI.Kind != ICNotAnalyzed &&
356 BBI.Kind != ICNotClassfied &&
360 // Check predication threshold.
361 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
364 // If it is already predicated, check if its predicate subsumes the new
366 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
369 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
371 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
373 // TODO: check if instruction clobbers predicate.
374 if (!I->isPredicable())
381 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
382 /// expose more if-conversion opportunities. e.g.
404 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
408 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
409 /// candidates. It returns true if any CFG restructuring is done to expose more
410 /// if-conversion opportunities.
411 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
412 std::vector<BBInfo*> &Candidates) {
414 std::set<MachineBasicBlock*> Visited;
415 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
416 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
417 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
418 MachineBasicBlock *BB = *I;
419 StructuralAnalysis(BB);
420 BBInfo &BBI = BBAnalysis[BB->getNumber()];
426 Candidates.push_back(&BBI);
429 Change |= AttemptRestructuring(BBI);
435 // Sort to favor more complex ifcvt scheme.
436 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
441 /// isNextBlock - Returns true either if ToBB the next block after BB or
442 /// that all the intervening blocks are empty.
443 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
444 MachineFunction::iterator I = BB;
445 while (++I != MachineFunction::iterator(ToBB))
451 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
452 /// to determine if it can be if-converted.
453 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
454 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
455 E = BB->pred_end(); PI != E; ++PI) {
456 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
457 PBBI.Kind = ICReAnalyze;
461 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
463 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
464 const TargetInstrInfo *TII) {
465 std::vector<MachineOperand> NoCond;
466 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
469 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
471 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
472 bool ReverseCond = BBI.Kind == ICSimpleFalse;
474 BBI.Kind = ICNotClassfied;
476 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
477 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
478 BBInfo *CvtBBI = &TrueBBI;
479 BBInfo *NextBBI = &FalseBBI;
481 std::vector<MachineOperand> Cond(BBI.BrCond);
483 std::swap(CvtBBI, NextBBI);
484 TII->ReverseBranchCondition(Cond);
487 PredicateBlock(*CvtBBI, Cond);
488 // If the 'true' block ends without a branch, add a conditional branch
489 // to its successor unless that happens to be the 'false' block.
490 if (CvtBBI->IsAnalyzable && CvtBBI->TrueBB == NULL) {
491 assert(CvtBBI->BB->succ_size() == 1 && "Unexpected!");
492 MachineBasicBlock *SuccBB = *CvtBBI->BB->succ_begin();
493 if (SuccBB != NextBBI->BB)
494 TII->InsertBranch(*CvtBBI->BB, SuccBB, NULL, Cond);
497 // Merge converted block into entry block. Also add an unconditional branch
498 // to the 'false' branch.
499 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
500 MergeBlocks(BBI, *CvtBBI);
501 if (!isNextBlock(BBI.BB, NextBBI->BB))
502 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
503 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
505 // Update block info. BB can be iteratively if-converted.
506 BBI.Kind = ICNotAnalyzed;
507 BBI.TrueBB = BBI.FalseBB = NULL;
509 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
511 CvtBBI->Kind = ICDead;
513 // FIXME: Must maintain LiveIns.
517 /// IfConvertTriangle - If convert a triangle sub-CFG.
519 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
520 BBI.Kind = ICNotClassfied;
522 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
524 // Predicate the 'true' block after removing its branch.
525 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
526 PredicateBlock(TrueBBI, BBI.BrCond);
528 // If 'true' block has a 'false' successor, add an exit branch to it.
529 if (TrueBBI.FalseBB) {
530 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
531 if (TII->ReverseBranchCondition(RevCond))
532 assert(false && "Unable to reverse branch condition!");
533 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
536 // Join the 'true' and 'false' blocks if the 'false' block has no other
537 // predecessors. Otherwise, add a unconditional branch from 'true' to 'false'.
538 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
539 if (FalseBBI.BB->pred_size() == 2)
540 MergeBlocks(TrueBBI, FalseBBI);
541 else if (!isNextBlock(TrueBBI.BB, FalseBBI.BB))
542 InsertUncondBranch(TrueBBI.BB, FalseBBI.BB, TII);
544 // Now merge the entry of the triangle with the true block.
545 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
546 MergeBlocks(BBI, TrueBBI);
547 std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
548 std::back_inserter(BBI.Predicate));
550 // Update block info. BB can be iteratively if-converted.
551 BBI.Kind = ICNotClassfied;
552 BBI.TrueBB = BBI.FalseBB = NULL;
554 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
556 TrueBBI.Kind = ICDead;
558 // FIXME: Must maintain LiveIns.
562 /// IfConvertDiamond - If convert a diamond sub-CFG.
564 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
565 BBI.Kind = ICNotClassfied;
567 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
568 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
570 SmallVector<MachineInstr*, 2> Dups;
572 // No common merge block. Check if the terminators (e.g. return) are
573 // the same or predicable.
574 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
575 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
576 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
577 if (TT->isIdenticalTo(FT))
578 Dups.push_back(TT); // Will erase these later.
579 else if (!TT->isPredicable() && !FT->isPredicable())
580 return false; // Can't if-convert. Abort!
585 // One of the two pathes have more terminators, make sure they are
587 while (TT != BBI.TrueBB->end()) {
588 if (!TT->isPredicable()) {
589 return false; // Can't if-convert. Abort!
593 while (FT != BBI.FalseBB->end()) {
594 if (!FT->isPredicable()) {
595 return false; // Can't if-convert. Abort!
601 // Remove the duplicated instructions from the 'true' block.
602 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
603 Dups[i]->eraseFromParent();
604 --TrueBBI.NonPredSize;
607 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
608 // Either the block fallthrough to another block or it ends with a
609 // return. If it's the former, add a branch to its successor.
610 bool TrueNeedBr = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
611 bool FalseNeedBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
613 // Merge the 'true' and 'false' blocks by copying the instructions
614 // from the 'false' block to the 'true' block. That is, unless the true
615 // block would clobber the predicate, in that case, do the opposite.
616 std::vector<MachineOperand> RevCond(BBI.BrCond);
617 TII->ReverseBranchCondition(RevCond);
619 if (!TrueBBI.ModifyPredicate) {
620 // Predicate the 'true' block after removing its branch.
621 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
622 PredicateBlock(TrueBBI, BBI.BrCond);
624 // Predicate the 'false' block.
625 PredicateBlock(FalseBBI, RevCond, true);
628 TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL,
630 // Add an unconditional branch from 'false' to to 'false' successor if it
631 // will not be the fallthrough block.
633 !isNextBlock(BBI.BB, *BBI.FalseBB->succ_begin()))
634 InsertUncondBranch(BBI.FalseBB, *BBI.FalseBB->succ_begin(), TII);
635 MergeBlocks(TrueBBI, FalseBBI);
638 // Predicate the 'false' block after removing its branch.
639 FalseBBI.NonPredSize -= TII->RemoveBranch(*BBI.FalseBB);
640 PredicateBlock(FalseBBI, RevCond);
642 // Predicate the 'false' block.
643 PredicateBlock(TrueBBI, BBI.BrCond, true);
645 // Add a conditional branch from 'false' to 'false' successor if needed.
647 TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
649 // Add an unconditional branch from 'true' to to 'true' successor if it
650 // will not be the fallthrough block.
652 !isNextBlock(BBI.BB, *BBI.TrueBB->succ_begin()))
653 InsertUncondBranch(BBI.TrueBB, *BBI.TrueBB->succ_begin(), TII);
654 MergeBlocks(FalseBBI, TrueBBI);
658 // Remove the conditional branch from entry to the blocks.
659 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
661 bool OkToIfcvt = true;
662 // Merge the combined block into the entry of the diamond if the entry
663 // block is its only predecessor. Otherwise, insert an unconditional
664 // branch from entry to the if-converted block.
665 if (CvtBBI->BB->pred_size() == 1) {
666 MergeBlocks(BBI, *CvtBBI);
669 } else if (!isNextBlock(BBI.BB, CvtBBI->BB))
670 InsertUncondBranch(BBI.BB, CvtBBI->BB, TII);
672 // If the if-converted block fallthrough or unconditionally branch into the
673 // tail block, and the tail block does not have other predecessors, then
674 // fold the tail block in as well.
676 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
677 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
678 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
679 MergeBlocks(*CvtBBI, TailBBI);
680 TailBBI.Kind = ICDead;
683 // Update block info. BB may be iteratively if-converted.
685 BBI.Kind = ICNotClassfied;
686 BBI.TrueBB = BBI.FalseBB = NULL;
688 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
691 TrueBBI.Kind = ICDead;
692 FalseBBI.Kind = ICDead;
694 // FIXME: Must maintain LiveIns.
698 /// PredicateBlock - Predicate every instruction in the block with the specified
699 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
700 void IfConverter::PredicateBlock(BBInfo &BBI,
701 std::vector<MachineOperand> &Cond,
703 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
705 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
707 if (TII->isPredicated(I))
709 if (!TII->PredicateInstruction(I, Cond)) {
710 cerr << "Unable to predicate " << *I << "!\n";
719 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
721 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
722 for (MachineBasicBlock::pred_iterator I = FromBB->pred_begin(),
723 E = FromBB->pred_end(); I != E; ++I) {
724 MachineBasicBlock *Pred = *I;
725 Pred->removeSuccessor(FromBB);
726 if (!Pred->isSuccessor(ToBB))
727 Pred->addSuccessor(ToBB);
731 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
733 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
734 for (MachineBasicBlock::succ_iterator I = FromBB->succ_begin(),
735 E = FromBB->succ_end(); I != E; ++I) {
736 FromBB->removeSuccessor(*I);
737 if (!ToBB->isSuccessor(*I))
738 ToBB->addSuccessor(*I);
742 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
744 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
745 ToBBI.BB->splice(ToBBI.BB->end(),
746 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
748 // If FromBBI is previously a successor, remove it from ToBBI's successor
749 // list and update its TrueBB / FalseBB field if needed.
750 if (ToBBI.BB->isSuccessor(FromBBI.BB))
751 ToBBI.BB->removeSuccessor(FromBBI.BB);
753 // Redirect all branches to FromBB to ToBB.
754 for (MachineBasicBlock::pred_iterator I = FromBBI.BB->pred_begin(),
755 E = FromBBI.BB->pred_end(); I != E; ++I)
756 (*I)->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
758 // Transfer preds / succs and update size.
759 TransferPreds(ToBBI.BB, FromBBI.BB);
760 TransferSuccs(ToBBI.BB, FromBBI.BB);
761 ToBBI.NonPredSize += FromBBI.NonPredSize;
762 FromBBI.NonPredSize = 0;