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;
524 MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
525 const TargetInstrInfo *TII) {
526 MachineBasicBlock::iterator I = BB->end();
527 while (I != BB->begin()) {
529 if (!I->getDesc().isBranch())
535 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
536 /// with their common predecessor) forms a valid diamond shape for ifcvt.
537 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
538 unsigned &Dups1, unsigned &Dups2) const {
540 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
541 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
544 MachineBasicBlock *TT = TrueBBI.TrueBB;
545 MachineBasicBlock *FT = FalseBBI.TrueBB;
547 if (!TT && blockAlwaysFallThrough(TrueBBI))
548 TT = getNextBlock(TrueBBI.BB);
549 if (!FT && blockAlwaysFallThrough(FalseBBI))
550 FT = getNextBlock(FalseBBI.BB);
553 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
555 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
558 // FIXME: Allow true block to have an early exit?
559 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
560 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
563 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
564 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
565 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
566 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
567 // Skip dbg_value instructions
568 while (TI != TIE && TI->isDebugValue())
570 while (FI != FIE && FI->isDebugValue())
572 while (TI != TIE && FI != FIE) {
573 // Skip dbg_value instructions. These do not count.
574 if (TI->isDebugValue()) {
575 while (TI != TIE && TI->isDebugValue())
580 if (FI->isDebugValue()) {
581 while (FI != FIE && FI->isDebugValue())
586 if (!TI->isIdenticalTo(FI))
593 TI = firstNonBranchInst(TrueBBI.BB, TII);
594 FI = firstNonBranchInst(FalseBBI.BB, TII);
595 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
596 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
597 // Skip dbg_value instructions at end of the bb's.
598 while (TI != TIB && TI->isDebugValue())
600 while (FI != FIB && FI->isDebugValue())
602 while (TI != TIB && FI != FIB) {
603 // Skip dbg_value instructions. These do not count.
604 if (TI->isDebugValue()) {
605 while (TI != TIB && TI->isDebugValue())
610 if (FI->isDebugValue()) {
611 while (FI != FIB && FI->isDebugValue())
616 if (!TI->isIdenticalTo(FI))
626 /// ScanInstructions - Scan all the instructions in the block to determine if
627 /// the block is predicable. In most cases, that means all the instructions
628 /// in the block are isPredicable(). Also checks if the block contains any
629 /// instruction which can clobber a predicate (e.g. condition code register).
630 /// If so, the block is not predicable unless it's the last instruction.
631 void IfConverter::ScanInstructions(BBInfo &BBI) {
635 bool AlreadyPredicated = BBI.Predicate.size() > 0;
636 // First analyze the end of BB branches.
637 BBI.TrueBB = BBI.FalseBB = NULL;
640 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
641 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
643 if (BBI.BrCond.size()) {
644 // No false branch. This BB must end with a conditional branch and a
647 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
649 // Malformed bcc? True and false blocks are the same?
650 BBI.IsUnpredicable = true;
655 // Then scan all the instructions.
658 BBI.ClobbersPred = false;
659 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
661 if (I->isDebugValue())
664 const TargetInstrDesc &TID = I->getDesc();
665 if (TID.isNotDuplicable())
666 BBI.CannotBeCopied = true;
668 bool isPredicated = TII->isPredicated(I);
669 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
674 unsigned NumOps = TII->getNumMicroOps(&*I, InstrItins);
676 BBI.ExtraCost += NumOps-1;
677 } else if (!AlreadyPredicated) {
678 // FIXME: This instruction is already predicated before the
679 // if-conversion pass. It's probably something like a conditional move.
680 // Mark this block unpredicable for now.
681 BBI.IsUnpredicable = true;
686 if (BBI.ClobbersPred && !isPredicated) {
687 // Predicate modification instruction should end the block (except for
688 // already predicated instructions and end of block branches).
690 // A conditional branch is not predicable, but it may be eliminated.
694 // Predicate may have been modified, the subsequent (currently)
695 // unpredicated instructions cannot be correctly predicated.
696 BBI.IsUnpredicable = true;
700 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
701 // still potentially predicable.
702 std::vector<MachineOperand> PredDefs;
703 if (TII->DefinesPredicate(I, PredDefs))
704 BBI.ClobbersPred = true;
706 if (!TII->isPredicable(I)) {
707 BBI.IsUnpredicable = true;
713 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
714 /// predicated by the specified predicate.
715 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
716 SmallVectorImpl<MachineOperand> &Pred,
717 bool isTriangle, bool RevBranch) {
718 // If the block is dead or unpredicable, then it cannot be predicated.
719 if (BBI.IsDone || BBI.IsUnpredicable)
722 // If it is already predicated, check if its predicate subsumes the new
724 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
727 if (BBI.BrCond.size()) {
731 // Test predicate subsumption.
732 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
733 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
735 if (TII->ReverseBranchCondition(Cond))
738 if (TII->ReverseBranchCondition(RevPred) ||
739 !TII->SubsumesPredicate(Cond, RevPred))
746 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
747 /// the specified block. Record its successors and whether it looks like an
748 /// if-conversion candidate.
749 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
750 std::vector<IfcvtToken*> &Tokens) {
751 BBInfo &BBI = BBAnalysis[BB->getNumber()];
753 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
757 BBI.IsBeingAnalyzed = true;
759 ScanInstructions(BBI);
761 // Unanalyzable or ends with fallthrough or unconditional branch.
762 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
763 BBI.IsBeingAnalyzed = false;
764 BBI.IsAnalyzed = true;
768 // Do not ifcvt if either path is a back edge to the entry block.
769 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
770 BBI.IsBeingAnalyzed = false;
771 BBI.IsAnalyzed = true;
775 // Do not ifcvt if true and false fallthrough blocks are the same.
777 BBI.IsBeingAnalyzed = false;
778 BBI.IsAnalyzed = true;
782 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
783 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
785 if (TrueBBI.IsDone && FalseBBI.IsDone) {
786 BBI.IsBeingAnalyzed = false;
787 BBI.IsAnalyzed = true;
791 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
792 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
796 bool TNeedSub = TrueBBI.Predicate.size() > 0;
797 bool FNeedSub = FalseBBI.Predicate.size() > 0;
798 bool Enqueued = false;
800 // Try to predict the branch, using loop info to guide us.
801 // General heuristics are:
802 // - backedge -> 90% taken
803 // - early exit -> 20% taken
804 // - branch predictor confidence -> 90%
805 float Prediction = 0.5f;
806 float Confidence = 0.9f;
807 MachineLoop *Loop = MLI->getLoopFor(BB);
809 if (TrueBBI.BB == Loop->getHeader())
811 else if (FalseBBI.BB == Loop->getHeader())
814 MachineLoop *TrueLoop = MLI->getLoopFor(TrueBBI.BB);
815 MachineLoop *FalseLoop = MLI->getLoopFor(FalseBBI.BB);
816 if (!TrueLoop || TrueLoop->getParentLoop() == Loop)
818 else if (!FalseLoop || FalseLoop->getParentLoop() == Loop)
822 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
823 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
825 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
827 Prediction, Confidence) &&
828 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
829 FeasibilityAnalysis(FalseBBI, RevCond)) {
837 // Note TailBB can be empty.
838 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
843 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction, Confidence) &&
844 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
845 Prediction, Confidence) &&
846 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
854 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
858 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction, Confidence) &&
859 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
860 Prediction, Confidence) &&
861 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
862 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
866 if (ValidSimple(TrueBBI, Dups, Prediction, Confidence) &&
867 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
868 Prediction, Confidence) &&
869 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
870 // Simple (split, no rejoin):
877 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
882 // Try the other path...
883 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
884 1.0-Prediction, Confidence) &&
885 MeetIfcvtSizeLimit(*FalseBBI.BB,
886 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
887 1.0-Prediction, Confidence) &&
888 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
889 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
893 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
894 1.0-Prediction, Confidence) &&
895 MeetIfcvtSizeLimit(*FalseBBI.BB,
896 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
897 1.0-Prediction, Confidence) &&
898 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
899 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
903 if (ValidSimple(FalseBBI, Dups, 1.0-Prediction, Confidence) &&
904 MeetIfcvtSizeLimit(*FalseBBI.BB,
905 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
906 1.0-Prediction, Confidence) &&
907 FeasibilityAnalysis(FalseBBI, RevCond)) {
908 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
913 BBI.IsEnqueued = Enqueued;
914 BBI.IsBeingAnalyzed = false;
915 BBI.IsAnalyzed = true;
919 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
921 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
922 std::vector<IfcvtToken*> &Tokens) {
923 std::set<MachineBasicBlock*> Visited;
924 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
925 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
926 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
927 MachineBasicBlock *BB = *I;
928 AnalyzeBlock(BB, Tokens);
932 // Sort to favor more complex ifcvt scheme.
933 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
936 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
937 /// that all the intervening blocks are empty (given BB can fall through to its
939 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
940 MachineFunction::iterator PI = BB;
941 MachineFunction::iterator I = llvm::next(PI);
942 MachineFunction::iterator TI = ToBB;
943 MachineFunction::iterator E = BB->getParent()->end();
945 // Check isSuccessor to avoid case where the next block is empty, but
946 // it's not a successor.
947 if (I == E || !I->empty() || !PI->isSuccessor(I))
954 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
955 /// to determine if it can be if-converted. If predecessor is already enqueued,
957 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
958 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
959 E = BB->pred_end(); PI != E; ++PI) {
960 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
961 if (PBBI.IsDone || PBBI.BB == BB)
963 PBBI.IsAnalyzed = false;
964 PBBI.IsEnqueued = false;
968 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
970 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
971 const TargetInstrInfo *TII) {
972 DebugLoc dl; // FIXME: this is nowhere
973 SmallVector<MachineOperand, 0> NoCond;
974 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
977 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
979 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
980 MachineBasicBlock *TBB = NULL, *FBB = NULL;
981 SmallVector<MachineOperand, 4> Cond;
982 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
983 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
986 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
987 /// modeled as read + write (sort like two-address instructions). These
988 /// routines track register liveness and add implicit uses to if-converted
989 /// instructions to conform to the model.
990 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
991 const TargetRegisterInfo *TRI) {
992 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
993 E = BB->livein_end(); I != E; ++I) {
996 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
998 Redefs.insert(*Subreg);
1002 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
1003 const TargetRegisterInfo *TRI,
1004 bool AddImpUse = false) {
1005 SmallVector<unsigned, 4> Defs;
1006 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1007 const MachineOperand &MO = MI->getOperand(i);
1010 unsigned Reg = MO.getReg();
1014 Defs.push_back(Reg);
1015 else if (MO.isKill()) {
1017 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1021 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1022 unsigned Reg = Defs[i];
1023 if (Redefs.count(Reg)) {
1025 // Treat predicated update as read + write.
1026 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
1027 true/*IsImp*/,false/*IsKill*/));
1030 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1036 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1037 MachineBasicBlock::iterator E,
1038 SmallSet<unsigned,4> &Redefs,
1039 const TargetRegisterInfo *TRI) {
1041 UpdatePredRedefs(I, Redefs, TRI);
1046 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1048 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1049 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1050 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1051 BBInfo *CvtBBI = &TrueBBI;
1052 BBInfo *NextBBI = &FalseBBI;
1054 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1055 if (Kind == ICSimpleFalse)
1056 std::swap(CvtBBI, NextBBI);
1058 if (CvtBBI->IsDone ||
1059 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1060 // Something has changed. It's no longer safe to predicate this block.
1061 BBI.IsAnalyzed = false;
1062 CvtBBI->IsAnalyzed = false;
1066 if (Kind == ICSimpleFalse)
1067 if (TII->ReverseBranchCondition(Cond))
1068 assert(false && "Unable to reverse branch condition!");
1070 // Initialize liveins to the first BB. These are potentiall redefined by
1071 // predicated instructions.
1072 SmallSet<unsigned, 4> Redefs;
1073 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1074 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1076 if (CvtBBI->BB->pred_size() > 1) {
1077 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1078 // Copy instructions in the true block, predicate them, and add them to
1080 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1082 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1084 // Merge converted block into entry block.
1085 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1086 MergeBlocks(BBI, *CvtBBI);
1089 bool IterIfcvt = true;
1090 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1091 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1092 BBI.HasFallThrough = false;
1093 // Now ifcvt'd block will look like this:
1100 // We cannot further ifcvt this block because the unconditional branch
1101 // will have to be predicated on the new condition, that will not be
1102 // available if cmp executes.
1106 RemoveExtraEdges(BBI);
1108 // Update block info. BB can be iteratively if-converted.
1111 InvalidatePreds(BBI.BB);
1112 CvtBBI->IsDone = true;
1114 // FIXME: Must maintain LiveIns.
1118 /// IfConvertTriangle - If convert a triangle sub-CFG.
1120 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1121 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1122 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1123 BBInfo *CvtBBI = &TrueBBI;
1124 BBInfo *NextBBI = &FalseBBI;
1125 DebugLoc dl; // FIXME: this is nowhere
1127 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1128 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1129 std::swap(CvtBBI, NextBBI);
1131 if (CvtBBI->IsDone ||
1132 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1133 // Something has changed. It's no longer safe to predicate this block.
1134 BBI.IsAnalyzed = false;
1135 CvtBBI->IsAnalyzed = false;
1139 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1140 if (TII->ReverseBranchCondition(Cond))
1141 assert(false && "Unable to reverse branch condition!");
1143 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1144 if (ReverseBranchCondition(*CvtBBI)) {
1145 // BB has been changed, modify its predecessors (except for this
1146 // one) so they don't get ifcvt'ed based on bad intel.
1147 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1148 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1149 MachineBasicBlock *PBB = *PI;
1152 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1153 if (PBBI.IsEnqueued) {
1154 PBBI.IsAnalyzed = false;
1155 PBBI.IsEnqueued = false;
1161 // Initialize liveins to the first BB. These are potentially redefined by
1162 // predicated instructions.
1163 SmallSet<unsigned, 4> Redefs;
1164 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1165 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1167 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1168 if (CvtBBI->BB->pred_size() > 1) {
1169 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1170 // Copy instructions in the true block, predicate them, and add them to
1172 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1174 // Predicate the 'true' block after removing its branch.
1175 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1176 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1178 // Now merge the entry of the triangle with the true block.
1179 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1180 MergeBlocks(BBI, *CvtBBI, false);
1183 // If 'true' block has a 'false' successor, add an exit branch to it.
1185 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1186 CvtBBI->BrCond.end());
1187 if (TII->ReverseBranchCondition(RevCond))
1188 assert(false && "Unable to reverse branch condition!");
1189 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1190 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1193 // Merge in the 'false' block if the 'false' block has no other
1194 // predecessors. Otherwise, add an unconditional branch to 'false'.
1195 bool FalseBBDead = false;
1196 bool IterIfcvt = true;
1197 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1198 if (!isFallThrough) {
1199 // Only merge them if the true block does not fallthrough to the false
1200 // block. By not merging them, we make it possible to iteratively
1201 // ifcvt the blocks.
1202 if (!HasEarlyExit &&
1203 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1204 MergeBlocks(BBI, *NextBBI);
1207 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1208 BBI.HasFallThrough = false;
1210 // Mixed predicated and unpredicated code. This cannot be iteratively
1215 RemoveExtraEdges(BBI);
1217 // Update block info. BB can be iteratively if-converted.
1220 InvalidatePreds(BBI.BB);
1221 CvtBBI->IsDone = true;
1223 NextBBI->IsDone = true;
1225 // FIXME: Must maintain LiveIns.
1229 /// IfConvertDiamond - If convert a diamond sub-CFG.
1231 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1232 unsigned NumDups1, unsigned NumDups2) {
1233 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1234 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1235 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1236 // True block must fall through or end with an unanalyzable terminator.
1238 if (blockAlwaysFallThrough(TrueBBI))
1239 TailBB = FalseBBI.TrueBB;
1240 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1243 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1244 TrueBBI.BB->pred_size() > 1 ||
1245 FalseBBI.BB->pred_size() > 1) {
1246 // Something has changed. It's no longer safe to predicate these blocks.
1247 BBI.IsAnalyzed = false;
1248 TrueBBI.IsAnalyzed = false;
1249 FalseBBI.IsAnalyzed = false;
1253 // Put the predicated instructions from the 'true' block before the
1254 // instructions from the 'false' block, unless the true block would clobber
1255 // the predicate, in which case, do the opposite.
1256 BBInfo *BBI1 = &TrueBBI;
1257 BBInfo *BBI2 = &FalseBBI;
1258 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1259 if (TII->ReverseBranchCondition(RevCond))
1260 assert(false && "Unable to reverse branch condition!");
1261 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1262 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1264 // Figure out the more profitable ordering.
1265 bool DoSwap = false;
1266 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1268 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1269 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1273 std::swap(BBI1, BBI2);
1274 std::swap(Cond1, Cond2);
1277 // Remove the conditional branch from entry to the blocks.
1278 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1280 // Initialize liveins to the first BB. These are potentially redefined by
1281 // predicated instructions.
1282 SmallSet<unsigned, 4> Redefs;
1283 InitPredRedefs(BBI1->BB, Redefs, TRI);
1285 // Remove the duplicated instructions at the beginnings of both paths.
1286 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1287 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1288 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1289 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1290 // Skip dbg_value instructions
1291 while (DI1 != DIE1 && DI1->isDebugValue())
1293 while (DI2 != DIE2 && DI2->isDebugValue())
1295 BBI1->NonPredSize -= NumDups1;
1296 BBI2->NonPredSize -= NumDups1;
1298 // Skip past the dups on each side separately since there may be
1299 // differing dbg_value entries.
1300 for (unsigned i = 0; i < NumDups1; ++DI1) {
1301 if (!DI1->isDebugValue())
1304 while (NumDups1 != 0) {
1306 if (!DI2->isDebugValue())
1310 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1311 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1312 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1314 // Predicate the 'true' block after removing its branch.
1315 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1316 DI1 = BBI1->BB->end();
1317 for (unsigned i = 0; i != NumDups2; ) {
1318 // NumDups2 only counted non-dbg_value instructions, so this won't
1319 // run off the head of the list.
1320 assert (DI1 != BBI1->BB->begin());
1322 // skip dbg_value instructions
1323 if (!DI1->isDebugValue())
1326 BBI1->BB->erase(DI1, BBI1->BB->end());
1327 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
1329 // Predicate the 'false' block.
1330 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1331 DI2 = BBI2->BB->end();
1332 while (NumDups2 != 0) {
1333 // NumDups2 only counted non-dbg_value instructions, so this won't
1334 // run off the head of the list.
1335 assert (DI2 != BBI2->BB->begin());
1337 // skip dbg_value instructions
1338 if (!DI2->isDebugValue())
1341 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1343 // Merge the true block into the entry of the diamond.
1344 MergeBlocks(BBI, *BBI1, TailBB == 0);
1345 MergeBlocks(BBI, *BBI2, TailBB == 0);
1347 // If the if-converted block falls through or unconditionally branches into
1348 // the tail block, and the tail block does not have other predecessors, then
1349 // fold the tail block in as well. Otherwise, unless it falls through to the
1350 // tail, add a unconditional branch to it.
1352 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1353 bool CanMergeTail = !TailBBI.HasFallThrough;
1354 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1355 // check if there are any other predecessors besides those.
1356 unsigned NumPreds = TailBB->pred_size();
1358 CanMergeTail = false;
1359 else if (NumPreds == 1 && CanMergeTail) {
1360 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1361 if (*PI != BBI1->BB && *PI != BBI2->BB)
1362 CanMergeTail = false;
1365 MergeBlocks(BBI, TailBBI);
1366 TailBBI.IsDone = true;
1368 BBI.BB->addSuccessor(TailBB);
1369 InsertUncondBranch(BBI.BB, TailBB, TII);
1370 BBI.HasFallThrough = false;
1374 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1375 // which can happen here if TailBB is unanalyzable and is merged, so
1376 // explicitly remove BBI1 and BBI2 as successors.
1377 BBI.BB->removeSuccessor(BBI1->BB);
1378 BBI.BB->removeSuccessor(BBI2->BB);
1379 RemoveExtraEdges(BBI);
1381 // Update block info.
1382 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1383 InvalidatePreds(BBI.BB);
1385 // FIXME: Must maintain LiveIns.
1389 /// PredicateBlock - Predicate instructions from the start of the block to the
1390 /// specified end with the specified condition.
1391 void IfConverter::PredicateBlock(BBInfo &BBI,
1392 MachineBasicBlock::iterator E,
1393 SmallVectorImpl<MachineOperand> &Cond,
1394 SmallSet<unsigned, 4> &Redefs) {
1395 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1396 if (I->isDebugValue() || TII->isPredicated(I))
1398 if (!TII->PredicateInstruction(I, Cond)) {
1400 dbgs() << "Unable to predicate " << *I << "!\n";
1402 llvm_unreachable(0);
1405 // If the predicated instruction now redefines a register as the result of
1406 // if-conversion, add an implicit kill.
1407 UpdatePredRedefs(I, Redefs, TRI, true);
1410 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1412 BBI.IsAnalyzed = false;
1413 BBI.NonPredSize = 0;
1418 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1419 /// the destination block. Skip end of block branches if IgnoreBr is true.
1420 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1421 SmallVectorImpl<MachineOperand> &Cond,
1422 SmallSet<unsigned, 4> &Redefs,
1424 MachineFunction &MF = *ToBBI.BB->getParent();
1426 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1427 E = FromBBI.BB->end(); I != E; ++I) {
1428 const TargetInstrDesc &TID = I->getDesc();
1429 // Do not copy the end of the block branches.
1430 if (IgnoreBr && TID.isBranch())
1433 MachineInstr *MI = MF.CloneMachineInstr(I);
1434 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1435 ToBBI.NonPredSize++;
1436 unsigned NumOps = TII->getNumMicroOps(MI, InstrItins);
1438 ToBBI.ExtraCost += NumOps-1;
1440 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1441 if (!TII->PredicateInstruction(MI, Cond)) {
1443 dbgs() << "Unable to predicate " << *I << "!\n";
1445 llvm_unreachable(0);
1449 // If the predicated instruction now redefines a register as the result of
1450 // if-conversion, add an implicit kill.
1451 UpdatePredRedefs(MI, Redefs, TRI, true);
1455 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1456 FromBBI.BB->succ_end());
1457 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1458 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1460 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1461 MachineBasicBlock *Succ = Succs[i];
1462 // Fallthrough edge can't be transferred.
1463 if (Succ == FallThrough)
1465 ToBBI.BB->addSuccessor(Succ);
1469 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1470 std::back_inserter(ToBBI.Predicate));
1471 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1473 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1474 ToBBI.IsAnalyzed = false;
1479 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1480 /// This will leave FromBB as an empty block, so remove all of its
1481 /// successor edges except for the fall-through edge. If AddEdges is true,
1482 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1484 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1485 ToBBI.BB->splice(ToBBI.BB->end(),
1486 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1488 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1489 FromBBI.BB->succ_end());
1490 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1491 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1493 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1494 MachineBasicBlock *Succ = Succs[i];
1495 // Fallthrough edge can't be transferred.
1496 if (Succ == FallThrough)
1498 FromBBI.BB->removeSuccessor(Succ);
1500 ToBBI.BB->addSuccessor(Succ);
1503 // Now FromBBI always falls through to the next block!
1504 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1505 FromBBI.BB->addSuccessor(NBB);
1507 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1508 std::back_inserter(ToBBI.Predicate));
1509 FromBBI.Predicate.clear();
1511 ToBBI.NonPredSize += FromBBI.NonPredSize;
1512 ToBBI.ExtraCost += FromBBI.ExtraCost;
1513 FromBBI.NonPredSize = 0;
1514 FromBBI.ExtraCost = 0;
1516 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1517 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1518 ToBBI.IsAnalyzed = false;
1519 FromBBI.IsAnalyzed = false;