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 "llvm/CodeGen/Passes.h"
16 #include "BranchFolding.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/TargetSchedule.h"
26 #include "llvm/MC/MCInstrItineraries.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
39 // Hidden options for help debugging.
40 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
41 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
42 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
43 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
44 cl::init(false), cl::Hidden);
45 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
46 cl::init(false), cl::Hidden);
47 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
48 cl::init(false), cl::Hidden);
49 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
50 cl::init(false), cl::Hidden);
51 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
52 cl::init(false), cl::Hidden);
53 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
54 cl::init(false), cl::Hidden);
55 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
56 cl::init(false), cl::Hidden);
57 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
58 cl::init(true), cl::Hidden);
60 STATISTIC(NumSimple, "Number of simple if-conversions performed");
61 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
62 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
63 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
64 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
65 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
66 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
67 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
68 STATISTIC(NumDupBBs, "Number of duplicated blocks");
69 STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
72 class IfConverter : public MachineFunctionPass {
74 ICNotClassfied, // BB data valid, but not classified.
75 ICSimpleFalse, // Same as ICSimple, but on the false path.
76 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
77 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
78 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
79 ICTriangleFalse, // Same as ICTriangle, but on the false path.
80 ICTriangle, // BB is entry of a triangle sub-CFG.
81 ICDiamond // BB is entry of a diamond sub-CFG.
84 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
85 /// if-conversion feasibility analysis. This includes results from
86 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
87 /// classification, and common tail block of its successors (if it's a
88 /// diamond shape), its size, whether it's predicable, and whether any
89 /// instruction can clobber the 'would-be' predicate.
91 /// IsDone - True if BB is not to be considered for ifcvt.
92 /// IsBeingAnalyzed - True if BB is currently being analyzed.
93 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
94 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
95 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
96 /// HasFallThrough - True if BB may fallthrough to the following BB.
97 /// IsUnpredicable - True if BB is known to be unpredicable.
98 /// ClobbersPred - True if BB could modify predicates (e.g. has
100 /// NonPredSize - Number of non-predicated instructions.
101 /// ExtraCost - Extra cost for multi-cycle instructions.
102 /// ExtraCost2 - Some instructions are slower when predicated
103 /// BB - Corresponding MachineBasicBlock.
104 /// TrueBB / FalseBB- See AnalyzeBranch().
105 /// BrCond - Conditions for end of block conditional branches.
106 /// Predicate - Predicate used in the BB.
109 bool IsBeingAnalyzed : 1;
112 bool IsBrAnalyzable : 1;
113 bool HasFallThrough : 1;
114 bool IsUnpredicable : 1;
115 bool CannotBeCopied : 1;
116 bool ClobbersPred : 1;
117 unsigned NonPredSize;
120 MachineBasicBlock *BB;
121 MachineBasicBlock *TrueBB;
122 MachineBasicBlock *FalseBB;
123 SmallVector<MachineOperand, 4> BrCond;
124 SmallVector<MachineOperand, 4> Predicate;
125 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
126 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
127 HasFallThrough(false), IsUnpredicable(false),
128 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
129 ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
132 /// IfcvtToken - Record information about pending if-conversions to attempt:
133 /// BBI - Corresponding BBInfo.
134 /// Kind - Type of block. See IfcvtKind.
135 /// NeedSubsumption - True if the to-be-predicated BB has already been
137 /// NumDups - Number of instructions that would be duplicated due
138 /// to this if-conversion. (For diamonds, the number of
139 /// identical instructions at the beginnings of both
141 /// NumDups2 - For diamonds, the number of identical instructions
142 /// at the ends of both paths.
146 bool NeedSubsumption;
149 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
150 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
153 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
154 /// basic block number.
155 std::vector<BBInfo> BBAnalysis;
156 TargetSchedModel SchedModel;
158 const TargetLoweringBase *TLI;
159 const TargetInstrInfo *TII;
160 const TargetRegisterInfo *TRI;
161 const MachineBranchProbabilityInfo *MBPI;
162 MachineRegisterInfo *MRI;
169 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
170 initializeIfConverterPass(*PassRegistry::getPassRegistry());
173 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
174 AU.addRequired<MachineBranchProbabilityInfo>();
175 MachineFunctionPass::getAnalysisUsage(AU);
178 virtual bool runOnMachineFunction(MachineFunction &MF);
181 bool ReverseBranchCondition(BBInfo &BBI);
182 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
183 const BranchProbability &Prediction) const;
184 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
185 bool FalseBranch, unsigned &Dups,
186 const BranchProbability &Prediction) const;
187 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
188 unsigned &Dups1, unsigned &Dups2) const;
189 void ScanInstructions(BBInfo &BBI);
190 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
191 std::vector<IfcvtToken*> &Tokens);
192 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
193 bool isTriangle = false, bool RevBranch = false);
194 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
195 void InvalidatePreds(MachineBasicBlock *BB);
196 void RemoveExtraEdges(BBInfo &BBI);
197 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
198 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
199 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
200 unsigned NumDups1, unsigned NumDups2);
201 void PredicateBlock(BBInfo &BBI,
202 MachineBasicBlock::iterator E,
203 SmallVectorImpl<MachineOperand> &Cond,
204 SmallSet<unsigned, 4> &Redefs,
205 SmallSet<unsigned, 4> *LaterRedefs = 0);
206 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
207 SmallVectorImpl<MachineOperand> &Cond,
208 SmallSet<unsigned, 4> &Redefs,
209 bool IgnoreBr = false);
210 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
212 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
213 unsigned Cycle, unsigned Extra,
214 const BranchProbability &Prediction) const {
215 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
219 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
220 unsigned TCycle, unsigned TExtra,
221 MachineBasicBlock &FBB,
222 unsigned FCycle, unsigned FExtra,
223 const BranchProbability &Prediction) const {
224 return TCycle > 0 && FCycle > 0 &&
225 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
229 // blockAlwaysFallThrough - Block ends without a terminator.
230 bool blockAlwaysFallThrough(BBInfo &BBI) const {
231 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
234 // IfcvtTokenCmp - Used to sort if-conversion candidates.
235 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
236 int Incr1 = (C1->Kind == ICDiamond)
237 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
238 int Incr2 = (C2->Kind == ICDiamond)
239 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
242 else if (Incr1 == Incr2) {
243 // Favors subsumption.
244 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
246 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
247 // Favors diamond over triangle, etc.
248 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
250 else if (C1->Kind == C2->Kind)
251 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
258 char IfConverter::ID = 0;
261 char &llvm::IfConverterID = IfConverter::ID;
263 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
264 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
265 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
267 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
268 TLI = MF.getTarget().getTargetLowering();
269 TII = MF.getTarget().getInstrInfo();
270 TRI = MF.getTarget().getRegisterInfo();
271 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
272 MRI = &MF.getRegInfo();
274 const TargetSubtargetInfo &ST =
275 MF.getTarget().getSubtarget<TargetSubtargetInfo>();
276 SchedModel.init(*ST.getSchedModel(), &ST, TII);
278 if (!TII) return false;
280 PreRegAlloc = MRI->isSSA();
282 bool BFChange = false;
284 // Tail merge tend to expose more if-conversion opportunities.
285 BranchFolder BF(true, false);
286 BFChange = BF.OptimizeFunction(MF, TII,
287 MF.getTarget().getRegisterInfo(),
288 getAnalysisIfAvailable<MachineModuleInfo>());
291 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
292 << MF.getName() << "\'");
294 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
295 DEBUG(dbgs() << " skipped\n");
298 DEBUG(dbgs() << "\n");
301 BBAnalysis.resize(MF.getNumBlockIDs());
303 std::vector<IfcvtToken*> Tokens;
305 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
306 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
307 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
308 // Do an initial analysis for each basic block and find all the potential
309 // candidates to perform if-conversion.
311 AnalyzeBlocks(MF, Tokens);
312 while (!Tokens.empty()) {
313 IfcvtToken *Token = Tokens.back();
315 BBInfo &BBI = Token->BBI;
316 IfcvtKind Kind = Token->Kind;
317 unsigned NumDups = Token->NumDups;
318 unsigned NumDups2 = Token->NumDups2;
322 // If the block has been evicted out of the queue or it has already been
323 // marked dead (due to it being predicated), then skip it.
325 BBI.IsEnqueued = false;
329 BBI.IsEnqueued = false;
333 default: llvm_unreachable("Unexpected!");
335 case ICSimpleFalse: {
336 bool isFalse = Kind == ICSimpleFalse;
337 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
338 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
340 << "): BB#" << BBI.BB->getNumber() << " ("
341 << ((Kind == ICSimpleFalse)
342 ? BBI.FalseBB->getNumber()
343 : BBI.TrueBB->getNumber()) << ") ");
344 RetVal = IfConvertSimple(BBI, Kind);
345 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
347 if (isFalse) ++NumSimpleFalse;
354 case ICTriangleFalse:
355 case ICTriangleFRev: {
356 bool isFalse = Kind == ICTriangleFalse;
357 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
358 if (DisableTriangle && !isFalse && !isRev) break;
359 if (DisableTriangleR && !isFalse && isRev) break;
360 if (DisableTriangleF && isFalse && !isRev) break;
361 if (DisableTriangleFR && isFalse && isRev) break;
362 DEBUG(dbgs() << "Ifcvt (Triangle");
364 DEBUG(dbgs() << " false");
366 DEBUG(dbgs() << " rev");
367 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
368 << BBI.TrueBB->getNumber() << ",F:"
369 << BBI.FalseBB->getNumber() << ") ");
370 RetVal = IfConvertTriangle(BBI, Kind);
371 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
374 if (isRev) ++NumTriangleFRev;
375 else ++NumTriangleFalse;
377 if (isRev) ++NumTriangleRev;
384 if (DisableDiamond) break;
385 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
386 << BBI.TrueBB->getNumber() << ",F:"
387 << BBI.FalseBB->getNumber() << ") ");
388 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
389 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
390 if (RetVal) ++NumDiamonds;
397 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
398 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
399 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
405 MadeChange |= Change;
408 // Delete tokens in case of early exit.
409 while (!Tokens.empty()) {
410 IfcvtToken *Token = Tokens.back();
418 if (MadeChange && IfCvtBranchFold) {
419 BranchFolder BF(false, false);
420 BF.OptimizeFunction(MF, TII,
421 MF.getTarget().getRegisterInfo(),
422 getAnalysisIfAvailable<MachineModuleInfo>());
425 MadeChange |= BFChange;
429 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
430 /// its 'true' successor.
431 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
432 MachineBasicBlock *TrueBB) {
433 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
434 E = BB->succ_end(); SI != E; ++SI) {
435 MachineBasicBlock *SuccBB = *SI;
436 if (SuccBB != TrueBB)
442 /// ReverseBranchCondition - Reverse the condition of the end of the block
443 /// branch. Swap block's 'true' and 'false' successors.
444 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
445 DebugLoc dl; // FIXME: this is nowhere
446 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
447 TII->RemoveBranch(*BBI.BB);
448 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
449 std::swap(BBI.TrueBB, BBI.FalseBB);
455 /// getNextBlock - Returns the next block in the function blocks ordering. If
456 /// it is the end, returns NULL.
457 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
458 MachineFunction::iterator I = BB;
459 MachineFunction::iterator E = BB->getParent()->end();
465 /// ValidSimple - Returns true if the 'true' block (along with its
466 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
467 /// number of instructions that the ifcvt would need to duplicate if performed
469 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
470 const BranchProbability &Prediction) const {
472 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
475 if (TrueBBI.IsBrAnalyzable)
478 if (TrueBBI.BB->pred_size() > 1) {
479 if (TrueBBI.CannotBeCopied ||
480 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
483 Dups = TrueBBI.NonPredSize;
489 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
490 /// with their common predecessor) forms a valid triangle shape for ifcvt.
491 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
492 /// branches to the 'false' block rather than the other way around. It also
493 /// returns the number of instructions that the ifcvt would need to duplicate
494 /// if performed in 'Dups'.
495 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
496 bool FalseBranch, unsigned &Dups,
497 const BranchProbability &Prediction) const {
499 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
502 if (TrueBBI.BB->pred_size() > 1) {
503 if (TrueBBI.CannotBeCopied)
506 unsigned Size = TrueBBI.NonPredSize;
507 if (TrueBBI.IsBrAnalyzable) {
508 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
509 // Ends with an unconditional branch. It will be removed.
512 MachineBasicBlock *FExit = FalseBranch
513 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
515 // Require a conditional branch
519 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
524 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
525 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
526 MachineFunction::iterator I = TrueBBI.BB;
527 if (++I == TrueBBI.BB->getParent()->end())
531 return TExit && TExit == FalseBBI.BB;
534 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
535 /// with their common predecessor) forms a valid diamond shape for ifcvt.
536 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
537 unsigned &Dups1, unsigned &Dups2) const {
539 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
540 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
543 MachineBasicBlock *TT = TrueBBI.TrueBB;
544 MachineBasicBlock *FT = FalseBBI.TrueBB;
546 if (!TT && blockAlwaysFallThrough(TrueBBI))
547 TT = getNextBlock(TrueBBI.BB);
548 if (!FT && blockAlwaysFallThrough(FalseBBI))
549 FT = getNextBlock(FalseBBI.BB);
552 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
554 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
557 // FIXME: Allow true block to have an early exit?
558 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
559 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
562 // Count duplicate instructions at the beginning of the true and false blocks.
563 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
564 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
565 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
566 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
567 while (TIB != TIE && FIB != FIE) {
568 // Skip dbg_value instructions. These do not count.
569 if (TIB->isDebugValue()) {
570 while (TIB != TIE && TIB->isDebugValue())
575 if (FIB->isDebugValue()) {
576 while (FIB != FIE && FIB->isDebugValue())
581 if (!TIB->isIdenticalTo(FIB))
588 // Now, in preparation for counting duplicate instructions at the ends of the
589 // blocks, move the end iterators up past any branch instructions.
592 if (!TIE->isBranch())
597 if (!FIE->isBranch())
601 // If Dups1 includes all of a block, then don't count duplicate
602 // instructions at the end of the blocks.
603 if (TIB == TIE || FIB == FIE)
606 // Count duplicate instructions at the ends of the blocks.
607 while (TIE != TIB && FIE != FIB) {
608 // Skip dbg_value instructions. These do not count.
609 if (TIE->isDebugValue()) {
610 while (TIE != TIB && TIE->isDebugValue())
615 if (FIE->isDebugValue()) {
616 while (FIE != FIB && FIE->isDebugValue())
621 if (!TIE->isIdenticalTo(FIE))
631 /// ScanInstructions - Scan all the instructions in the block to determine if
632 /// the block is predicable. In most cases, that means all the instructions
633 /// in the block are isPredicable(). Also checks if the block contains any
634 /// instruction which can clobber a predicate (e.g. condition code register).
635 /// If so, the block is not predicable unless it's the last instruction.
636 void IfConverter::ScanInstructions(BBInfo &BBI) {
640 bool AlreadyPredicated = !BBI.Predicate.empty();
641 // First analyze the end of BB branches.
642 BBI.TrueBB = BBI.FalseBB = NULL;
645 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
646 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
648 if (BBI.BrCond.size()) {
649 // No false branch. This BB must end with a conditional branch and a
652 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
654 // Malformed bcc? True and false blocks are the same?
655 BBI.IsUnpredicable = true;
660 // Then scan all the instructions.
664 BBI.ClobbersPred = false;
665 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
667 if (I->isDebugValue())
670 if (I->isNotDuplicable())
671 BBI.CannotBeCopied = true;
673 bool isPredicated = TII->isPredicated(I);
674 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
676 // A conditional branch is not predicable, but it may be eliminated.
682 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
683 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
685 BBI.ExtraCost += NumCycles-1;
686 BBI.ExtraCost2 += ExtraPredCost;
687 } else if (!AlreadyPredicated) {
688 // FIXME: This instruction is already predicated before the
689 // if-conversion pass. It's probably something like a conditional move.
690 // Mark this block unpredicable for now.
691 BBI.IsUnpredicable = true;
695 if (BBI.ClobbersPred && !isPredicated) {
696 // Predicate modification instruction should end the block (except for
697 // already predicated instructions and end of block branches).
698 // Predicate may have been modified, the subsequent (currently)
699 // unpredicated instructions cannot be correctly predicated.
700 BBI.IsUnpredicable = true;
704 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
705 // still potentially predicable.
706 std::vector<MachineOperand> PredDefs;
707 if (TII->DefinesPredicate(I, PredDefs))
708 BBI.ClobbersPred = true;
710 if (!TII->isPredicable(I)) {
711 BBI.IsUnpredicable = true;
717 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
718 /// predicated by the specified predicate.
719 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
720 SmallVectorImpl<MachineOperand> &Pred,
721 bool isTriangle, bool RevBranch) {
722 // If the block is dead or unpredicable, then it cannot be predicated.
723 if (BBI.IsDone || BBI.IsUnpredicable)
726 // If it is already predicated, check if the new predicate subsumes
728 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
731 if (BBI.BrCond.size()) {
735 // Test predicate subsumption.
736 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
737 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
739 if (TII->ReverseBranchCondition(Cond))
742 if (TII->ReverseBranchCondition(RevPred) ||
743 !TII->SubsumesPredicate(Cond, RevPred))
750 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
751 /// the specified block. Record its successors and whether it looks like an
752 /// if-conversion candidate.
753 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
754 std::vector<IfcvtToken*> &Tokens) {
755 BBInfo &BBI = BBAnalysis[BB->getNumber()];
757 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
761 BBI.IsBeingAnalyzed = true;
763 ScanInstructions(BBI);
765 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
766 // considered for ifcvt anymore.
767 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
768 BBI.IsBeingAnalyzed = false;
769 BBI.IsAnalyzed = true;
773 // Do not ifcvt if either path is a back edge to the entry block.
774 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
775 BBI.IsBeingAnalyzed = false;
776 BBI.IsAnalyzed = true;
780 // Do not ifcvt if true and false fallthrough blocks are the same.
782 BBI.IsBeingAnalyzed = false;
783 BBI.IsAnalyzed = true;
787 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
788 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
790 if (TrueBBI.IsDone && FalseBBI.IsDone) {
791 BBI.IsBeingAnalyzed = false;
792 BBI.IsAnalyzed = true;
796 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
797 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
801 bool TNeedSub = !TrueBBI.Predicate.empty();
802 bool FNeedSub = !FalseBBI.Predicate.empty();
803 bool Enqueued = false;
805 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
807 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
808 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
809 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
810 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
811 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
813 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
814 FeasibilityAnalysis(FalseBBI, RevCond)) {
822 // Note TailBB can be empty.
823 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
828 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
829 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
830 TrueBBI.ExtraCost2, Prediction) &&
831 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
839 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
843 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
844 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
845 TrueBBI.ExtraCost2, Prediction) &&
846 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
847 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
851 if (ValidSimple(TrueBBI, Dups, Prediction) &&
852 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
853 TrueBBI.ExtraCost2, Prediction) &&
854 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
855 // Simple (split, no rejoin):
862 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
867 // Try the other path...
868 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
869 Prediction.getCompl()) &&
870 MeetIfcvtSizeLimit(*FalseBBI.BB,
871 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
872 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
873 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
874 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
878 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
879 Prediction.getCompl()) &&
880 MeetIfcvtSizeLimit(*FalseBBI.BB,
881 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
882 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
883 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
884 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
888 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
889 MeetIfcvtSizeLimit(*FalseBBI.BB,
890 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
891 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
892 FeasibilityAnalysis(FalseBBI, RevCond)) {
893 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
898 BBI.IsEnqueued = Enqueued;
899 BBI.IsBeingAnalyzed = false;
900 BBI.IsAnalyzed = true;
904 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
906 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
907 std::vector<IfcvtToken*> &Tokens) {
908 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
909 MachineBasicBlock *BB = I;
910 AnalyzeBlock(BB, Tokens);
913 // Sort to favor more complex ifcvt scheme.
914 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
917 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
918 /// that all the intervening blocks are empty (given BB can fall through to its
920 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
921 MachineFunction::iterator PI = BB;
922 MachineFunction::iterator I = llvm::next(PI);
923 MachineFunction::iterator TI = ToBB;
924 MachineFunction::iterator E = BB->getParent()->end();
926 // Check isSuccessor to avoid case where the next block is empty, but
927 // it's not a successor.
928 if (I == E || !I->empty() || !PI->isSuccessor(I))
935 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
936 /// to determine if it can be if-converted. If predecessor is already enqueued,
938 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
939 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
940 E = BB->pred_end(); PI != E; ++PI) {
941 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
942 if (PBBI.IsDone || PBBI.BB == BB)
944 PBBI.IsAnalyzed = false;
945 PBBI.IsEnqueued = false;
949 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
951 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
952 const TargetInstrInfo *TII) {
953 DebugLoc dl; // FIXME: this is nowhere
954 SmallVector<MachineOperand, 0> NoCond;
955 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
958 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
960 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
961 MachineBasicBlock *TBB = NULL, *FBB = NULL;
962 SmallVector<MachineOperand, 4> Cond;
963 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
964 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
967 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
968 /// modeled as read + write (sort like two-address instructions). These
969 /// routines track register liveness and add implicit uses to if-converted
970 /// instructions to conform to the model.
971 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
972 const TargetRegisterInfo *TRI) {
973 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
974 E = BB->livein_end(); I != E; ++I) {
976 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
977 SubRegs.isValid(); ++SubRegs)
978 Redefs.insert(*SubRegs);
982 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
983 const TargetRegisterInfo *TRI,
984 bool AddImpUse = false) {
985 SmallVector<unsigned, 4> Defs;
986 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
987 const MachineOperand &MO = MI->getOperand(i);
990 unsigned Reg = MO.getReg();
995 else if (MO.isKill()) {
996 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
997 SubRegs.isValid(); ++SubRegs)
998 Redefs.erase(*SubRegs);
1001 MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
1002 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1003 unsigned Reg = Defs[i];
1004 if (!Redefs.insert(Reg)) {
1006 // Treat predicated update as read + write.
1007 MIB.addReg(Reg, RegState::Implicit | RegState::Undef);
1009 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1010 Redefs.insert(*SubRegs);
1015 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1016 MachineBasicBlock::iterator E,
1017 SmallSet<unsigned,4> &Redefs,
1018 const TargetRegisterInfo *TRI) {
1020 UpdatePredRedefs(I, Redefs, TRI);
1025 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1027 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1028 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1029 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1030 BBInfo *CvtBBI = &TrueBBI;
1031 BBInfo *NextBBI = &FalseBBI;
1033 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1034 if (Kind == ICSimpleFalse)
1035 std::swap(CvtBBI, NextBBI);
1037 if (CvtBBI->IsDone ||
1038 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1039 // Something has changed. It's no longer safe to predicate this block.
1040 BBI.IsAnalyzed = false;
1041 CvtBBI->IsAnalyzed = false;
1045 if (CvtBBI->BB->hasAddressTaken())
1046 // Conservatively abort if-conversion if BB's address is taken.
1049 if (Kind == ICSimpleFalse)
1050 if (TII->ReverseBranchCondition(Cond))
1051 llvm_unreachable("Unable to reverse branch condition!");
1053 // Initialize liveins to the first BB. These are potentiall redefined by
1054 // predicated instructions.
1055 SmallSet<unsigned, 4> Redefs;
1056 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1057 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1059 if (CvtBBI->BB->pred_size() > 1) {
1060 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1061 // Copy instructions in the true block, predicate them, and add them to
1063 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1065 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1066 // explicitly remove CvtBBI as a successor.
1067 BBI.BB->removeSuccessor(CvtBBI->BB);
1069 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1071 // Merge converted block into entry block.
1072 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1073 MergeBlocks(BBI, *CvtBBI);
1076 bool IterIfcvt = true;
1077 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1078 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1079 BBI.HasFallThrough = false;
1080 // Now ifcvt'd block will look like this:
1087 // We cannot further ifcvt this block because the unconditional branch
1088 // will have to be predicated on the new condition, that will not be
1089 // available if cmp executes.
1093 RemoveExtraEdges(BBI);
1095 // Update block info. BB can be iteratively if-converted.
1098 InvalidatePreds(BBI.BB);
1099 CvtBBI->IsDone = true;
1101 // FIXME: Must maintain LiveIns.
1105 /// IfConvertTriangle - If convert a triangle sub-CFG.
1107 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1108 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1109 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1110 BBInfo *CvtBBI = &TrueBBI;
1111 BBInfo *NextBBI = &FalseBBI;
1112 DebugLoc dl; // FIXME: this is nowhere
1114 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1115 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1116 std::swap(CvtBBI, NextBBI);
1118 if (CvtBBI->IsDone ||
1119 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1120 // Something has changed. It's no longer safe to predicate this block.
1121 BBI.IsAnalyzed = false;
1122 CvtBBI->IsAnalyzed = false;
1126 if (CvtBBI->BB->hasAddressTaken())
1127 // Conservatively abort if-conversion if BB's address is taken.
1130 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1131 if (TII->ReverseBranchCondition(Cond))
1132 llvm_unreachable("Unable to reverse branch condition!");
1134 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1135 if (ReverseBranchCondition(*CvtBBI)) {
1136 // BB has been changed, modify its predecessors (except for this
1137 // one) so they don't get ifcvt'ed based on bad intel.
1138 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1139 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1140 MachineBasicBlock *PBB = *PI;
1143 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1144 if (PBBI.IsEnqueued) {
1145 PBBI.IsAnalyzed = false;
1146 PBBI.IsEnqueued = false;
1152 // Initialize liveins to the first BB. These are potentially redefined by
1153 // predicated instructions.
1154 SmallSet<unsigned, 4> Redefs;
1155 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1156 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1158 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1159 if (CvtBBI->BB->pred_size() > 1) {
1160 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1161 // Copy instructions in the true block, predicate them, and add them to
1163 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1165 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1166 // explicitly remove CvtBBI as a successor.
1167 BBI.BB->removeSuccessor(CvtBBI->BB);
1169 // Predicate the 'true' block after removing its branch.
1170 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1171 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1173 // Now merge the entry of the triangle with the true block.
1174 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1175 MergeBlocks(BBI, *CvtBBI, false);
1178 // If 'true' block has a 'false' successor, add an exit branch to it.
1180 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1181 CvtBBI->BrCond.end());
1182 if (TII->ReverseBranchCondition(RevCond))
1183 llvm_unreachable("Unable to reverse branch condition!");
1184 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1185 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1188 // Merge in the 'false' block if the 'false' block has no other
1189 // predecessors. Otherwise, add an unconditional branch to 'false'.
1190 bool FalseBBDead = false;
1191 bool IterIfcvt = true;
1192 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1193 if (!isFallThrough) {
1194 // Only merge them if the true block does not fallthrough to the false
1195 // block. By not merging them, we make it possible to iteratively
1196 // ifcvt the blocks.
1197 if (!HasEarlyExit &&
1198 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1199 !NextBBI->BB->hasAddressTaken()) {
1200 MergeBlocks(BBI, *NextBBI);
1203 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1204 BBI.HasFallThrough = false;
1206 // Mixed predicated and unpredicated code. This cannot be iteratively
1211 RemoveExtraEdges(BBI);
1213 // Update block info. BB can be iteratively if-converted.
1216 InvalidatePreds(BBI.BB);
1217 CvtBBI->IsDone = true;
1219 NextBBI->IsDone = true;
1221 // FIXME: Must maintain LiveIns.
1225 /// IfConvertDiamond - If convert a diamond sub-CFG.
1227 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1228 unsigned NumDups1, unsigned NumDups2) {
1229 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1230 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1231 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1232 // True block must fall through or end with an unanalyzable terminator.
1234 if (blockAlwaysFallThrough(TrueBBI))
1235 TailBB = FalseBBI.TrueBB;
1236 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1239 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1240 TrueBBI.BB->pred_size() > 1 ||
1241 FalseBBI.BB->pred_size() > 1) {
1242 // Something has changed. It's no longer safe to predicate these blocks.
1243 BBI.IsAnalyzed = false;
1244 TrueBBI.IsAnalyzed = false;
1245 FalseBBI.IsAnalyzed = false;
1249 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1250 // Conservatively abort if-conversion if either BB has its address taken.
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 llvm_unreachable("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 // Remove branch from 'true' block and remove duplicated instructions.
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());
1328 // Remove 'false' block branch and find the last instruction to predicate.
1329 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1330 DI2 = BBI2->BB->end();
1331 while (NumDups2 != 0) {
1332 // NumDups2 only counted non-dbg_value instructions, so this won't
1333 // run off the head of the list.
1334 assert (DI2 != BBI2->BB->begin());
1336 // skip dbg_value instructions
1337 if (!DI2->isDebugValue())
1341 // Remember which registers would later be defined by the false block.
1342 // This allows us not to predicate instructions in the true block that would
1343 // later be re-defined. That is, rather than
1349 SmallSet<unsigned, 4> RedefsByFalse;
1350 SmallSet<unsigned, 4> ExtUses;
1351 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1352 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1353 if (FI->isDebugValue())
1355 SmallVector<unsigned, 4> Defs;
1356 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1357 const MachineOperand &MO = FI->getOperand(i);
1360 unsigned Reg = MO.getReg();
1364 Defs.push_back(Reg);
1365 } else if (!RedefsByFalse.count(Reg)) {
1366 // These are defined before ctrl flow reach the 'false' instructions.
1367 // They cannot be modified by the 'true' instructions.
1368 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1369 SubRegs.isValid(); ++SubRegs)
1370 ExtUses.insert(*SubRegs);
1374 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1375 unsigned Reg = Defs[i];
1376 if (!ExtUses.count(Reg)) {
1377 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1378 SubRegs.isValid(); ++SubRegs)
1379 RedefsByFalse.insert(*SubRegs);
1385 // Predicate the 'true' block.
1386 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
1388 // Predicate the 'false' block.
1389 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1391 // Merge the true block into the entry of the diamond.
1392 MergeBlocks(BBI, *BBI1, TailBB == 0);
1393 MergeBlocks(BBI, *BBI2, TailBB == 0);
1395 // If the if-converted block falls through or unconditionally branches into
1396 // the tail block, and the tail block does not have other predecessors, then
1397 // fold the tail block in as well. Otherwise, unless it falls through to the
1398 // tail, add a unconditional branch to it.
1400 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1401 bool CanMergeTail = !TailBBI.HasFallThrough &&
1402 !TailBBI.BB->hasAddressTaken();
1403 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1404 // check if there are any other predecessors besides those.
1405 unsigned NumPreds = TailBB->pred_size();
1407 CanMergeTail = false;
1408 else if (NumPreds == 1 && CanMergeTail) {
1409 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1410 if (*PI != BBI1->BB && *PI != BBI2->BB)
1411 CanMergeTail = false;
1414 MergeBlocks(BBI, TailBBI);
1415 TailBBI.IsDone = true;
1417 BBI.BB->addSuccessor(TailBB);
1418 InsertUncondBranch(BBI.BB, TailBB, TII);
1419 BBI.HasFallThrough = false;
1423 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1424 // which can happen here if TailBB is unanalyzable and is merged, so
1425 // explicitly remove BBI1 and BBI2 as successors.
1426 BBI.BB->removeSuccessor(BBI1->BB);
1427 BBI.BB->removeSuccessor(BBI2->BB);
1428 RemoveExtraEdges(BBI);
1430 // Update block info.
1431 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1432 InvalidatePreds(BBI.BB);
1434 // FIXME: Must maintain LiveIns.
1438 static bool MaySpeculate(const MachineInstr *MI,
1439 SmallSet<unsigned, 4> &LaterRedefs,
1440 const TargetInstrInfo *TII) {
1441 bool SawStore = true;
1442 if (!MI->isSafeToMove(TII, 0, SawStore))
1445 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1446 const MachineOperand &MO = MI->getOperand(i);
1449 unsigned Reg = MO.getReg();
1452 if (MO.isDef() && !LaterRedefs.count(Reg))
1459 /// PredicateBlock - Predicate instructions from the start of the block to the
1460 /// specified end with the specified condition.
1461 void IfConverter::PredicateBlock(BBInfo &BBI,
1462 MachineBasicBlock::iterator E,
1463 SmallVectorImpl<MachineOperand> &Cond,
1464 SmallSet<unsigned, 4> &Redefs,
1465 SmallSet<unsigned, 4> *LaterRedefs) {
1466 bool AnyUnpred = false;
1467 bool MaySpec = LaterRedefs != 0;
1468 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1469 if (I->isDebugValue() || TII->isPredicated(I))
1471 // It may be possible not to predicate an instruction if it's the 'true'
1472 // side of a diamond and the 'false' side may re-define the instruction's
1474 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1478 // If any instruction is predicated, then every instruction after it must
1481 if (!TII->PredicateInstruction(I, Cond)) {
1483 dbgs() << "Unable to predicate " << *I << "!\n";
1485 llvm_unreachable(0);
1488 // If the predicated instruction now redefines a register as the result of
1489 // if-conversion, add an implicit kill.
1490 UpdatePredRedefs(I, Redefs, TRI, true);
1493 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1495 BBI.IsAnalyzed = false;
1496 BBI.NonPredSize = 0;
1503 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1504 /// the destination block. Skip end of block branches if IgnoreBr is true.
1505 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1506 SmallVectorImpl<MachineOperand> &Cond,
1507 SmallSet<unsigned, 4> &Redefs,
1509 MachineFunction &MF = *ToBBI.BB->getParent();
1511 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1512 E = FromBBI.BB->end(); I != E; ++I) {
1513 // Do not copy the end of the block branches.
1514 if (IgnoreBr && I->isBranch())
1517 MachineInstr *MI = MF.CloneMachineInstr(I);
1518 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1519 ToBBI.NonPredSize++;
1520 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1521 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
1523 ToBBI.ExtraCost += NumCycles-1;
1524 ToBBI.ExtraCost2 += ExtraPredCost;
1526 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1527 if (!TII->PredicateInstruction(MI, Cond)) {
1529 dbgs() << "Unable to predicate " << *I << "!\n";
1531 llvm_unreachable(0);
1535 // If the predicated instruction now redefines a register as the result of
1536 // if-conversion, add an implicit kill.
1537 UpdatePredRedefs(MI, Redefs, TRI, true);
1541 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1542 FromBBI.BB->succ_end());
1543 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1544 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1546 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1547 MachineBasicBlock *Succ = Succs[i];
1548 // Fallthrough edge can't be transferred.
1549 if (Succ == FallThrough)
1551 ToBBI.BB->addSuccessor(Succ);
1555 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1556 std::back_inserter(ToBBI.Predicate));
1557 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1559 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1560 ToBBI.IsAnalyzed = false;
1565 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1566 /// This will leave FromBB as an empty block, so remove all of its
1567 /// successor edges except for the fall-through edge. If AddEdges is true,
1568 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1570 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1571 assert(!FromBBI.BB->hasAddressTaken() &&
1572 "Removing a BB whose address is taken!");
1574 ToBBI.BB->splice(ToBBI.BB->end(),
1575 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1577 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1578 FromBBI.BB->succ_end());
1579 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1580 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1582 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1583 MachineBasicBlock *Succ = Succs[i];
1584 // Fallthrough edge can't be transferred.
1585 if (Succ == FallThrough)
1587 FromBBI.BB->removeSuccessor(Succ);
1588 if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
1589 ToBBI.BB->addSuccessor(Succ);
1592 // Now FromBBI always falls through to the next block!
1593 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1594 FromBBI.BB->addSuccessor(NBB);
1596 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1597 std::back_inserter(ToBBI.Predicate));
1598 FromBBI.Predicate.clear();
1600 ToBBI.NonPredSize += FromBBI.NonPredSize;
1601 ToBBI.ExtraCost += FromBBI.ExtraCost;
1602 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1603 FromBBI.NonPredSize = 0;
1604 FromBBI.ExtraCost = 0;
1605 FromBBI.ExtraCost2 = 0;
1607 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1608 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1609 ToBBI.IsAnalyzed = false;
1610 FromBBI.IsAnalyzed = false;