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> DisableSimpleF("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> DisableTriangleR("disable-ifcvt-triangle-rev",
40 cl::init(false), cl::Hidden);
41 cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
42 cl::init(false), cl::Hidden);
43 cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
44 cl::init(false), cl::Hidden);
45 cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
46 cl::init(false), cl::Hidden);
49 STATISTIC(NumSimple, "Number of simple if-conversions performed");
50 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
51 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
52 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
53 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
54 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
55 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
56 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
57 STATISTIC(NumDupBBs, "Number of duplicated blocks");
60 class IfConverter : public MachineFunctionPass {
62 ICNotClassfied, // BB data valid, but not classified.
63 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
64 ICSimpleFalse, // Same as ICSimple, but on the false path.
65 ICTriangle, // BB is entry of a triangle sub-CFG.
66 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
67 ICTriangleFalse, // Same as ICTriangle, but on the false path.
68 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
69 ICDiamond // BB is entry of a diamond sub-CFG.
72 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
73 /// if-conversion feasibility analysis. This includes results from
74 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
75 /// classification, and common tail block of its successors (if it's a
76 /// diamond shape), its size, whether it's predicable, and whether any
77 /// instruction can clobber the 'would-be' predicate.
79 /// Kind - Type of block. See BBICKind.
80 /// IsDone - True if BB is not to be considered for ifcvt.
81 /// IsBeingAnalyzed - True if BB is currently being analyzed.
82 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
83 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
84 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
85 /// HasFallThrough - True if BB may fallthrough to the following BB.
86 /// IsUnpredicable - True if BB is known to be unpredicable.
87 /// ClobbersPredicate- True if BB would modify the predicate (e.g. has
89 /// NonPredSize - Number of non-predicated instructions.
90 /// BB - Corresponding MachineBasicBlock.
91 /// TrueBB / FalseBB- See AnalyzeBranch().
92 /// BrCond - Conditions for end of block conditional branches.
93 /// Predicate - Predicate used in the BB.
97 bool IsBeingAnalyzed : 1;
100 bool IsBrAnalyzable : 1;
101 bool HasFallThrough : 1;
102 bool IsUnpredicable : 1;
103 bool ClobbersPred : 1;
104 unsigned NonPredSize;
105 MachineBasicBlock *BB;
106 MachineBasicBlock *TrueBB;
107 MachineBasicBlock *FalseBB;
108 MachineBasicBlock *TailBB;
109 std::vector<MachineOperand> BrCond;
110 std::vector<MachineOperand> Predicate;
111 BBInfo() : Kind(ICNotClassfied), IsDone(false), IsBeingAnalyzed(false),
112 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
113 HasFallThrough(false), IsUnpredicable(false),
114 ClobbersPred(false), NonPredSize(0),
115 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
118 /// Roots - Basic blocks that do not have successors. These are the starting
119 /// points of Graph traversal.
120 std::vector<MachineBasicBlock*> Roots;
122 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
123 /// basic block number.
124 std::vector<BBInfo> BBAnalysis;
126 const TargetLowering *TLI;
127 const TargetInstrInfo *TII;
131 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
133 virtual bool runOnMachineFunction(MachineFunction &MF);
134 virtual const char *getPassName() const { return "If converter"; }
137 bool ReverseBranchCondition(BBInfo &BBI);
138 bool ValidSimple(BBInfo &TrueBBI) const;
139 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
140 bool FalseBranch = false) const;
141 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
142 void ScanInstructions(BBInfo &BBI);
143 BBInfo &AnalyzeBlock(MachineBasicBlock *BB);
144 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
145 bool isTriangle = false, bool RevBranch = false);
146 bool AttemptRestructuring(BBInfo &BBI);
147 bool AnalyzeBlocks(MachineFunction &MF,
148 std::vector<BBInfo*> &Candidates);
149 void ReTryPreds(MachineBasicBlock *BB);
150 void RemoveExtraEdges(BBInfo &BBI);
151 bool IfConvertSimple(BBInfo &BBI);
152 bool IfConvertTriangle(BBInfo &BBI);
153 bool IfConvertDiamond(BBInfo &BBI);
154 void PredicateBlock(BBInfo &BBI,
155 std::vector<MachineOperand> &Cond,
156 bool IgnoreTerm = false);
157 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
158 std::vector<MachineOperand> &Cond,
159 bool IgnoreBr = false);
160 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
162 // blockAlwaysFallThrough - Block ends without a terminator.
163 bool blockAlwaysFallThrough(BBInfo &BBI) const {
164 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
167 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
168 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
169 // Favor diamond over triangle, etc.
170 return (unsigned)C1->Kind < (unsigned)C2->Kind;
173 char IfConverter::ID = 0;
176 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
178 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
179 TLI = MF.getTarget().getTargetLowering();
180 TII = MF.getTarget().getInstrInfo();
181 if (!TII) return false;
183 static int FnNum = -1;
184 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
185 << MF.getFunction()->getName() << "\'";
187 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
188 DOUT << " skipped\n";
194 BBAnalysis.resize(MF.getNumBlockIDs());
196 // Look for root nodes, i.e. blocks without successors.
197 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
198 if (I->succ_size() == 0)
201 std::vector<BBInfo*> Candidates;
203 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
204 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
205 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
206 // Do an intial analysis for each basic block and finding all the potential
207 // candidates to perform if-convesion.
208 bool Change = AnalyzeBlocks(MF, Candidates);
209 while (!Candidates.empty()) {
210 BBInfo &BBI = *Candidates.back();
211 Candidates.pop_back();
213 // If the block has been evicted out of the queue or it has already been
214 // marked dead (due to it being predicated), then skip it.
215 if (!BBI.IsEnqueued || BBI.IsDone)
217 BBI.IsEnqueued = false;
221 default: assert(false && "Unexpected!");
224 case ICSimpleFalse: {
225 bool isFalse = BBI.Kind == ICSimpleFalse;
226 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
227 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
228 << "): BB#" << BBI.BB->getNumber() << " ("
229 << ((BBI.Kind == ICSimpleFalse)
230 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
231 RetVal = IfConvertSimple(BBI);
232 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
234 if (isFalse) NumSimpleFalse++;
240 case ICTriangleFalse:
241 case ICTriangleFRev: {
242 bool isFalse = BBI.Kind == ICTriangleFalse;
243 bool isRev = (BBI.Kind == ICTriangleRev || BBI.Kind == ICTriangleFRev);
244 if (DisableTriangle && !isFalse && !isRev) break;
245 if (DisableTriangleR && !isFalse && isRev) break;
246 if (DisableTriangleF && isFalse && !isRev) break;
247 if (DisableTriangleFR && isFalse && isRev) break;
248 DOUT << "Ifcvt (Triangle";
253 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
254 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
256 RetVal = IfConvertTriangle(BBI);
257 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
260 if (isRev) NumTriangleFRev++;
261 else NumTriangleFalse++;
263 if (isRev) NumTriangleRev++;
270 if (DisableDiamond) break;
271 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
272 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
274 DOUT << "," << BBI.TailBB->getNumber() ;
276 RetVal = IfConvertDiamond(BBI);
277 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
278 if (RetVal) NumDiamonds++;
283 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
284 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
285 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
291 MadeChange |= Change;
300 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
301 MachineBasicBlock *TrueBB) {
302 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
303 E = BB->succ_end(); SI != E; ++SI) {
304 MachineBasicBlock *SuccBB = *SI;
305 if (SuccBB != TrueBB)
311 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
312 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
313 TII->RemoveBranch(*BBI.BB);
314 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
315 std::swap(BBI.TrueBB, BBI.FalseBB);
321 /// getNextBlock - Returns the next block in the function blocks ordering. If
322 /// it is the end, returns NULL.
323 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
324 MachineFunction::iterator I = BB;
325 MachineFunction::iterator E = BB->getParent()->end();
331 /// ValidSimple - Returns true if the 'true' block (along with its
332 /// predecessor) forms a valid simple shape for ifcvt.
333 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
334 if (TrueBBI.IsBeingAnalyzed)
337 if (TrueBBI.BB->pred_size() != 1) {
338 if (TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
342 return !blockAlwaysFallThrough(TrueBBI) && TrueBBI.BrCond.size() == 0;
345 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
346 /// with their common predecessor) forms a valid triangle shape for ifcvt.
347 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
348 bool FalseBranch) const {
349 if (TrueBBI.IsBeingAnalyzed)
352 if (TrueBBI.BB->pred_size() != 1) {
353 unsigned Size = TrueBBI.NonPredSize;
356 if (Size > TLI->getIfCvtDupBlockSizeLimit())
360 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
361 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
362 MachineFunction::iterator I = TrueBBI.BB;
363 if (++I == TrueBBI.BB->getParent()->end())
367 return TExit && TExit == FalseBBI.BB;
370 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
371 /// with their common predecessor) forms a valid diamond shape for ifcvt.
372 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
373 if (TrueBBI.IsBeingAnalyzed || FalseBBI.IsBeingAnalyzed)
376 MachineBasicBlock *TT = TrueBBI.TrueBB;
377 MachineBasicBlock *FT = FalseBBI.TrueBB;
379 if (!TT && blockAlwaysFallThrough(TrueBBI))
380 TT = getNextBlock(TrueBBI.BB);
381 if (!FT && blockAlwaysFallThrough(FalseBBI))
382 FT = getNextBlock(FalseBBI.BB);
385 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
387 // FIXME: Allow false block to have an early exit?
388 return (TrueBBI.BB->pred_size() == 1 &&
389 FalseBBI.BB->pred_size() == 1 &&
390 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
393 /// ScanInstructions - Scan all the instructions in the block to determine if
394 /// the block is predicable. In most cases, that means all the instructions
395 /// in the block has M_PREDICABLE flag. Also checks if the block contains any
396 /// instruction which can clobber a predicate (e.g. condition code register).
397 /// If so, the block is not predicable unless it's the last instruction.
398 void IfConverter::ScanInstructions(BBInfo &BBI) {
402 // First analyze the end of BB branches.
403 BBI.TrueBB = BBI.FalseBB = NULL;
406 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
407 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
409 if (BBI.BrCond.size()) {
410 // No false branch. This BB must end with a conditional branch and a
413 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
414 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
417 // Then scan all the instructions.
419 BBI.ClobbersPred = false;
420 bool SeenCondBr = false;
421 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
423 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
424 bool isPredicated = TII->isPredicated(I);
425 bool isCondBr = BBI.IsBrAnalyzable &&
426 (TID->Flags & M_BRANCH_FLAG) != 0 && (TID->Flags & M_BARRIER_FLAG) == 0;
428 if (!isPredicated && !isCondBr)
431 if (BBI.ClobbersPred && !isPredicated) {
432 // Predicate modification instruction should end the block (except for
433 // already predicated instructions and end of block branches).
437 // Conditional branches is not predicable. But it may be eliminated.
441 // Predicate may have been modified, the subsequent (currently)
442 // unpredocated instructions cannot be correctly predicated.
443 BBI.IsUnpredicable = true;
447 if (TID->Flags & M_CLOBBERS_PRED)
448 BBI.ClobbersPred = true;
450 if (!I->isPredicable()) {
451 BBI.IsUnpredicable = true;
457 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
458 /// predicated by the specified predicate.
459 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
460 std::vector<MachineOperand> &Pred,
461 bool isTriangle, bool RevBranch) {
462 // Forget about it if it's unpredicable.
463 if (BBI.IsUnpredicable)
466 // If the block is dead, or it is going to be the entry block of a sub-CFG
467 // that will be if-converted, then it cannot be predicated.
468 if (BBI.IsDone || BBI.IsEnqueued)
471 // Check predication threshold.
472 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
475 // If it is already predicated, check if its predicate subsumes the new
477 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
480 if (BBI.BrCond.size()) {
484 // Test predicate subsumsion.
485 std::vector<MachineOperand> RevPred(Pred);
486 std::vector<MachineOperand> Cond(BBI.BrCond);
488 if (TII->ReverseBranchCondition(Cond))
491 if (TII->ReverseBranchCondition(RevPred) ||
492 !TII->SubsumesPredicate(Cond, RevPred))
499 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
500 /// the specified block. Record its successors and whether it looks like an
501 /// if-conversion candidate.
502 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
503 BBInfo &BBI = BBAnalysis[BB->getNumber()];
505 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
509 BBI.IsBeingAnalyzed = true;
510 BBI.Kind = ICNotClassfied;
512 ScanInstructions(BBI);
514 // Unanalyable or ends with fallthrough or unconditional branch.
515 if (!BBI.IsBrAnalyzable || BBI.BrCond.size() == 0) {
516 BBI.IsBeingAnalyzed = false;
517 BBI.IsAnalyzed = true;
521 // Do not ifcvt if either path is a back edge to the entry block.
522 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
523 BBI.IsBeingAnalyzed = false;
524 BBI.IsAnalyzed = true;
528 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB);
529 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB);
531 if (TrueBBI.IsDone && FalseBBI.IsDone) {
532 BBI.IsBeingAnalyzed = false;
533 BBI.IsAnalyzed = true;
537 std::vector<MachineOperand> RevCond(BBI.BrCond);
538 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
540 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
541 !(TrueBBI.ClobbersPred && FalseBBI.ClobbersPred) &&
542 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
543 FeasibilityAnalysis(FalseBBI, RevCond)) {
551 // Note TailBB can be empty.
552 BBI.Kind = ICDiamond;
553 BBI.TailBB = TrueBBI.TrueBB;
555 // FIXME: Consider duplicating if BB is small.
556 if (ValidTriangle(TrueBBI, FalseBBI) &&
557 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
565 BBI.Kind = ICTriangle;
566 } else if (ValidTriangle(TrueBBI, FalseBBI, true) &&
567 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
568 BBI.Kind = ICTriangleRev;
569 } else if (ValidSimple(TrueBBI) &&
570 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
571 // Simple (split, no rejoin):
579 } else if (CanRevCond) {
580 // Try the other path...
581 if (ValidTriangle(FalseBBI, TrueBBI) &&
582 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
583 BBI.Kind = ICTriangleFalse;
584 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
585 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
586 BBI.Kind = ICTriangleFRev;
587 } else if (ValidSimple(FalseBBI) &&
588 FeasibilityAnalysis(FalseBBI, RevCond)) {
589 BBI.Kind = ICSimpleFalse;
594 BBI.IsBeingAnalyzed = false;
595 BBI.IsAnalyzed = true;
599 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
600 /// expose more if-conversion opportunities. e.g.
622 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
626 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
627 /// candidates. It returns true if any CFG restructuring is done to expose more
628 /// if-conversion opportunities.
629 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
630 std::vector<BBInfo*> &Candidates) {
632 std::set<MachineBasicBlock*> Visited;
633 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
634 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
635 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
636 MachineBasicBlock *BB = *I;
637 BBInfo &BBI = AnalyzeBlock(BB);
643 case ICTriangleFalse:
646 BBI.IsEnqueued = true;
647 Candidates.push_back(&BBI);
650 Change |= AttemptRestructuring(BBI);
656 // Sort to favor more complex ifcvt scheme.
657 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
662 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
663 /// that all the intervening blocks are empty (given BB can fall through to its
665 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
666 MachineFunction::iterator I = BB;
667 MachineFunction::iterator TI = ToBB;
668 MachineFunction::iterator E = BB->getParent()->end();
670 if (I == E || !I->empty())
675 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
676 /// to determine if it can be if-converted. If predecessor is already
677 /// enqueud, dequeue it!
678 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
679 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
680 E = BB->pred_end(); PI != E; ++PI) {
681 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
682 if (PBBI.IsDone || PBBI.BB == BB)
684 PBBI.Kind = ICNotClassfied;
685 PBBI.IsAnalyzed = false;
686 PBBI.IsEnqueued = false;
690 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
692 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
693 const TargetInstrInfo *TII) {
694 std::vector<MachineOperand> NoCond;
695 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
698 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
700 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
701 MachineBasicBlock *TBB = NULL, *FBB = NULL;
702 std::vector<MachineOperand> Cond;
703 bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
704 bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
705 if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
706 if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
707 (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
708 BBI.BB->removeSuccessor(BBI.TrueBB);
709 if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
710 if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
711 (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
712 BBI.BB->removeSuccessor(BBI.FalseBB);
715 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
717 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
718 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
719 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
720 BBInfo *CvtBBI = &TrueBBI;
721 BBInfo *NextBBI = &FalseBBI;
723 std::vector<MachineOperand> Cond(BBI.BrCond);
724 if (BBI.Kind == ICSimpleFalse) {
725 std::swap(CvtBBI, NextBBI);
726 TII->ReverseBranchCondition(Cond);
729 if (CvtBBI->BB->pred_size() > 1) {
730 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
731 // Copy instructions in the true block, predicate them add them to
733 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
735 PredicateBlock(*CvtBBI, Cond);
737 // Merge converted block into entry block.
738 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
739 MergeBlocks(BBI, *CvtBBI);
742 bool IterIfcvt = true;
743 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
744 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
745 BBI.HasFallThrough = false;
746 // Now ifcvt'd block will look like this:
753 // We cannot further ifcvt this block because the unconditional branch
754 // will have to be predicated on the new condition, that will not be
755 // available if cmp executes.
759 RemoveExtraEdges(BBI);
761 // Update block info. BB can be iteratively if-converted.
765 CvtBBI->IsDone = true;
767 // FIXME: Must maintain LiveIns.
771 /// IfConvertTriangle - If convert a triangle sub-CFG.
773 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
774 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
775 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
776 BBInfo *CvtBBI = &TrueBBI;
777 BBInfo *NextBBI = &FalseBBI;
779 std::vector<MachineOperand> Cond(BBI.BrCond);
780 if (BBI.Kind == ICTriangleFalse || BBI.Kind == ICTriangleFRev) {
781 std::swap(CvtBBI, NextBBI);
782 TII->ReverseBranchCondition(Cond);
784 if (BBI.Kind == ICTriangleRev || BBI.Kind == ICTriangleFRev) {
785 ReverseBranchCondition(*CvtBBI);
786 // BB has been changed, modify its predecessors (except for this
787 // one) so they don't get ifcvt'ed based on bad intel.
788 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
789 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
790 MachineBasicBlock *PBB = *PI;
793 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
794 if (PBBI.IsEnqueued) {
795 PBBI.Kind = ICNotClassfied;
796 PBBI.IsAnalyzed = false;
797 PBBI.IsEnqueued = false;
802 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
803 bool DupBB = CvtBBI->BB->pred_size() > 1;
805 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
806 // Copy instructions in the true block, predicate them add them to
808 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
809 BBI.BB->removeSuccessor(CvtBBI->BB);
811 // Predicate the 'true' block after removing its branch.
812 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
813 PredicateBlock(*CvtBBI, Cond);
816 // If 'true' block has a 'false' successor, add an exit branch to it.
818 std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
819 if (TII->ReverseBranchCondition(RevCond))
820 assert(false && "Unable to reverse branch condition!");
822 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
823 BBI.BB->addSuccessor(CvtBBI->FalseBB);
825 TII->InsertBranch(*CvtBBI->BB, CvtBBI->FalseBB, NULL, RevCond);
830 // Now merge the entry of the triangle with the true block.
831 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
832 MergeBlocks(BBI, *CvtBBI);
835 // Merge in the 'false' block if the 'false' block has no other
836 // predecessors. Otherwise, add a unconditional branch from to 'false'.
837 bool FalseBBDead = false;
838 bool IterIfcvt = true;
839 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
840 if (!isFallThrough) {
841 // Only merge them if the true block does not fallthrough to the false
842 // block. By not merging them, we make it possible to iteratively
844 if (!HasEarlyExit && NextBBI->BB->pred_size() == 1) {
845 MergeBlocks(BBI, *NextBBI);
848 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
849 BBI.HasFallThrough = false;
851 // Mixed predicated and unpredicated code. This cannot be iteratively
856 RemoveExtraEdges(BBI);
858 // Update block info. BB can be iteratively if-converted.
862 CvtBBI->IsDone = true;
864 NextBBI->IsDone = true;
866 // FIXME: Must maintain LiveIns.
870 /// IfConvertDiamond - If convert a diamond sub-CFG.
872 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
873 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
874 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
876 SmallVector<MachineInstr*, 2> Dups;
878 // No common merge block. Check if the terminators (e.g. return) are
879 // the same or predicable.
880 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
881 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
882 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
883 if (TT->isIdenticalTo(FT))
884 Dups.push_back(TT); // Will erase these later.
885 else if (!TT->isPredicable() && !FT->isPredicable())
886 return false; // Can't if-convert. Abort!
891 // One of the two pathes have more terminators, make sure they are
893 while (TT != BBI.TrueBB->end()) {
894 if (!TT->isPredicable()) {
895 return false; // Can't if-convert. Abort!
899 while (FT != BBI.FalseBB->end()) {
900 if (!FT->isPredicable()) {
901 return false; // Can't if-convert. Abort!
907 // Remove the duplicated instructions from the 'true' block.
908 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
909 Dups[i]->eraseFromParent();
910 --TrueBBI.NonPredSize;
913 // Merge the 'true' and 'false' blocks by copying the instructions
914 // from the 'false' block to the 'true' block. That is, unless the true
915 // block would clobber the predicate, in that case, do the opposite.
916 BBInfo *BBI1 = &TrueBBI;
917 BBInfo *BBI2 = &FalseBBI;
918 std::vector<MachineOperand> RevCond(BBI.BrCond);
919 TII->ReverseBranchCondition(RevCond);
920 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
921 std::vector<MachineOperand> *Cond2 = &RevCond;
922 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
923 // Either the block fallthrough to another block or it ends with a
924 // return. If it's the former, add a branch to its successor.
925 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
926 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
928 if ((TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred) ||
929 (!TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred &&
930 NeedBr1 && !NeedBr2)) {
931 std::swap(BBI1, BBI2);
932 std::swap(Cond1, Cond2);
933 std::swap(NeedBr1, NeedBr2);
936 // Predicate the 'true' block after removing its branch.
937 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
938 PredicateBlock(*BBI1, *Cond1);
940 // Add an early exit branch if needed.
942 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
944 // Predicate the 'false' block.
945 PredicateBlock(*BBI2, *Cond2, true);
947 // Add an unconditional branch from 'false' to to 'false' successor if it
948 // will not be the fallthrough block.
949 if (NeedBr2 && !NeedBr1) {
950 // If BBI2 isn't going to be merged in, then the existing fallthrough
951 // or branch is fine.
952 if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
953 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
954 BBI2->HasFallThrough = false;
958 // Keep them as two separate blocks if there is an early exit.
960 MergeBlocks(*BBI1, *BBI2);
962 // Remove the conditional branch from entry to the blocks.
963 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
965 // Merge the combined block into the entry of the diamond.
966 MergeBlocks(BBI, *BBI1);
968 // 'True' and 'false' aren't combined, see if we need to add a unconditional
969 // branch to the 'false' block.
970 if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
971 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
972 BBI1->HasFallThrough = false;
975 // If the if-converted block fallthrough or unconditionally branch into the
976 // tail block, and the tail block does not have other predecessors, then
977 // fold the tail block in as well.
978 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
980 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
981 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
982 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
983 MergeBlocks(*CvtBBI, TailBBI);
984 TailBBI.IsDone = true;
987 RemoveExtraEdges(BBI);
989 // Update block info.
990 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
992 // FIXME: Must maintain LiveIns.
996 /// PredicateBlock - Predicate every instruction in the block with the specified
997 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
998 void IfConverter::PredicateBlock(BBInfo &BBI,
999 std::vector<MachineOperand> &Cond,
1001 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
1003 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
1005 if (TII->isPredicated(I))
1007 if (!TII->PredicateInstruction(I, Cond)) {
1008 cerr << "Unable to predicate " << *I << "!\n";
1013 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1015 BBI.IsAnalyzed = false;
1016 BBI.NonPredSize = 0;
1021 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1022 /// the destination block. Skip end of block branches if IgnoreBr is true.
1023 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1024 std::vector<MachineOperand> &Cond,
1026 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1027 E = FromBBI.BB->end(); I != E; ++I) {
1028 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
1029 bool isPredicated = TII->isPredicated(I);
1030 // Do not copy the end of the block branches.
1031 if (IgnoreBr && !isPredicated && (TID->Flags & M_BRANCH_FLAG) != 0)
1034 MachineInstr *MI = I->clone();
1035 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1036 ToBBI.NonPredSize++;
1039 if (!TII->PredicateInstruction(MI, Cond)) {
1040 cerr << "Unable to predicate " << *MI << "!\n";
1045 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1046 std::back_inserter(ToBBI.Predicate));
1047 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1049 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1050 ToBBI.IsAnalyzed = false;
1055 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1057 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1058 ToBBI.BB->splice(ToBBI.BB->end(),
1059 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1061 // Redirect all branches to FromBB to ToBB.
1062 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1063 FromBBI.BB->pred_end());
1064 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1065 MachineBasicBlock *Pred = Preds[i];
1066 if (Pred == ToBBI.BB)
1068 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1071 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1072 FromBBI.BB->succ_end());
1073 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1074 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1076 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1077 MachineBasicBlock *Succ = Succs[i];
1078 // Fallthrough edge can't be transferred.
1079 if (Succ == FallThrough)
1081 FromBBI.BB->removeSuccessor(Succ);
1082 if (!ToBBI.BB->isSuccessor(Succ))
1083 ToBBI.BB->addSuccessor(Succ);
1086 // Now FromBBI always fall through to the next block!
1088 FromBBI.BB->addSuccessor(NBB);
1090 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1091 std::back_inserter(ToBBI.Predicate));
1092 FromBBI.Predicate.clear();
1094 ToBBI.NonPredSize += FromBBI.NonPredSize;
1095 FromBBI.NonPredSize = 0;
1097 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1098 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1099 ToBBI.IsAnalyzed = false;
1100 FromBBI.IsAnalyzed = false;