1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "BranchFolding.h"
16 #include "llvm/Function.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetInstrItineraries.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
35 // Hidden options for help debugging.
36 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
39 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
40 cl::init(false), cl::Hidden);
41 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
42 cl::init(false), cl::Hidden);
43 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
44 cl::init(false), cl::Hidden);
45 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
46 cl::init(false), cl::Hidden);
47 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
48 cl::init(false), cl::Hidden);
49 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
50 cl::init(false), cl::Hidden);
51 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
52 cl::init(false), cl::Hidden);
53 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54 cl::init(true), cl::Hidden);
56 STATISTIC(NumSimple, "Number of simple if-conversions performed");
57 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
58 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
59 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
60 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
63 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
64 STATISTIC(NumDupBBs, "Number of duplicated blocks");
67 class IfConverter : public MachineFunctionPass {
69 ICNotClassfied, // BB data valid, but not classified.
70 ICSimpleFalse, // Same as ICSimple, but on the false path.
71 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
72 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
73 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
74 ICTriangleFalse, // Same as ICTriangle, but on the false path.
75 ICTriangle, // BB is entry of a triangle sub-CFG.
76 ICDiamond // BB is entry of a diamond sub-CFG.
79 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
80 /// if-conversion feasibility analysis. This includes results from
81 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
82 /// classification, and common tail block of its successors (if it's a
83 /// diamond shape), its size, whether it's predicable, and whether any
84 /// instruction can clobber the 'would-be' predicate.
86 /// IsDone - True if BB is not to be considered for ifcvt.
87 /// IsBeingAnalyzed - True if BB is currently being analyzed.
88 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
89 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
90 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
91 /// HasFallThrough - True if BB may fallthrough to the following BB.
92 /// IsUnpredicable - True if BB is known to be unpredicable.
93 /// ClobbersPred - True if BB could modify predicates (e.g. has
95 /// NonPredSize - Number of non-predicated instructions.
96 /// ExtraCost - Extra cost for microcoded instructions.
97 /// BB - Corresponding MachineBasicBlock.
98 /// TrueBB / FalseBB- See AnalyzeBranch().
99 /// BrCond - Conditions for end of block conditional branches.
100 /// Predicate - Predicate used in the BB.
103 bool IsBeingAnalyzed : 1;
106 bool IsBrAnalyzable : 1;
107 bool HasFallThrough : 1;
108 bool IsUnpredicable : 1;
109 bool CannotBeCopied : 1;
110 bool ClobbersPred : 1;
111 unsigned NonPredSize;
113 MachineBasicBlock *BB;
114 MachineBasicBlock *TrueBB;
115 MachineBasicBlock *FalseBB;
116 SmallVector<MachineOperand, 4> BrCond;
117 SmallVector<MachineOperand, 4> Predicate;
118 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
119 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
120 HasFallThrough(false), IsUnpredicable(false),
121 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
122 ExtraCost(0), BB(0), TrueBB(0), FalseBB(0) {}
125 /// IfcvtToken - Record information about pending if-conversions to attempt:
126 /// BBI - Corresponding BBInfo.
127 /// Kind - Type of block. See IfcvtKind.
128 /// NeedSubsumption - True if the to-be-predicated BB has already been
130 /// NumDups - Number of instructions that would be duplicated due
131 /// to this if-conversion. (For diamonds, the number of
132 /// identical instructions at the beginnings of both
134 /// NumDups2 - For diamonds, the number of identical instructions
135 /// at the ends of both paths.
139 bool NeedSubsumption;
142 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
143 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
146 /// Roots - Basic blocks that do not have successors. These are the starting
147 /// points of Graph traversal.
148 std::vector<MachineBasicBlock*> Roots;
150 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
151 /// basic block number.
152 std::vector<BBInfo> BBAnalysis;
154 const TargetLowering *TLI;
155 const TargetInstrInfo *TII;
156 const TargetRegisterInfo *TRI;
157 const InstrItineraryData *InstrItins;
158 const MachineLoopInfo *MLI;
163 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
164 initializeIfConverterPass(*PassRegistry::getPassRegistry());
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<MachineLoopInfo>();
169 MachineFunctionPass::getAnalysisUsage(AU);
172 virtual bool runOnMachineFunction(MachineFunction &MF);
173 virtual const char *getPassName() const { return "If Converter"; }
176 bool ReverseBranchCondition(BBInfo &BBI);
177 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
178 float Prediction, float Confidence) const;
179 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
180 bool FalseBranch, unsigned &Dups,
181 float Prediction, float Confidence) const;
182 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
183 unsigned &Dups1, unsigned &Dups2) const;
184 void ScanInstructions(BBInfo &BBI);
185 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
186 std::vector<IfcvtToken*> &Tokens);
187 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
188 bool isTriangle = false, bool RevBranch = false);
189 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
190 void InvalidatePreds(MachineBasicBlock *BB);
191 void RemoveExtraEdges(BBInfo &BBI);
192 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
193 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
194 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
195 unsigned NumDups1, unsigned NumDups2);
196 void PredicateBlock(BBInfo &BBI,
197 MachineBasicBlock::iterator E,
198 SmallVectorImpl<MachineOperand> &Cond,
199 SmallSet<unsigned, 4> &Redefs);
200 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
201 SmallVectorImpl<MachineOperand> &Cond,
202 SmallSet<unsigned, 4> &Redefs,
203 bool IgnoreBr = false);
204 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
206 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, unsigned Size,
207 float Prediction, float Confidence) const {
208 return Size > 0 && TII->isProfitableToIfCvt(BB, Size,
209 Prediction, Confidence);
212 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, unsigned TSize,
213 MachineBasicBlock &FBB, unsigned FSize,
214 float Prediction, float Confidence) const {
215 return TSize > 0 && FSize > 0 &&
216 TII->isProfitableToIfCvt(TBB, TSize, FBB, FSize,
217 Prediction, Confidence);
220 // blockAlwaysFallThrough - Block ends without a terminator.
221 bool blockAlwaysFallThrough(BBInfo &BBI) const {
222 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
225 // IfcvtTokenCmp - Used to sort if-conversion candidates.
226 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
227 int Incr1 = (C1->Kind == ICDiamond)
228 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
229 int Incr2 = (C2->Kind == ICDiamond)
230 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
233 else if (Incr1 == Incr2) {
234 // Favors subsumption.
235 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
237 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
238 // Favors diamond over triangle, etc.
239 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
241 else if (C1->Kind == C2->Kind)
242 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
249 char IfConverter::ID = 0;
252 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
253 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
254 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
256 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
258 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
259 TLI = MF.getTarget().getTargetLowering();
260 TII = MF.getTarget().getInstrInfo();
261 TRI = MF.getTarget().getRegisterInfo();
262 MLI = &getAnalysis<MachineLoopInfo>();
263 InstrItins = MF.getTarget().getInstrItineraryData();
264 if (!TII) return false;
266 // Tail merge tend to expose more if-conversion opportunities.
267 BranchFolder BF(true);
268 bool BFChange = BF.OptimizeFunction(MF, TII,
269 MF.getTarget().getRegisterInfo(),
270 getAnalysisIfAvailable<MachineModuleInfo>());
272 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
273 << MF.getFunction()->getName() << "\'");
275 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
276 DEBUG(dbgs() << " skipped\n");
279 DEBUG(dbgs() << "\n");
282 BBAnalysis.resize(MF.getNumBlockIDs());
284 // Look for root nodes, i.e. blocks without successors.
285 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
289 std::vector<IfcvtToken*> Tokens;
291 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
292 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
293 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
294 // Do an initial analysis for each basic block and find all the potential
295 // candidates to perform if-conversion.
297 AnalyzeBlocks(MF, Tokens);
298 while (!Tokens.empty()) {
299 IfcvtToken *Token = Tokens.back();
301 BBInfo &BBI = Token->BBI;
302 IfcvtKind Kind = Token->Kind;
303 unsigned NumDups = Token->NumDups;
304 unsigned NumDups2 = Token->NumDups2;
308 // If the block has been evicted out of the queue or it has already been
309 // marked dead (due to it being predicated), then skip it.
311 BBI.IsEnqueued = false;
315 BBI.IsEnqueued = false;
319 default: assert(false && "Unexpected!");
322 case ICSimpleFalse: {
323 bool isFalse = Kind == ICSimpleFalse;
324 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
325 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
327 << "): BB#" << BBI.BB->getNumber() << " ("
328 << ((Kind == ICSimpleFalse)
329 ? BBI.FalseBB->getNumber()
330 : BBI.TrueBB->getNumber()) << ") ");
331 RetVal = IfConvertSimple(BBI, Kind);
332 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
334 if (isFalse) ++NumSimpleFalse;
341 case ICTriangleFalse:
342 case ICTriangleFRev: {
343 bool isFalse = Kind == ICTriangleFalse;
344 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
345 if (DisableTriangle && !isFalse && !isRev) break;
346 if (DisableTriangleR && !isFalse && isRev) break;
347 if (DisableTriangleF && isFalse && !isRev) break;
348 if (DisableTriangleFR && isFalse && isRev) break;
349 DEBUG(dbgs() << "Ifcvt (Triangle");
351 DEBUG(dbgs() << " false");
353 DEBUG(dbgs() << " rev");
354 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
355 << BBI.TrueBB->getNumber() << ",F:"
356 << BBI.FalseBB->getNumber() << ") ");
357 RetVal = IfConvertTriangle(BBI, Kind);
358 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
361 if (isRev) ++NumTriangleFRev;
362 else ++NumTriangleFalse;
364 if (isRev) ++NumTriangleRev;
371 if (DisableDiamond) break;
372 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
373 << BBI.TrueBB->getNumber() << ",F:"
374 << BBI.FalseBB->getNumber() << ") ");
375 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
376 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
377 if (RetVal) ++NumDiamonds;
384 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
385 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
386 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
392 MadeChange |= Change;
395 // Delete tokens in case of early exit.
396 while (!Tokens.empty()) {
397 IfcvtToken *Token = Tokens.back();
406 if (MadeChange && IfCvtBranchFold) {
407 BranchFolder BF(false);
408 BF.OptimizeFunction(MF, TII,
409 MF.getTarget().getRegisterInfo(),
410 getAnalysisIfAvailable<MachineModuleInfo>());
413 MadeChange |= BFChange;
417 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
418 /// its 'true' successor.
419 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
420 MachineBasicBlock *TrueBB) {
421 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
422 E = BB->succ_end(); SI != E; ++SI) {
423 MachineBasicBlock *SuccBB = *SI;
424 if (SuccBB != TrueBB)
430 /// ReverseBranchCondition - Reverse the condition of the end of the block
431 /// branch. Swap block's 'true' and 'false' successors.
432 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
433 DebugLoc dl; // FIXME: this is nowhere
434 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
435 TII->RemoveBranch(*BBI.BB);
436 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
437 std::swap(BBI.TrueBB, BBI.FalseBB);
443 /// getNextBlock - Returns the next block in the function blocks ordering. If
444 /// it is the end, returns NULL.
445 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
446 MachineFunction::iterator I = BB;
447 MachineFunction::iterator E = BB->getParent()->end();
453 /// ValidSimple - Returns true if the 'true' block (along with its
454 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
455 /// number of instructions that the ifcvt would need to duplicate if performed
457 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
458 float Prediction, float Confidence) const {
460 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
463 if (TrueBBI.IsBrAnalyzable)
466 if (TrueBBI.BB->pred_size() > 1) {
467 if (TrueBBI.CannotBeCopied ||
468 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
469 Prediction, Confidence))
471 Dups = TrueBBI.NonPredSize;
477 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
478 /// with their common predecessor) forms a valid triangle shape for ifcvt.
479 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
480 /// branches to the 'false' block rather than the other way around. It also
481 /// returns the number of instructions that the ifcvt would need to duplicate
482 /// if performed in 'Dups'.
483 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
484 bool FalseBranch, unsigned &Dups,
485 float Prediction, float Confidence) const {
487 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
490 if (TrueBBI.BB->pred_size() > 1) {
491 if (TrueBBI.CannotBeCopied)
494 unsigned Size = TrueBBI.NonPredSize;
495 if (TrueBBI.IsBrAnalyzable) {
496 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
497 // Ends with an unconditional branch. It will be removed.
500 MachineBasicBlock *FExit = FalseBranch
501 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
503 // Require a conditional branch
507 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size,
508 Prediction, Confidence))
513 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
514 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
515 MachineFunction::iterator I = TrueBBI.BB;
516 if (++I == TrueBBI.BB->getParent()->end())
520 return TExit && TExit == FalseBBI.BB;
523 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
524 /// with their common predecessor) forms a valid diamond shape for ifcvt.
525 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
526 unsigned &Dups1, unsigned &Dups2) const {
528 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
529 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
532 MachineBasicBlock *TT = TrueBBI.TrueBB;
533 MachineBasicBlock *FT = FalseBBI.TrueBB;
535 if (!TT && blockAlwaysFallThrough(TrueBBI))
536 TT = getNextBlock(TrueBBI.BB);
537 if (!FT && blockAlwaysFallThrough(FalseBBI))
538 FT = getNextBlock(FalseBBI.BB);
541 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
543 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
546 // FIXME: Allow true block to have an early exit?
547 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
548 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
551 // Count duplicate instructions at the beginning of the true and false blocks.
552 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
553 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
554 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
555 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
556 while (TIB != TIE && FIB != FIE) {
557 // Skip dbg_value instructions. These do not count.
558 if (TIB->isDebugValue()) {
559 while (TIB != TIE && TIB->isDebugValue())
564 if (FIB->isDebugValue()) {
565 while (FIB != FIE && FIB->isDebugValue())
570 if (!TIB->isIdenticalTo(FIB))
577 // Now, in preparation for counting duplicate instructions at the ends of the
578 // blocks, move the end iterators up past any branch instructions.
581 if (!TIE->getDesc().isBranch())
586 if (!FIE->getDesc().isBranch())
590 // If Dups1 includes all of a block, then don't count duplicate
591 // instructions at the end of the blocks.
592 if (TIB == TIE || FIB == FIE)
595 // Count duplicate instructions at the ends of the blocks.
596 while (TIE != TIB && FIE != FIB) {
597 // Skip dbg_value instructions. These do not count.
598 if (TIE->isDebugValue()) {
599 while (TIE != TIB && TIE->isDebugValue())
604 if (FIE->isDebugValue()) {
605 while (FIE != FIB && FIE->isDebugValue())
610 if (!TIE->isIdenticalTo(FIE))
620 /// ScanInstructions - Scan all the instructions in the block to determine if
621 /// the block is predicable. In most cases, that means all the instructions
622 /// in the block are isPredicable(). Also checks if the block contains any
623 /// instruction which can clobber a predicate (e.g. condition code register).
624 /// If so, the block is not predicable unless it's the last instruction.
625 void IfConverter::ScanInstructions(BBInfo &BBI) {
629 bool AlreadyPredicated = BBI.Predicate.size() > 0;
630 // First analyze the end of BB branches.
631 BBI.TrueBB = BBI.FalseBB = NULL;
634 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
635 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
637 if (BBI.BrCond.size()) {
638 // No false branch. This BB must end with a conditional branch and a
641 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
643 // Malformed bcc? True and false blocks are the same?
644 BBI.IsUnpredicable = true;
649 // Then scan all the instructions.
652 BBI.ClobbersPred = false;
653 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
655 if (I->isDebugValue())
658 const TargetInstrDesc &TID = I->getDesc();
659 if (TID.isNotDuplicable())
660 BBI.CannotBeCopied = true;
662 bool isPredicated = TII->isPredicated(I);
663 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
668 unsigned NumOps = TII->getNumMicroOps(&*I, InstrItins);
670 BBI.ExtraCost += NumOps-1;
671 } else if (!AlreadyPredicated) {
672 // FIXME: This instruction is already predicated before the
673 // if-conversion pass. It's probably something like a conditional move.
674 // Mark this block unpredicable for now.
675 BBI.IsUnpredicable = true;
680 if (BBI.ClobbersPred && !isPredicated) {
681 // Predicate modification instruction should end the block (except for
682 // already predicated instructions and end of block branches).
684 // A conditional branch is not predicable, but it may be eliminated.
688 // Predicate may have been modified, the subsequent (currently)
689 // unpredicated instructions cannot be correctly predicated.
690 BBI.IsUnpredicable = true;
694 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
695 // still potentially predicable.
696 std::vector<MachineOperand> PredDefs;
697 if (TII->DefinesPredicate(I, PredDefs))
698 BBI.ClobbersPred = true;
700 if (!TII->isPredicable(I)) {
701 BBI.IsUnpredicable = true;
707 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
708 /// predicated by the specified predicate.
709 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
710 SmallVectorImpl<MachineOperand> &Pred,
711 bool isTriangle, bool RevBranch) {
712 // If the block is dead or unpredicable, then it cannot be predicated.
713 if (BBI.IsDone || BBI.IsUnpredicable)
716 // If it is already predicated, check if its predicate subsumes the new
718 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
721 if (BBI.BrCond.size()) {
725 // Test predicate subsumption.
726 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
727 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
729 if (TII->ReverseBranchCondition(Cond))
732 if (TII->ReverseBranchCondition(RevPred) ||
733 !TII->SubsumesPredicate(Cond, RevPred))
740 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
741 /// the specified block. Record its successors and whether it looks like an
742 /// if-conversion candidate.
743 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
744 std::vector<IfcvtToken*> &Tokens) {
745 BBInfo &BBI = BBAnalysis[BB->getNumber()];
747 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
751 BBI.IsBeingAnalyzed = true;
753 ScanInstructions(BBI);
755 // Unanalyzable or ends with fallthrough or unconditional branch.
756 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
757 BBI.IsBeingAnalyzed = false;
758 BBI.IsAnalyzed = true;
762 // Do not ifcvt if either path is a back edge to the entry block.
763 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
764 BBI.IsBeingAnalyzed = false;
765 BBI.IsAnalyzed = true;
769 // Do not ifcvt if true and false fallthrough blocks are the same.
771 BBI.IsBeingAnalyzed = false;
772 BBI.IsAnalyzed = true;
776 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
777 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
779 if (TrueBBI.IsDone && FalseBBI.IsDone) {
780 BBI.IsBeingAnalyzed = false;
781 BBI.IsAnalyzed = true;
785 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
786 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
790 bool TNeedSub = TrueBBI.Predicate.size() > 0;
791 bool FNeedSub = FalseBBI.Predicate.size() > 0;
792 bool Enqueued = false;
794 // Try to predict the branch, using loop info to guide us.
795 // General heuristics are:
796 // - backedge -> 90% taken
797 // - early exit -> 20% taken
798 // - branch predictor confidence -> 90%
799 float Prediction = 0.5f;
800 float Confidence = 0.9f;
801 MachineLoop *Loop = MLI->getLoopFor(BB);
803 if (TrueBBI.BB == Loop->getHeader())
805 else if (FalseBBI.BB == Loop->getHeader())
808 MachineLoop *TrueLoop = MLI->getLoopFor(TrueBBI.BB);
809 MachineLoop *FalseLoop = MLI->getLoopFor(FalseBBI.BB);
810 if (!TrueLoop || TrueLoop->getParentLoop() == Loop)
812 else if (!FalseLoop || FalseLoop->getParentLoop() == Loop)
816 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
817 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
819 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
821 Prediction, Confidence) &&
822 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
823 FeasibilityAnalysis(FalseBBI, RevCond)) {
831 // Note TailBB can be empty.
832 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
837 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction, Confidence) &&
838 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
839 Prediction, Confidence) &&
840 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
848 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
852 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction, Confidence) &&
853 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
854 Prediction, Confidence) &&
855 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
856 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
860 if (ValidSimple(TrueBBI, Dups, Prediction, Confidence) &&
861 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
862 Prediction, Confidence) &&
863 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
864 // Simple (split, no rejoin):
871 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
876 // Try the other path...
877 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
878 1.0-Prediction, Confidence) &&
879 MeetIfcvtSizeLimit(*FalseBBI.BB,
880 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
881 1.0-Prediction, Confidence) &&
882 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
883 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
887 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
888 1.0-Prediction, Confidence) &&
889 MeetIfcvtSizeLimit(*FalseBBI.BB,
890 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
891 1.0-Prediction, Confidence) &&
892 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
893 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
897 if (ValidSimple(FalseBBI, Dups, 1.0-Prediction, Confidence) &&
898 MeetIfcvtSizeLimit(*FalseBBI.BB,
899 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
900 1.0-Prediction, Confidence) &&
901 FeasibilityAnalysis(FalseBBI, RevCond)) {
902 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
907 BBI.IsEnqueued = Enqueued;
908 BBI.IsBeingAnalyzed = false;
909 BBI.IsAnalyzed = true;
913 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
915 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
916 std::vector<IfcvtToken*> &Tokens) {
917 std::set<MachineBasicBlock*> Visited;
918 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
919 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
920 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
921 MachineBasicBlock *BB = *I;
922 AnalyzeBlock(BB, Tokens);
926 // Sort to favor more complex ifcvt scheme.
927 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
930 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
931 /// that all the intervening blocks are empty (given BB can fall through to its
933 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
934 MachineFunction::iterator PI = BB;
935 MachineFunction::iterator I = llvm::next(PI);
936 MachineFunction::iterator TI = ToBB;
937 MachineFunction::iterator E = BB->getParent()->end();
939 // Check isSuccessor to avoid case where the next block is empty, but
940 // it's not a successor.
941 if (I == E || !I->empty() || !PI->isSuccessor(I))
948 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
949 /// to determine if it can be if-converted. If predecessor is already enqueued,
951 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
952 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
953 E = BB->pred_end(); PI != E; ++PI) {
954 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
955 if (PBBI.IsDone || PBBI.BB == BB)
957 PBBI.IsAnalyzed = false;
958 PBBI.IsEnqueued = false;
962 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
964 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
965 const TargetInstrInfo *TII) {
966 DebugLoc dl; // FIXME: this is nowhere
967 SmallVector<MachineOperand, 0> NoCond;
968 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
971 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
973 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
974 MachineBasicBlock *TBB = NULL, *FBB = NULL;
975 SmallVector<MachineOperand, 4> Cond;
976 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
977 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
980 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
981 /// modeled as read + write (sort like two-address instructions). These
982 /// routines track register liveness and add implicit uses to if-converted
983 /// instructions to conform to the model.
984 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
985 const TargetRegisterInfo *TRI) {
986 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
987 E = BB->livein_end(); I != E; ++I) {
990 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
992 Redefs.insert(*Subreg);
996 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
997 const TargetRegisterInfo *TRI,
998 bool AddImpUse = false) {
999 SmallVector<unsigned, 4> Defs;
1000 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1001 const MachineOperand &MO = MI->getOperand(i);
1004 unsigned Reg = MO.getReg();
1008 Defs.push_back(Reg);
1009 else if (MO.isKill()) {
1011 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1015 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1016 unsigned Reg = Defs[i];
1017 if (Redefs.count(Reg)) {
1019 // Treat predicated update as read + write.
1020 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
1021 true/*IsImp*/,false/*IsKill*/));
1024 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1030 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1031 MachineBasicBlock::iterator E,
1032 SmallSet<unsigned,4> &Redefs,
1033 const TargetRegisterInfo *TRI) {
1035 UpdatePredRedefs(I, Redefs, TRI);
1040 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1042 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1043 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1044 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1045 BBInfo *CvtBBI = &TrueBBI;
1046 BBInfo *NextBBI = &FalseBBI;
1048 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1049 if (Kind == ICSimpleFalse)
1050 std::swap(CvtBBI, NextBBI);
1052 if (CvtBBI->IsDone ||
1053 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1054 // Something has changed. It's no longer safe to predicate this block.
1055 BBI.IsAnalyzed = false;
1056 CvtBBI->IsAnalyzed = false;
1060 if (Kind == ICSimpleFalse)
1061 if (TII->ReverseBranchCondition(Cond))
1062 assert(false && "Unable to reverse branch condition!");
1064 // Initialize liveins to the first BB. These are potentiall redefined by
1065 // predicated instructions.
1066 SmallSet<unsigned, 4> Redefs;
1067 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1068 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1070 if (CvtBBI->BB->pred_size() > 1) {
1071 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1072 // Copy instructions in the true block, predicate them, and add them to
1074 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1076 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1078 // Merge converted block into entry block.
1079 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1080 MergeBlocks(BBI, *CvtBBI);
1083 bool IterIfcvt = true;
1084 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1085 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1086 BBI.HasFallThrough = false;
1087 // Now ifcvt'd block will look like this:
1094 // We cannot further ifcvt this block because the unconditional branch
1095 // will have to be predicated on the new condition, that will not be
1096 // available if cmp executes.
1100 RemoveExtraEdges(BBI);
1102 // Update block info. BB can be iteratively if-converted.
1105 InvalidatePreds(BBI.BB);
1106 CvtBBI->IsDone = true;
1108 // FIXME: Must maintain LiveIns.
1112 /// IfConvertTriangle - If convert a triangle sub-CFG.
1114 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1115 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1116 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1117 BBInfo *CvtBBI = &TrueBBI;
1118 BBInfo *NextBBI = &FalseBBI;
1119 DebugLoc dl; // FIXME: this is nowhere
1121 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1122 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1123 std::swap(CvtBBI, NextBBI);
1125 if (CvtBBI->IsDone ||
1126 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1127 // Something has changed. It's no longer safe to predicate this block.
1128 BBI.IsAnalyzed = false;
1129 CvtBBI->IsAnalyzed = false;
1133 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1134 if (TII->ReverseBranchCondition(Cond))
1135 assert(false && "Unable to reverse branch condition!");
1137 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1138 if (ReverseBranchCondition(*CvtBBI)) {
1139 // BB has been changed, modify its predecessors (except for this
1140 // one) so they don't get ifcvt'ed based on bad intel.
1141 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1142 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1143 MachineBasicBlock *PBB = *PI;
1146 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1147 if (PBBI.IsEnqueued) {
1148 PBBI.IsAnalyzed = false;
1149 PBBI.IsEnqueued = false;
1155 // Initialize liveins to the first BB. These are potentially redefined by
1156 // predicated instructions.
1157 SmallSet<unsigned, 4> Redefs;
1158 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1159 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1161 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1162 if (CvtBBI->BB->pred_size() > 1) {
1163 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1164 // Copy instructions in the true block, predicate them, and add them to
1166 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1168 // Predicate the 'true' block after removing its branch.
1169 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1170 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1172 // Now merge the entry of the triangle with the true block.
1173 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1174 MergeBlocks(BBI, *CvtBBI, false);
1177 // If 'true' block has a 'false' successor, add an exit branch to it.
1179 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1180 CvtBBI->BrCond.end());
1181 if (TII->ReverseBranchCondition(RevCond))
1182 assert(false && "Unable to reverse branch condition!");
1183 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1184 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1187 // Merge in the 'false' block if the 'false' block has no other
1188 // predecessors. Otherwise, add an unconditional branch to 'false'.
1189 bool FalseBBDead = false;
1190 bool IterIfcvt = true;
1191 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1192 if (!isFallThrough) {
1193 // Only merge them if the true block does not fallthrough to the false
1194 // block. By not merging them, we make it possible to iteratively
1195 // ifcvt the blocks.
1196 if (!HasEarlyExit &&
1197 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1198 MergeBlocks(BBI, *NextBBI);
1201 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1202 BBI.HasFallThrough = false;
1204 // Mixed predicated and unpredicated code. This cannot be iteratively
1209 RemoveExtraEdges(BBI);
1211 // Update block info. BB can be iteratively if-converted.
1214 InvalidatePreds(BBI.BB);
1215 CvtBBI->IsDone = true;
1217 NextBBI->IsDone = true;
1219 // FIXME: Must maintain LiveIns.
1223 /// IfConvertDiamond - If convert a diamond sub-CFG.
1225 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1226 unsigned NumDups1, unsigned NumDups2) {
1227 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1228 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1229 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1230 // True block must fall through or end with an unanalyzable terminator.
1232 if (blockAlwaysFallThrough(TrueBBI))
1233 TailBB = FalseBBI.TrueBB;
1234 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1237 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1238 TrueBBI.BB->pred_size() > 1 ||
1239 FalseBBI.BB->pred_size() > 1) {
1240 // Something has changed. It's no longer safe to predicate these blocks.
1241 BBI.IsAnalyzed = false;
1242 TrueBBI.IsAnalyzed = false;
1243 FalseBBI.IsAnalyzed = false;
1247 // Put the predicated instructions from the 'true' block before the
1248 // instructions from the 'false' block, unless the true block would clobber
1249 // the predicate, in which case, do the opposite.
1250 BBInfo *BBI1 = &TrueBBI;
1251 BBInfo *BBI2 = &FalseBBI;
1252 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1253 if (TII->ReverseBranchCondition(RevCond))
1254 assert(false && "Unable to reverse branch condition!");
1255 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1256 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1258 // Figure out the more profitable ordering.
1259 bool DoSwap = false;
1260 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1262 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1263 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1267 std::swap(BBI1, BBI2);
1268 std::swap(Cond1, Cond2);
1271 // Remove the conditional branch from entry to the blocks.
1272 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1274 // Initialize liveins to the first BB. These are potentially redefined by
1275 // predicated instructions.
1276 SmallSet<unsigned, 4> Redefs;
1277 InitPredRedefs(BBI1->BB, Redefs, TRI);
1279 // Remove the duplicated instructions at the beginnings of both paths.
1280 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1281 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1282 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1283 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1284 // Skip dbg_value instructions
1285 while (DI1 != DIE1 && DI1->isDebugValue())
1287 while (DI2 != DIE2 && DI2->isDebugValue())
1289 BBI1->NonPredSize -= NumDups1;
1290 BBI2->NonPredSize -= NumDups1;
1292 // Skip past the dups on each side separately since there may be
1293 // differing dbg_value entries.
1294 for (unsigned i = 0; i < NumDups1; ++DI1) {
1295 if (!DI1->isDebugValue())
1298 while (NumDups1 != 0) {
1300 if (!DI2->isDebugValue())
1304 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1305 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1306 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1308 // Predicate the 'true' block after removing its branch.
1309 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1310 DI1 = BBI1->BB->end();
1311 for (unsigned i = 0; i != NumDups2; ) {
1312 // NumDups2 only counted non-dbg_value instructions, so this won't
1313 // run off the head of the list.
1314 assert (DI1 != BBI1->BB->begin());
1316 // skip dbg_value instructions
1317 if (!DI1->isDebugValue())
1320 BBI1->BB->erase(DI1, BBI1->BB->end());
1321 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
1323 // Predicate the 'false' block.
1324 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1325 DI2 = BBI2->BB->end();
1326 while (NumDups2 != 0) {
1327 // NumDups2 only counted non-dbg_value instructions, so this won't
1328 // run off the head of the list.
1329 assert (DI2 != BBI2->BB->begin());
1331 // skip dbg_value instructions
1332 if (!DI2->isDebugValue())
1335 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1337 // Merge the true block into the entry of the diamond.
1338 MergeBlocks(BBI, *BBI1, TailBB == 0);
1339 MergeBlocks(BBI, *BBI2, TailBB == 0);
1341 // If the if-converted block falls through or unconditionally branches into
1342 // the tail block, and the tail block does not have other predecessors, then
1343 // fold the tail block in as well. Otherwise, unless it falls through to the
1344 // tail, add a unconditional branch to it.
1346 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1347 bool CanMergeTail = !TailBBI.HasFallThrough;
1348 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1349 // check if there are any other predecessors besides those.
1350 unsigned NumPreds = TailBB->pred_size();
1352 CanMergeTail = false;
1353 else if (NumPreds == 1 && CanMergeTail) {
1354 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1355 if (*PI != BBI1->BB && *PI != BBI2->BB)
1356 CanMergeTail = false;
1359 MergeBlocks(BBI, TailBBI);
1360 TailBBI.IsDone = true;
1362 BBI.BB->addSuccessor(TailBB);
1363 InsertUncondBranch(BBI.BB, TailBB, TII);
1364 BBI.HasFallThrough = false;
1368 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1369 // which can happen here if TailBB is unanalyzable and is merged, so
1370 // explicitly remove BBI1 and BBI2 as successors.
1371 BBI.BB->removeSuccessor(BBI1->BB);
1372 BBI.BB->removeSuccessor(BBI2->BB);
1373 RemoveExtraEdges(BBI);
1375 // Update block info.
1376 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1377 InvalidatePreds(BBI.BB);
1379 // FIXME: Must maintain LiveIns.
1383 /// PredicateBlock - Predicate instructions from the start of the block to the
1384 /// specified end with the specified condition.
1385 void IfConverter::PredicateBlock(BBInfo &BBI,
1386 MachineBasicBlock::iterator E,
1387 SmallVectorImpl<MachineOperand> &Cond,
1388 SmallSet<unsigned, 4> &Redefs) {
1389 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1390 if (I->isDebugValue() || TII->isPredicated(I))
1392 if (!TII->PredicateInstruction(I, Cond)) {
1394 dbgs() << "Unable to predicate " << *I << "!\n";
1396 llvm_unreachable(0);
1399 // If the predicated instruction now redefines a register as the result of
1400 // if-conversion, add an implicit kill.
1401 UpdatePredRedefs(I, Redefs, TRI, true);
1404 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1406 BBI.IsAnalyzed = false;
1407 BBI.NonPredSize = 0;
1412 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1413 /// the destination block. Skip end of block branches if IgnoreBr is true.
1414 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1415 SmallVectorImpl<MachineOperand> &Cond,
1416 SmallSet<unsigned, 4> &Redefs,
1418 MachineFunction &MF = *ToBBI.BB->getParent();
1420 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1421 E = FromBBI.BB->end(); I != E; ++I) {
1422 const TargetInstrDesc &TID = I->getDesc();
1423 // Do not copy the end of the block branches.
1424 if (IgnoreBr && TID.isBranch())
1427 MachineInstr *MI = MF.CloneMachineInstr(I);
1428 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1429 ToBBI.NonPredSize++;
1430 unsigned NumOps = TII->getNumMicroOps(MI, InstrItins);
1432 ToBBI.ExtraCost += NumOps-1;
1434 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1435 if (!TII->PredicateInstruction(MI, Cond)) {
1437 dbgs() << "Unable to predicate " << *I << "!\n";
1439 llvm_unreachable(0);
1443 // If the predicated instruction now redefines a register as the result of
1444 // if-conversion, add an implicit kill.
1445 UpdatePredRedefs(MI, Redefs, TRI, true);
1449 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1450 FromBBI.BB->succ_end());
1451 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1452 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1454 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1455 MachineBasicBlock *Succ = Succs[i];
1456 // Fallthrough edge can't be transferred.
1457 if (Succ == FallThrough)
1459 ToBBI.BB->addSuccessor(Succ);
1463 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1464 std::back_inserter(ToBBI.Predicate));
1465 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1467 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1468 ToBBI.IsAnalyzed = false;
1473 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1474 /// This will leave FromBB as an empty block, so remove all of its
1475 /// successor edges except for the fall-through edge. If AddEdges is true,
1476 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1478 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1479 ToBBI.BB->splice(ToBBI.BB->end(),
1480 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1482 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1483 FromBBI.BB->succ_end());
1484 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1485 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1487 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1488 MachineBasicBlock *Succ = Succs[i];
1489 // Fallthrough edge can't be transferred.
1490 if (Succ == FallThrough)
1492 FromBBI.BB->removeSuccessor(Succ);
1494 ToBBI.BB->addSuccessor(Succ);
1497 // Now FromBBI always falls through to the next block!
1498 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1499 FromBBI.BB->addSuccessor(NBB);
1501 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1502 std::back_inserter(ToBBI.Predicate));
1503 FromBBI.Predicate.clear();
1505 ToBBI.NonPredSize += FromBBI.NonPredSize;
1506 ToBBI.ExtraCost += FromBBI.ExtraCost;
1507 FromBBI.NonPredSize = 0;
1508 FromBBI.ExtraCost = 0;
1510 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1511 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1512 ToBBI.IsAnalyzed = false;
1513 FromBBI.IsAnalyzed = false;