blob: 1ee27f0e38da932c73dbf6dc32692fd1b418d082 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "ifcvt"
Evan Cheng9dcb7602009-09-04 07:47:40 +000015#include "BranchFolding.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000016#include "llvm/Function.h"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
Owen Andersond4397bb2010-09-28 20:42:15 +000020#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng0cf9a822010-09-10 01:29:16 +000022#include "llvm/Target/TargetInstrItineraries.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/Target/TargetLowering.h"
24#include "llvm/Target/TargetMachine.h"
Evan Cheng160f30c2010-06-16 07:35:02 +000025#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/ADT/DepthFirstIterator.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33using namespace llvm;
34
Chris Lattner4335bff2008-01-07 05:40:58 +000035// Hidden options for help debugging.
36static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000039static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner4335bff2008-01-07 05:40:58 +000040 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000041static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000042 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000043static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner4335bff2008-01-07 05:40:58 +000044 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000045static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000046 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000047static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000049static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000051static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner4335bff2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Evan Cheng160f30c2010-06-16 07:35:02 +000053static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54 cl::init(true), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055
56STATISTIC(NumSimple, "Number of simple if-conversions performed");
57STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
58STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
59STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
60STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
63STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
64STATISTIC(NumDupBBs, "Number of duplicated blocks");
65
66namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000067 class IfConverter : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068 enum IfcvtKind {
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.
77 };
78
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.
85 ///
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
94 /// cmp, call, etc.)
95 /// NonPredSize - Number of non-predicated instructions.
96 /// BB - Corresponding MachineBasicBlock.
97 /// TrueBB / FalseBB- See AnalyzeBranch().
98 /// BrCond - Conditions for end of block conditional branches.
99 /// Predicate - Predicate used in the BB.
100 struct BBInfo {
101 bool IsDone : 1;
102 bool IsBeingAnalyzed : 1;
103 bool IsAnalyzed : 1;
104 bool IsEnqueued : 1;
105 bool IsBrAnalyzable : 1;
106 bool HasFallThrough : 1;
107 bool IsUnpredicable : 1;
108 bool CannotBeCopied : 1;
109 bool ClobbersPred : 1;
110 unsigned NonPredSize;
111 MachineBasicBlock *BB;
112 MachineBasicBlock *TrueBB;
113 MachineBasicBlock *FalseBB;
Owen Andersond131b5b2008-08-14 22:49:33 +0000114 SmallVector<MachineOperand, 4> BrCond;
115 SmallVector<MachineOperand, 4> Predicate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
117 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
118 HasFallThrough(false), IsUnpredicable(false),
119 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
120 BB(0), TrueBB(0), FalseBB(0) {}
121 };
122
Bob Wilson01320da2010-06-15 18:19:27 +0000123 /// IfcvtToken - Record information about pending if-conversions to attempt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124 /// BBI - Corresponding BBInfo.
125 /// Kind - Type of block. See IfcvtKind.
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000126 /// NeedSubsumption - True if the to-be-predicated BB has already been
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 /// predicated.
128 /// NumDups - Number of instructions that would be duplicated due
129 /// to this if-conversion. (For diamonds, the number of
130 /// identical instructions at the beginnings of both
131 /// paths).
132 /// NumDups2 - For diamonds, the number of identical instructions
133 /// at the ends of both paths.
134 struct IfcvtToken {
135 BBInfo &BBI;
136 IfcvtKind Kind;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000137 bool NeedSubsumption;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 unsigned NumDups;
139 unsigned NumDups2;
140 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000141 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142 };
143
144 /// Roots - Basic blocks that do not have successors. These are the starting
145 /// points of Graph traversal.
146 std::vector<MachineBasicBlock*> Roots;
147
148 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
149 /// basic block number.
150 std::vector<BBInfo> BBAnalysis;
151
152 const TargetLowering *TLI;
153 const TargetInstrInfo *TII;
Evan Cheng160f30c2010-06-16 07:35:02 +0000154 const TargetRegisterInfo *TRI;
Evan Cheng0cf9a822010-09-10 01:29:16 +0000155 const InstrItineraryData *InstrItins;
Owen Andersond4397bb2010-09-28 20:42:15 +0000156 const MachineLoopInfo *MLI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 bool MadeChange;
Owen Anderson03f2a7b2009-06-24 23:41:44 +0000158 int FnNum;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 public:
160 static char ID;
Owen Andersona65d6a62010-10-19 17:21:58 +0000161 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
162 initializeIfConverterPass(*PassRegistry::getPassRegistry());
163 }
Owen Andersond4397bb2010-09-28 20:42:15 +0000164
165 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166 AU.addRequired<MachineLoopInfo>();
167 MachineFunctionPass::getAnalysisUsage(AU);
168 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169
170 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga911dfe2008-06-04 09:15:51 +0000171 virtual const char *getPassName() const { return "If Converter"; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172
173 private:
174 bool ReverseBranchCondition(BBInfo &BBI);
Owen Anderson97d32912010-10-01 22:45:50 +0000175 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
176 float Prediction, float Confidence) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Anderson97d32912010-10-01 22:45:50 +0000178 bool FalseBranch, unsigned &Dups,
179 float Prediction, float Confidence) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
181 unsigned &Dups1, unsigned &Dups2) const;
182 void ScanInstructions(BBInfo &BBI);
183 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
184 std::vector<IfcvtToken*> &Tokens);
Owen Andersond131b5b2008-08-14 22:49:33 +0000185 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186 bool isTriangle = false, bool RevBranch = false);
Bob Wilson89b9c322010-06-15 18:57:15 +0000187 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 void InvalidatePreds(MachineBasicBlock *BB);
189 void RemoveExtraEdges(BBInfo &BBI);
190 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
191 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
192 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
193 unsigned NumDups1, unsigned NumDups2);
194 void PredicateBlock(BBInfo &BBI,
195 MachineBasicBlock::iterator E,
Evan Cheng160f30c2010-06-16 07:35:02 +0000196 SmallVectorImpl<MachineOperand> &Cond,
197 SmallSet<unsigned, 4> &Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000199 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng160f30c2010-06-16 07:35:02 +0000200 SmallSet<unsigned, 4> &Redefs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 bool IgnoreBr = false);
Bob Wilson2e99a562010-06-29 00:55:23 +0000202 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203
Owen Andersond4397bb2010-09-28 20:42:15 +0000204 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, unsigned Size,
Owen Anderson97d32912010-10-01 22:45:50 +0000205 float Prediction, float Confidence) const {
206 return Size > 0 && TII->isProfitableToIfCvt(BB, Size,
207 Prediction, Confidence);
Evan Cheng09f72522010-06-25 22:42:03 +0000208 }
209
210 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, unsigned TSize,
Owen Andersond4397bb2010-09-28 20:42:15 +0000211 MachineBasicBlock &FBB, unsigned FSize,
Owen Anderson97d32912010-10-01 22:45:50 +0000212 float Prediction, float Confidence) const {
Evan Cheng09f72522010-06-25 22:42:03 +0000213 return TSize > 0 && FSize > 0 &&
Owen Anderson97d32912010-10-01 22:45:50 +0000214 TII->isProfitableToIfCvt(TBB, TSize, FBB, FSize,
215 Prediction, Confidence);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 }
217
218 // blockAlwaysFallThrough - Block ends without a terminator.
219 bool blockAlwaysFallThrough(BBInfo &BBI) const {
220 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
221 }
222
223 // IfcvtTokenCmp - Used to sort if-conversion candidates.
224 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
225 int Incr1 = (C1->Kind == ICDiamond)
226 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
227 int Incr2 = (C2->Kind == ICDiamond)
228 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
229 if (Incr1 > Incr2)
230 return true;
231 else if (Incr1 == Incr2) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000232 // Favors subsumption.
233 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 return true;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000235 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 // Favors diamond over triangle, etc.
237 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
238 return true;
239 else if (C1->Kind == C2->Kind)
240 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
241 }
242 }
243 return false;
244 }
245 };
246
247 char IfConverter::ID = 0;
248}
249
Owen Andersoncdb0c032010-10-12 19:48:12 +0000250INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
251INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
252INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson93ab5612009-10-28 20:46:46 +0000253
254FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255
256bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
257 TLI = MF.getTarget().getTargetLowering();
258 TII = MF.getTarget().getInstrInfo();
Evan Cheng160f30c2010-06-16 07:35:02 +0000259 TRI = MF.getTarget().getRegisterInfo();
Owen Andersond4397bb2010-09-28 20:42:15 +0000260 MLI = &getAnalysis<MachineLoopInfo>();
Evan Cheng0cf9a822010-09-10 01:29:16 +0000261 InstrItins = MF.getTarget().getInstrItineraryData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 if (!TII) return false;
263
Evan Cheng24ff0562010-06-18 23:09:54 +0000264 // Tail merge tend to expose more if-conversion opportunities.
265 BranchFolder BF(true);
266 bool BFChange = BF.OptimizeFunction(MF, TII,
267 MF.getTarget().getRegisterInfo(),
268 getAnalysisIfAvailable<MachineModuleInfo>());
269
David Greenead778702010-01-04 22:02:01 +0000270 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000271 << MF.getFunction()->getName() << "\'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272
273 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greenead778702010-01-04 22:02:01 +0000274 DEBUG(dbgs() << " skipped\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 return false;
276 }
David Greenead778702010-01-04 22:02:01 +0000277 DEBUG(dbgs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278
279 MF.RenumberBlocks();
280 BBAnalysis.resize(MF.getNumBlockIDs());
281
282 // Look for root nodes, i.e. blocks without successors.
283 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000284 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 Roots.push_back(I);
286
287 std::vector<IfcvtToken*> Tokens;
288 MadeChange = false;
289 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
290 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
291 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000292 // Do an initial analysis for each basic block and find all the potential
293 // candidates to perform if-conversion.
Bob Wilson89b9c322010-06-15 18:57:15 +0000294 bool Change = false;
295 AnalyzeBlocks(MF, Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 while (!Tokens.empty()) {
297 IfcvtToken *Token = Tokens.back();
298 Tokens.pop_back();
299 BBInfo &BBI = Token->BBI;
300 IfcvtKind Kind = Token->Kind;
Nuno Lopes06cea782008-11-04 13:02:59 +0000301 unsigned NumDups = Token->NumDups;
Duncan Sands5c2a51a2008-11-04 18:05:30 +0000302 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes06cea782008-11-04 13:02:59 +0000303
304 delete Token;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305
306 // If the block has been evicted out of the queue or it has already been
307 // marked dead (due to it being predicated), then skip it.
308 if (BBI.IsDone)
309 BBI.IsEnqueued = false;
310 if (!BBI.IsEnqueued)
311 continue;
312
313 BBI.IsEnqueued = false;
314
315 bool RetVal = false;
316 switch (Kind) {
317 default: assert(false && "Unexpected!");
318 break;
319 case ICSimple:
320 case ICSimpleFalse: {
321 bool isFalse = Kind == ICSimpleFalse;
322 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000323 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
324 " false" : "")
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000325 << "): BB#" << BBI.BB->getNumber() << " ("
326 << ((Kind == ICSimpleFalse)
327 ? BBI.FalseBB->getNumber()
328 : BBI.TrueBB->getNumber()) << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 RetVal = IfConvertSimple(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000330 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000331 if (RetVal) {
Dan Gohman559d5132010-06-22 15:08:57 +0000332 if (isFalse) ++NumSimpleFalse;
333 else ++NumSimple;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000334 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 break;
336 }
337 case ICTriangle:
338 case ICTriangleRev:
339 case ICTriangleFalse:
340 case ICTriangleFRev: {
341 bool isFalse = Kind == ICTriangleFalse;
342 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
343 if (DisableTriangle && !isFalse && !isRev) break;
344 if (DisableTriangleR && !isFalse && isRev) break;
345 if (DisableTriangleF && isFalse && !isRev) break;
346 if (DisableTriangleFR && isFalse && isRev) break;
David Greenead778702010-01-04 22:02:01 +0000347 DEBUG(dbgs() << "Ifcvt (Triangle");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348 if (isFalse)
David Greenead778702010-01-04 22:02:01 +0000349 DEBUG(dbgs() << " false");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 if (isRev)
David Greenead778702010-01-04 22:02:01 +0000351 DEBUG(dbgs() << " rev");
352 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000353 << BBI.TrueBB->getNumber() << ",F:"
354 << BBI.FalseBB->getNumber() << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355 RetVal = IfConvertTriangle(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000356 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 if (RetVal) {
358 if (isFalse) {
Dan Gohman559d5132010-06-22 15:08:57 +0000359 if (isRev) ++NumTriangleFRev;
360 else ++NumTriangleFalse;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 } else {
Dan Gohman559d5132010-06-22 15:08:57 +0000362 if (isRev) ++NumTriangleRev;
363 else ++NumTriangle;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 }
365 }
366 break;
367 }
368 case ICDiamond: {
369 if (DisableDiamond) break;
David Greenead778702010-01-04 22:02:01 +0000370 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000371 << BBI.TrueBB->getNumber() << ",F:"
372 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes06cea782008-11-04 13:02:59 +0000373 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greenead778702010-01-04 22:02:01 +0000374 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohman559d5132010-06-22 15:08:57 +0000375 if (RetVal) ++NumDiamonds;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 break;
377 }
378 }
379
380 Change |= RetVal;
381
382 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
383 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
384 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
385 break;
386 }
387
388 if (!Change)
389 break;
390 MadeChange |= Change;
391 }
392
393 // Delete tokens in case of early exit.
394 while (!Tokens.empty()) {
395 IfcvtToken *Token = Tokens.back();
396 Tokens.pop_back();
397 delete Token;
398 }
399
400 Tokens.clear();
401 Roots.clear();
402 BBAnalysis.clear();
403
Evan Chengd50455b2010-06-18 22:17:13 +0000404 if (MadeChange && IfCvtBranchFold) {
Bob Wilson93ab5612009-10-28 20:46:46 +0000405 BranchFolder BF(false);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000406 BF.OptimizeFunction(MF, TII,
407 MF.getTarget().getRegisterInfo(),
408 getAnalysisIfAvailable<MachineModuleInfo>());
409 }
410
Evan Cheng24ff0562010-06-18 23:09:54 +0000411 MadeChange |= BFChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 return MadeChange;
413}
414
415/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
416/// its 'true' successor.
417static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
418 MachineBasicBlock *TrueBB) {
419 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
420 E = BB->succ_end(); SI != E; ++SI) {
421 MachineBasicBlock *SuccBB = *SI;
422 if (SuccBB != TrueBB)
423 return SuccBB;
424 }
425 return NULL;
426}
427
428/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000429/// branch. Swap block's 'true' and 'false' successors.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000431 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
433 TII->RemoveBranch(*BBI.BB);
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000434 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 std::swap(BBI.TrueBB, BBI.FalseBB);
436 return true;
437 }
438 return false;
439}
440
441/// getNextBlock - Returns the next block in the function blocks ordering. If
442/// it is the end, returns NULL.
443static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
444 MachineFunction::iterator I = BB;
445 MachineFunction::iterator E = BB->getParent()->end();
446 if (++I == E)
447 return NULL;
448 return I;
449}
450
451/// ValidSimple - Returns true if the 'true' block (along with its
452/// predecessor) forms a valid simple shape for ifcvt. It also returns the
453/// number of instructions that the ifcvt would need to duplicate if performed
454/// in Dups.
Owen Andersond4397bb2010-09-28 20:42:15 +0000455bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Owen Anderson97d32912010-10-01 22:45:50 +0000456 float Prediction, float Confidence) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 Dups = 0;
458 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
459 return false;
460
461 if (TrueBBI.IsBrAnalyzable)
462 return false;
463
464 if (TrueBBI.BB->pred_size() > 1) {
465 if (TrueBBI.CannotBeCopied ||
Owen Andersond4397bb2010-09-28 20:42:15 +0000466 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Owen Anderson97d32912010-10-01 22:45:50 +0000467 Prediction, Confidence))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468 return false;
469 Dups = TrueBBI.NonPredSize;
470 }
471
472 return true;
473}
474
475/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
476/// with their common predecessor) forms a valid triangle shape for ifcvt.
477/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000478/// branches to the 'false' block rather than the other way around. It also
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479/// returns the number of instructions that the ifcvt would need to duplicate
480/// if performed in 'Dups'.
481bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Anderson97d32912010-10-01 22:45:50 +0000482 bool FalseBranch, unsigned &Dups,
483 float Prediction, float Confidence) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 Dups = 0;
485 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
486 return false;
487
488 if (TrueBBI.BB->pred_size() > 1) {
489 if (TrueBBI.CannotBeCopied)
490 return false;
491
492 unsigned Size = TrueBBI.NonPredSize;
493 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000494 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000495 // Ends with an unconditional branch. It will be removed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 --Size;
497 else {
498 MachineBasicBlock *FExit = FalseBranch
499 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
500 if (FExit)
501 // Require a conditional branch
502 ++Size;
503 }
504 }
Owen Anderson97d32912010-10-01 22:45:50 +0000505 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size,
506 Prediction, Confidence))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507 return false;
508 Dups = Size;
509 }
510
511 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
512 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
513 MachineFunction::iterator I = TrueBBI.BB;
514 if (++I == TrueBBI.BB->getParent()->end())
515 return false;
516 TExit = I;
517 }
518 return TExit && TExit == FalseBBI.BB;
519}
520
521static
522MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
523 const TargetInstrInfo *TII) {
524 MachineBasicBlock::iterator I = BB->end();
525 while (I != BB->begin()) {
526 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000527 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 break;
529 }
530 return I;
531}
532
533/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
534/// with their common predecessor) forms a valid diamond shape for ifcvt.
535bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
536 unsigned &Dups1, unsigned &Dups2) const {
537 Dups1 = Dups2 = 0;
538 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
539 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
540 return false;
541
542 MachineBasicBlock *TT = TrueBBI.TrueBB;
543 MachineBasicBlock *FT = FalseBBI.TrueBB;
544
545 if (!TT && blockAlwaysFallThrough(TrueBBI))
546 TT = getNextBlock(TrueBBI.BB);
547 if (!FT && blockAlwaysFallThrough(FalseBBI))
548 FT = getNextBlock(FalseBBI.BB);
549 if (TT != FT)
550 return false;
551 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
552 return false;
553 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
554 return false;
555
556 // FIXME: Allow true block to have an early exit?
557 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
558 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
559 return false;
560
561 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
562 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000563 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
564 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
565 // Skip dbg_value instructions
566 while (TI != TIE && TI->isDebugValue())
567 ++TI;
568 while (FI != FIE && FI->isDebugValue())
569 ++FI;
570 while (TI != TIE && FI != FIE) {
Evan Chenga03a63c2010-06-18 21:52:57 +0000571 // Skip dbg_value instructions. These do not count.
572 if (TI->isDebugValue()) {
573 while (TI != TIE && TI->isDebugValue())
574 ++TI;
575 if (TI == TIE)
576 break;
577 }
578 if (FI->isDebugValue()) {
579 while (FI != FIE && FI->isDebugValue())
580 ++FI;
581 if (FI == FIE)
582 break;
583 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 if (!TI->isIdenticalTo(FI))
585 break;
586 ++Dups1;
587 ++TI;
588 ++FI;
589 }
590
591 TI = firstNonBranchInst(TrueBBI.BB, TII);
592 FI = firstNonBranchInst(FalseBBI.BB, TII);
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000593 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
594 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Evan Chenga03a63c2010-06-18 21:52:57 +0000595 // Skip dbg_value instructions at end of the bb's.
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000596 while (TI != TIB && TI->isDebugValue())
597 --TI;
598 while (FI != FIB && FI->isDebugValue())
599 --FI;
600 while (TI != TIB && FI != FIB) {
Evan Chenga03a63c2010-06-18 21:52:57 +0000601 // Skip dbg_value instructions. These do not count.
602 if (TI->isDebugValue()) {
603 while (TI != TIB && TI->isDebugValue())
604 --TI;
605 if (TI == TIB)
606 break;
607 }
608 if (FI->isDebugValue()) {
609 while (FI != FIB && FI->isDebugValue())
610 --FI;
611 if (FI == FIB)
612 break;
613 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 if (!TI->isIdenticalTo(FI))
615 break;
616 ++Dups2;
617 --TI;
618 --FI;
619 }
620
621 return true;
622}
623
624/// ScanInstructions - Scan all the instructions in the block to determine if
625/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000626/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627/// instruction which can clobber a predicate (e.g. condition code register).
628/// If so, the block is not predicable unless it's the last instruction.
629void IfConverter::ScanInstructions(BBInfo &BBI) {
630 if (BBI.IsDone)
631 return;
632
633 bool AlreadyPredicated = BBI.Predicate.size() > 0;
634 // First analyze the end of BB branches.
635 BBI.TrueBB = BBI.FalseBB = NULL;
636 BBI.BrCond.clear();
637 BBI.IsBrAnalyzable =
638 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
639 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
640
641 if (BBI.BrCond.size()) {
642 // No false branch. This BB must end with a conditional branch and a
643 // fallthrough.
644 if (!BBI.FalseBB)
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000645 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng4eb66e62009-06-15 21:24:34 +0000646 if (!BBI.FalseBB) {
647 // Malformed bcc? True and false blocks are the same?
648 BBI.IsUnpredicable = true;
649 return;
650 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 }
652
653 // Then scan all the instructions.
654 BBI.NonPredSize = 0;
655 BBI.ClobbersPred = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
657 I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +0000658 if (I->isDebugValue())
659 continue;
660
Chris Lattner5b930372008-01-07 07:27:27 +0000661 const TargetInstrDesc &TID = I->getDesc();
662 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 BBI.CannotBeCopied = true;
664
665 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000666 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667
668 if (!isCondBr) {
Evan Cheng0cf9a822010-09-10 01:29:16 +0000669 if (!isPredicated) {
670 unsigned NumOps = TII->getNumMicroOps(&*I, InstrItins);
671 BBI.NonPredSize += NumOps;
672 } else if (!AlreadyPredicated) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 // FIXME: This instruction is already predicated before the
674 // if-conversion pass. It's probably something like a conditional move.
675 // Mark this block unpredicable for now.
676 BBI.IsUnpredicable = true;
677 return;
678 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 }
680
681 if (BBI.ClobbersPred && !isPredicated) {
682 // Predicate modification instruction should end the block (except for
683 // already predicated instructions and end of block branches).
684 if (isCondBr) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000685 // A conditional branch is not predicable, but it may be eliminated.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 continue;
687 }
688
689 // Predicate may have been modified, the subsequent (currently)
690 // unpredicated instructions cannot be correctly predicated.
691 BBI.IsUnpredicable = true;
692 return;
693 }
694
695 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
696 // still potentially predicable.
697 std::vector<MachineOperand> PredDefs;
698 if (TII->DefinesPredicate(I, PredDefs))
699 BBI.ClobbersPred = true;
700
Evan Cheng76fe9892009-11-21 06:20:26 +0000701 if (!TII->isPredicable(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 BBI.IsUnpredicable = true;
703 return;
704 }
705 }
706}
707
708/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
709/// predicated by the specified predicate.
710bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000711 SmallVectorImpl<MachineOperand> &Pred,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712 bool isTriangle, bool RevBranch) {
713 // If the block is dead or unpredicable, then it cannot be predicated.
714 if (BBI.IsDone || BBI.IsUnpredicable)
715 return false;
716
717 // If it is already predicated, check if its predicate subsumes the new
718 // predicate.
719 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
720 return false;
721
722 if (BBI.BrCond.size()) {
723 if (!isTriangle)
724 return false;
725
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000726 // Test predicate subsumption.
Owen Andersond131b5b2008-08-14 22:49:33 +0000727 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
728 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 if (RevBranch) {
730 if (TII->ReverseBranchCondition(Cond))
731 return false;
732 }
733 if (TII->ReverseBranchCondition(RevPred) ||
734 !TII->SubsumesPredicate(Cond, RevPred))
735 return false;
736 }
737
738 return true;
739}
740
741/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
742/// the specified block. Record its successors and whether it looks like an
743/// if-conversion candidate.
744IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
745 std::vector<IfcvtToken*> &Tokens) {
746 BBInfo &BBI = BBAnalysis[BB->getNumber()];
747
748 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
749 return BBI;
750
751 BBI.BB = BB;
752 BBI.IsBeingAnalyzed = true;
753
754 ScanInstructions(BBI);
755
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000756 // Unanalyzable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000757 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 BBI.IsBeingAnalyzed = false;
759 BBI.IsAnalyzed = true;
760 return BBI;
761 }
762
763 // Do not ifcvt if either path is a back edge to the entry block.
764 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
765 BBI.IsBeingAnalyzed = false;
766 BBI.IsAnalyzed = true;
767 return BBI;
768 }
769
Evan Cheng4eb66e62009-06-15 21:24:34 +0000770 // Do not ifcvt if true and false fallthrough blocks are the same.
771 if (!BBI.FalseBB) {
772 BBI.IsBeingAnalyzed = false;
773 BBI.IsAnalyzed = true;
774 return BBI;
775 }
776
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
778 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
779
780 if (TrueBBI.IsDone && FalseBBI.IsDone) {
781 BBI.IsBeingAnalyzed = false;
782 BBI.IsAnalyzed = true;
783 return BBI;
784 }
785
Owen Andersond131b5b2008-08-14 22:49:33 +0000786 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
788
789 unsigned Dups = 0;
790 unsigned Dups2 = 0;
791 bool TNeedSub = TrueBBI.Predicate.size() > 0;
792 bool FNeedSub = FalseBBI.Predicate.size() > 0;
793 bool Enqueued = false;
Owen Andersond4397bb2010-09-28 20:42:15 +0000794
795 // Try to predict the branch, using loop info to guide us.
796 // General heuristics are:
797 // - backedge -> 90% taken
798 // - early exit -> 20% taken
Owen Anderson97d32912010-10-01 22:45:50 +0000799 // - branch predictor confidence -> 90%
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000800 float Prediction = 0.5f;
Owen Anderson97d32912010-10-01 22:45:50 +0000801 float Confidence = 0.9f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000802 MachineLoop *Loop = MLI->getLoopFor(BB);
803 if (Loop) {
804 if (TrueBBI.BB == Loop->getHeader())
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000805 Prediction = 0.9f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000806 else if (FalseBBI.BB == Loop->getHeader())
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000807 Prediction = 0.1f;
808
Owen Andersond4397bb2010-09-28 20:42:15 +0000809 MachineLoop *TrueLoop = MLI->getLoopFor(TrueBBI.BB);
810 MachineLoop *FalseLoop = MLI->getLoopFor(FalseBBI.BB);
811 if (!TrueLoop || TrueLoop->getParentLoop() == Loop)
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000812 Prediction = 0.2f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000813 else if (!FalseLoop || FalseLoop->getParentLoop() == Loop)
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000814 Prediction = 0.8f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000815 }
816
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Evan Cheng09f72522010-06-25 22:42:03 +0000818 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize - (Dups + Dups2),
Owen Andersond4397bb2010-09-28 20:42:15 +0000819 *FalseBBI.BB, FalseBBI.NonPredSize - (Dups + Dups2),
Owen Anderson97d32912010-10-01 22:45:50 +0000820 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
822 FeasibilityAnalysis(FalseBBI, RevCond)) {
823 // Diamond:
824 // EBB
825 // / \_
826 // | |
827 // TBB FBB
828 // \ /
829 // TailBB
830 // Note TailBB can be empty.
831 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
832 Dups2));
833 Enqueued = true;
834 }
835
Owen Anderson97d32912010-10-01 22:45:50 +0000836 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction, Confidence) &&
837 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize,
838 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
840 // Triangle:
841 // EBB
842 // | \_
843 // | |
844 // | TBB
845 // | /
846 // FBB
847 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
848 Enqueued = true;
849 }
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000850
Owen Anderson97d32912010-10-01 22:45:50 +0000851 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction, Confidence) &&
852 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize,
853 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
855 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
856 Enqueued = true;
857 }
858
Owen Anderson97d32912010-10-01 22:45:50 +0000859 if (ValidSimple(TrueBBI, Dups, Prediction, Confidence) &&
860 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize,
861 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
863 // Simple (split, no rejoin):
864 // EBB
865 // | \_
866 // | |
867 // | TBB---> exit
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000868 // |
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000869 // FBB
870 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
871 Enqueued = true;
872 }
873
874 if (CanRevCond) {
875 // Try the other path...
Owen Anderson97d32912010-10-01 22:45:50 +0000876 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
877 1.0-Prediction, Confidence) &&
878 MeetIfcvtSizeLimit(*FalseBBI.BB, FalseBBI.NonPredSize,
879 1.0-Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
881 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
882 Enqueued = true;
883 }
884
Owen Anderson97d32912010-10-01 22:45:50 +0000885 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
886 1.0-Prediction, Confidence) &&
887 MeetIfcvtSizeLimit(*FalseBBI.BB, FalseBBI.NonPredSize,
888 1.0-Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
890 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
891 Enqueued = true;
892 }
893
Owen Anderson97d32912010-10-01 22:45:50 +0000894 if (ValidSimple(FalseBBI, Dups, 1.0-Prediction, Confidence) &&
895 MeetIfcvtSizeLimit(*FalseBBI.BB, FalseBBI.NonPredSize,
896 1.0-Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 FeasibilityAnalysis(FalseBBI, RevCond)) {
898 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
899 Enqueued = true;
900 }
901 }
902
903 BBI.IsEnqueued = Enqueued;
904 BBI.IsBeingAnalyzed = false;
905 BBI.IsAnalyzed = true;
906 return BBI;
907}
908
909/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson89b9c322010-06-15 18:57:15 +0000910/// candidates.
911void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 std::vector<IfcvtToken*> &Tokens) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 std::set<MachineBasicBlock*> Visited;
914 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
915 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
916 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
917 MachineBasicBlock *BB = *I;
918 AnalyzeBlock(BB, Tokens);
919 }
920 }
921
922 // Sort to favor more complex ifcvt scheme.
923 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924}
925
926/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
927/// that all the intervening blocks are empty (given BB can fall through to its
928/// next block).
929static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Cheng160f30c2010-06-16 07:35:02 +0000930 MachineFunction::iterator PI = BB;
931 MachineFunction::iterator I = llvm::next(PI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 MachineFunction::iterator TI = ToBB;
933 MachineFunction::iterator E = BB->getParent()->end();
Evan Cheng160f30c2010-06-16 07:35:02 +0000934 while (I != TI) {
935 // Check isSuccessor to avoid case where the next block is empty, but
936 // it's not a successor.
937 if (I == E || !I->empty() || !PI->isSuccessor(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 return false;
Evan Cheng160f30c2010-06-16 07:35:02 +0000939 PI = I++;
940 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 return true;
942}
943
944/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
945/// to determine if it can be if-converted. If predecessor is already enqueued,
946/// dequeue it!
947void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
948 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
949 E = BB->pred_end(); PI != E; ++PI) {
950 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
951 if (PBBI.IsDone || PBBI.BB == BB)
952 continue;
953 PBBI.IsAnalyzed = false;
954 PBBI.IsEnqueued = false;
955 }
956}
957
958/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
959///
960static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
961 const TargetInstrInfo *TII) {
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000962 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmane458ea82008-08-22 16:07:55 +0000963 SmallVector<MachineOperand, 0> NoCond;
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000964 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965}
966
967/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
968/// successors.
969void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
970 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Andersond131b5b2008-08-14 22:49:33 +0000971 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
973 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
974}
975
Evan Cheng160f30c2010-06-16 07:35:02 +0000976/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
977/// modeled as read + write (sort like two-address instructions). These
978/// routines track register liveness and add implicit uses to if-converted
979/// instructions to conform to the model.
980static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
981 const TargetRegisterInfo *TRI) {
982 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
983 E = BB->livein_end(); I != E; ++I) {
984 unsigned Reg = *I;
985 Redefs.insert(Reg);
986 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
987 *Subreg; ++Subreg)
988 Redefs.insert(*Subreg);
989 }
990}
991
992static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
993 const TargetRegisterInfo *TRI,
994 bool AddImpUse = false) {
995 SmallVector<unsigned, 4> Defs;
996 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
997 const MachineOperand &MO = MI->getOperand(i);
998 if (!MO.isReg())
999 continue;
1000 unsigned Reg = MO.getReg();
1001 if (!Reg)
1002 continue;
1003 if (MO.isDef())
1004 Defs.push_back(Reg);
1005 else if (MO.isKill()) {
1006 Redefs.erase(Reg);
1007 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1008 Redefs.erase(*SR);
1009 }
1010 }
1011 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1012 unsigned Reg = Defs[i];
1013 if (Redefs.count(Reg)) {
1014 if (AddImpUse)
1015 // Treat predicated update as read + write.
1016 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
Jim Grosbachf44b1712010-06-25 22:02:28 +00001017 true/*IsImp*/,false/*IsKill*/));
Evan Cheng160f30c2010-06-16 07:35:02 +00001018 } else {
1019 Redefs.insert(Reg);
1020 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1021 Redefs.insert(*SR);
1022 }
1023 }
1024}
1025
1026static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1027 MachineBasicBlock::iterator E,
1028 SmallSet<unsigned,4> &Redefs,
1029 const TargetRegisterInfo *TRI) {
1030 while (I != E) {
1031 UpdatePredRedefs(I, Redefs, TRI);
1032 ++I;
1033 }
1034}
1035
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1037///
1038bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1039 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1040 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1041 BBInfo *CvtBBI = &TrueBBI;
1042 BBInfo *NextBBI = &FalseBBI;
1043
Owen Andersond131b5b2008-08-14 22:49:33 +00001044 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 if (Kind == ICSimpleFalse)
1046 std::swap(CvtBBI, NextBBI);
1047
1048 if (CvtBBI->IsDone ||
1049 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1050 // Something has changed. It's no longer safe to predicate this block.
1051 BBI.IsAnalyzed = false;
1052 CvtBBI->IsAnalyzed = false;
1053 return false;
1054 }
1055
1056 if (Kind == ICSimpleFalse)
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001057 if (TII->ReverseBranchCondition(Cond))
1058 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059
Bob Wilson8d7f1622010-06-19 05:33:57 +00001060 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Cheng160f30c2010-06-16 07:35:02 +00001061 // predicated instructions.
1062 SmallSet<unsigned, 4> Redefs;
1063 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1064 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1065
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 if (CvtBBI->BB->pred_size() > 1) {
1067 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001068 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 // the entry block.
Evan Cheng160f30c2010-06-16 07:35:02 +00001070 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 } else {
Evan Cheng160f30c2010-06-16 07:35:02 +00001072 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073
1074 // Merge converted block into entry block.
1075 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1076 MergeBlocks(BBI, *CvtBBI);
1077 }
1078
1079 bool IterIfcvt = true;
1080 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1081 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1082 BBI.HasFallThrough = false;
1083 // Now ifcvt'd block will look like this:
1084 // BB:
1085 // ...
1086 // t, f = cmp
1087 // if t op
1088 // b BBf
1089 //
1090 // We cannot further ifcvt this block because the unconditional branch
1091 // will have to be predicated on the new condition, that will not be
1092 // available if cmp executes.
1093 IterIfcvt = false;
1094 }
1095
1096 RemoveExtraEdges(BBI);
1097
1098 // Update block info. BB can be iteratively if-converted.
1099 if (!IterIfcvt)
1100 BBI.IsDone = true;
1101 InvalidatePreds(BBI.BB);
1102 CvtBBI->IsDone = true;
1103
1104 // FIXME: Must maintain LiveIns.
1105 return true;
1106}
1107
1108/// IfConvertTriangle - If convert a triangle sub-CFG.
1109///
1110bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1111 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1112 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1113 BBInfo *CvtBBI = &TrueBBI;
1114 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings9fa5e332010-06-17 22:43:56 +00001115 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116
Owen Andersond131b5b2008-08-14 22:49:33 +00001117 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1119 std::swap(CvtBBI, NextBBI);
1120
1121 if (CvtBBI->IsDone ||
1122 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1123 // Something has changed. It's no longer safe to predicate this block.
1124 BBI.IsAnalyzed = false;
1125 CvtBBI->IsAnalyzed = false;
1126 return false;
1127 }
1128
1129 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001130 if (TII->ReverseBranchCondition(Cond))
1131 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132
1133 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001134 if (ReverseBranchCondition(*CvtBBI)) {
1135 // BB has been changed, modify its predecessors (except for this
1136 // one) so they don't get ifcvt'ed based on bad intel.
1137 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1138 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1139 MachineBasicBlock *PBB = *PI;
1140 if (PBB == BBI.BB)
1141 continue;
1142 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1143 if (PBBI.IsEnqueued) {
1144 PBBI.IsAnalyzed = false;
1145 PBBI.IsEnqueued = false;
1146 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147 }
1148 }
1149 }
1150
Bob Wilson8d7f1622010-06-19 05:33:57 +00001151 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng160f30c2010-06-16 07:35:02 +00001152 // predicated instructions.
1153 SmallSet<unsigned, 4> Redefs;
1154 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1155 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1156
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001157 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
Bob Wilson2e99a562010-06-29 00:55:23 +00001158 if (CvtBBI->BB->pred_size() > 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001160 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 // the entry block.
Evan Cheng160f30c2010-06-16 07:35:02 +00001162 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 } else {
1164 // Predicate the 'true' block after removing its branch.
1165 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Cheng160f30c2010-06-16 07:35:02 +00001166 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 // Now merge the entry of the triangle with the true block.
1169 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2e99a562010-06-29 00:55:23 +00001170 MergeBlocks(BBI, *CvtBBI, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 }
1172
1173 // If 'true' block has a 'false' successor, add an exit branch to it.
1174 if (HasEarlyExit) {
Owen Andersond131b5b2008-08-14 22:49:33 +00001175 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1176 CvtBBI->BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177 if (TII->ReverseBranchCondition(RevCond))
1178 assert(false && "Unable to reverse branch condition!");
Stuart Hastings9fa5e332010-06-17 22:43:56 +00001179 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1181 }
1182
1183 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001184 // predecessors. Otherwise, add an unconditional branch to 'false'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 bool FalseBBDead = false;
1186 bool IterIfcvt = true;
1187 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1188 if (!isFallThrough) {
1189 // Only merge them if the true block does not fallthrough to the false
1190 // block. By not merging them, we make it possible to iteratively
1191 // ifcvt the blocks.
1192 if (!HasEarlyExit &&
1193 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1194 MergeBlocks(BBI, *NextBBI);
1195 FalseBBDead = true;
1196 } else {
1197 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1198 BBI.HasFallThrough = false;
1199 }
1200 // Mixed predicated and unpredicated code. This cannot be iteratively
1201 // predicated.
1202 IterIfcvt = false;
1203 }
1204
1205 RemoveExtraEdges(BBI);
1206
1207 // Update block info. BB can be iteratively if-converted.
Bob Wilson2f5b10d2010-06-15 22:18:54 +00001208 if (!IterIfcvt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 BBI.IsDone = true;
1210 InvalidatePreds(BBI.BB);
1211 CvtBBI->IsDone = true;
1212 if (FalseBBDead)
1213 NextBBI->IsDone = true;
1214
1215 // FIXME: Must maintain LiveIns.
1216 return true;
1217}
1218
1219/// IfConvertDiamond - If convert a diamond sub-CFG.
1220///
1221bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1222 unsigned NumDups1, unsigned NumDups2) {
1223 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1224 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1225 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001226 // True block must fall through or end with an unanalyzable terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 if (!TailBB) {
1228 if (blockAlwaysFallThrough(TrueBBI))
1229 TailBB = FalseBBI.TrueBB;
1230 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1231 }
1232
1233 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1234 TrueBBI.BB->pred_size() > 1 ||
1235 FalseBBI.BB->pred_size() > 1) {
1236 // Something has changed. It's no longer safe to predicate these blocks.
1237 BBI.IsAnalyzed = false;
1238 TrueBBI.IsAnalyzed = false;
1239 FalseBBI.IsAnalyzed = false;
1240 return false;
1241 }
1242
Bob Wilson2e99a562010-06-29 00:55:23 +00001243 // Put the predicated instructions from the 'true' block before the
1244 // instructions from the 'false' block, unless the true block would clobber
1245 // the predicate, in which case, do the opposite.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 BBInfo *BBI1 = &TrueBBI;
1247 BBInfo *BBI2 = &FalseBBI;
Owen Andersond131b5b2008-08-14 22:49:33 +00001248 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001249 if (TII->ReverseBranchCondition(RevCond))
1250 assert(false && "Unable to reverse branch condition!");
Owen Andersond131b5b2008-08-14 22:49:33 +00001251 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1252 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253
1254 // Figure out the more profitable ordering.
1255 bool DoSwap = false;
1256 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1257 DoSwap = true;
1258 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1259 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1260 DoSwap = true;
1261 }
1262 if (DoSwap) {
1263 std::swap(BBI1, BBI2);
1264 std::swap(Cond1, Cond2);
1265 }
1266
1267 // Remove the conditional branch from entry to the blocks.
1268 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1269
Jim Grosbachf44b1712010-06-25 22:02:28 +00001270 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng160f30c2010-06-16 07:35:02 +00001271 // predicated instructions.
1272 SmallSet<unsigned, 4> Redefs;
1273 InitPredRedefs(BBI1->BB, Redefs, TRI);
1274
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 // Remove the duplicated instructions at the beginnings of both paths.
1276 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1277 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachf8648062010-06-14 21:30:32 +00001278 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1279 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1280 // Skip dbg_value instructions
1281 while (DI1 != DIE1 && DI1->isDebugValue())
1282 ++DI1;
1283 while (DI2 != DIE2 && DI2->isDebugValue())
1284 ++DI2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 BBI1->NonPredSize -= NumDups1;
1286 BBI2->NonPredSize -= NumDups1;
Jim Grosbach8ea33f62010-06-28 20:26:00 +00001287
1288 // Skip past the dups on each side separately since there may be
1289 // differing dbg_value entries.
1290 for (unsigned i = 0; i < NumDups1; ++DI1) {
1291 if (!DI1->isDebugValue())
1292 ++i;
1293 }
Jim Grosbach1213ebc2010-06-25 23:05:46 +00001294 while (NumDups1 != 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 ++DI2;
Jim Grosbach8ea33f62010-06-28 20:26:00 +00001296 if (!DI2->isDebugValue())
1297 --NumDups1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001299
1300 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1302 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1303
1304 // Predicate the 'true' block after removing its branch.
1305 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1306 DI1 = BBI1->BB->end();
Jim Grosbachf8648062010-06-14 21:30:32 +00001307 for (unsigned i = 0; i != NumDups2; ) {
1308 // NumDups2 only counted non-dbg_value instructions, so this won't
1309 // run off the head of the list.
1310 assert (DI1 != BBI1->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 --DI1;
Jim Grosbachf8648062010-06-14 21:30:32 +00001312 // skip dbg_value instructions
1313 if (!DI1->isDebugValue())
1314 ++i;
1315 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng160f30c2010-06-16 07:35:02 +00001317 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318
1319 // Predicate the 'false' block.
1320 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1321 DI2 = BBI2->BB->end();
1322 while (NumDups2 != 0) {
Jim Grosbachf8648062010-06-14 21:30:32 +00001323 // NumDups2 only counted non-dbg_value instructions, so this won't
1324 // run off the head of the list.
1325 assert (DI2 != BBI2->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 --DI2;
Jim Grosbachf8648062010-06-14 21:30:32 +00001327 // skip dbg_value instructions
1328 if (!DI2->isDebugValue())
1329 --NumDups2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001331 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332
1333 // Merge the true block into the entry of the diamond.
Bob Wilson2e99a562010-06-29 00:55:23 +00001334 MergeBlocks(BBI, *BBI1, TailBB == 0);
1335 MergeBlocks(BBI, *BBI2, TailBB == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001337 // If the if-converted block falls through or unconditionally branches into
1338 // the tail block, and the tail block does not have other predecessors, then
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 // fold the tail block in as well. Otherwise, unless it falls through to the
1340 // tail, add a unconditional branch to it.
1341 if (TailBB) {
1342 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
Bob Wilson2e99a562010-06-29 00:55:23 +00001343 bool CanMergeTail = !TailBBI.HasFallThrough;
1344 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1345 // check if there are any other predecessors besides those.
1346 unsigned NumPreds = TailBB->pred_size();
1347 if (NumPreds > 1)
1348 CanMergeTail = false;
1349 else if (NumPreds == 1 && CanMergeTail) {
1350 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1351 if (*PI != BBI1->BB && *PI != BBI2->BB)
1352 CanMergeTail = false;
1353 }
1354 if (CanMergeTail) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 MergeBlocks(BBI, TailBBI);
1356 TailBBI.IsDone = true;
1357 } else {
Bob Wilson2e99a562010-06-29 00:55:23 +00001358 BBI.BB->addSuccessor(TailBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 InsertUncondBranch(BBI.BB, TailBB, TII);
1360 BBI.HasFallThrough = false;
1361 }
1362 }
1363
Bob Wilson2e99a562010-06-29 00:55:23 +00001364 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1365 // which can happen here if TailBB is unanalyzable and is merged, so
1366 // explicitly remove BBI1 and BBI2 as successors.
1367 BBI.BB->removeSuccessor(BBI1->BB);
1368 BBI.BB->removeSuccessor(BBI2->BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 RemoveExtraEdges(BBI);
1370
1371 // Update block info.
1372 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1373 InvalidatePreds(BBI.BB);
1374
1375 // FIXME: Must maintain LiveIns.
1376 return true;
1377}
1378
1379/// PredicateBlock - Predicate instructions from the start of the block to the
1380/// specified end with the specified condition.
1381void IfConverter::PredicateBlock(BBInfo &BBI,
1382 MachineBasicBlock::iterator E,
Evan Cheng160f30c2010-06-16 07:35:02 +00001383 SmallVectorImpl<MachineOperand> &Cond,
1384 SmallSet<unsigned, 4> &Redefs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +00001386 if (I->isDebugValue() || TII->isPredicated(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 continue;
1388 if (!TII->PredicateInstruction(I, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001389#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001390 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001391#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001392 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001394
Bob Wilson8d7f1622010-06-19 05:33:57 +00001395 // If the predicated instruction now redefines a register as the result of
Evan Cheng160f30c2010-06-16 07:35:02 +00001396 // if-conversion, add an implicit kill.
1397 UpdatePredRedefs(I, Redefs, TRI, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398 }
1399
1400 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1401
1402 BBI.IsAnalyzed = false;
1403 BBI.NonPredSize = 0;
1404
Dan Gohman559d5132010-06-22 15:08:57 +00001405 ++NumIfConvBBs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406}
1407
1408/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1409/// the destination block. Skip end of block branches if IgnoreBr is true.
1410void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +00001411 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng160f30c2010-06-16 07:35:02 +00001412 SmallSet<unsigned, 4> &Redefs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 bool IgnoreBr) {
Dan Gohman221a4372008-07-07 23:14:23 +00001414 MachineFunction &MF = *ToBBI.BB->getParent();
1415
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1417 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001418 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 // Do not copy the end of the block branches.
Bob Wilsond00487b2010-06-18 17:07:23 +00001420 if (IgnoreBr && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421 break;
1422
Dan Gohman221a4372008-07-07 23:14:23 +00001423 MachineInstr *MI = MF.CloneMachineInstr(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Evan Cheng0cf9a822010-09-10 01:29:16 +00001425 unsigned NumOps = TII->getNumMicroOps(MI, InstrItins);
1426 ToBBI.NonPredSize += NumOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427
Bob Wilsond00487b2010-06-18 17:07:23 +00001428 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 if (!TII->PredicateInstruction(MI, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001430#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001431 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001432#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001433 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001435 }
1436
Bob Wilson8d7f1622010-06-19 05:33:57 +00001437 // If the predicated instruction now redefines a register as the result of
Evan Cheng160f30c2010-06-16 07:35:02 +00001438 // if-conversion, add an implicit kill.
1439 UpdatePredRedefs(MI, Redefs, TRI, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 }
1441
Bob Wilson2e99a562010-06-29 00:55:23 +00001442 if (!IgnoreBr) {
1443 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1444 FromBBI.BB->succ_end());
1445 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1446 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447
Bob Wilson2e99a562010-06-29 00:55:23 +00001448 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1449 MachineBasicBlock *Succ = Succs[i];
1450 // Fallthrough edge can't be transferred.
1451 if (Succ == FallThrough)
1452 continue;
1453 ToBBI.BB->addSuccessor(Succ);
1454 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 }
1456
1457 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1458 std::back_inserter(ToBBI.Predicate));
1459 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1460
1461 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1462 ToBBI.IsAnalyzed = false;
1463
Dan Gohman559d5132010-06-22 15:08:57 +00001464 ++NumDupBBs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001465}
1466
1467/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson2e99a562010-06-29 00:55:23 +00001468/// This will leave FromBB as an empty block, so remove all of its
1469/// successor edges except for the fall-through edge. If AddEdges is true,
1470/// i.e., when FromBBI's branch is being moved, add those successor edges to
1471/// ToBBI.
1472void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473 ToBBI.BB->splice(ToBBI.BB->end(),
1474 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1475
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1477 FromBBI.BB->succ_end());
1478 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1479 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1480
1481 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1482 MachineBasicBlock *Succ = Succs[i];
1483 // Fallthrough edge can't be transferred.
1484 if (Succ == FallThrough)
1485 continue;
1486 FromBBI.BB->removeSuccessor(Succ);
Bob Wilson2e99a562010-06-29 00:55:23 +00001487 if (AddEdges)
1488 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 }
1490
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001491 // Now FromBBI always falls through to the next block!
Bob Wilson58c9e3c2009-05-13 23:48:58 +00001492 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493 FromBBI.BB->addSuccessor(NBB);
1494
1495 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1496 std::back_inserter(ToBBI.Predicate));
1497 FromBBI.Predicate.clear();
1498
1499 ToBBI.NonPredSize += FromBBI.NonPredSize;
1500 FromBBI.NonPredSize = 0;
1501
1502 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1503 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1504 ToBBI.IsAnalyzed = false;
1505 FromBBI.IsAnalyzed = false;
1506}