blob: 51ec096e9e5d694d89b6f55f6f6bae76faabf0b9 [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"
20#include "llvm/Target/TargetInstrInfo.h"
21#include "llvm/Target/TargetLowering.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000025#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
30using namespace llvm;
31
Chris Lattner4335bff2008-01-07 05:40:58 +000032// Hidden options for help debugging.
33static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
34static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
35static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
36static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
37 cl::init(false), cl::Hidden);
38static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
39 cl::init(false), cl::Hidden);
40static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
41 cl::init(false), cl::Hidden);
42static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
43 cl::init(false), cl::Hidden);
44static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
45 cl::init(false), cl::Hidden);
46static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
47 cl::init(false), cl::Hidden);
48static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
49 cl::init(false), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050
51STATISTIC(NumSimple, "Number of simple if-conversions performed");
52STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
53STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
54STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
55STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
56STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
57STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
58STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
59STATISTIC(NumDupBBs, "Number of duplicated blocks");
60
61namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000062 class IfConverter : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063 enum IfcvtKind {
64 ICNotClassfied, // BB data valid, but not classified.
65 ICSimpleFalse, // Same as ICSimple, but on the false path.
66 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
67 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
68 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
69 ICTriangleFalse, // Same as ICTriangle, but on the false path.
70 ICTriangle, // BB is entry of a triangle sub-CFG.
71 ICDiamond // BB is entry of a diamond sub-CFG.
72 };
73
74 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
75 /// if-conversion feasibility analysis. This includes results from
76 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
77 /// classification, and common tail block of its successors (if it's a
78 /// diamond shape), its size, whether it's predicable, and whether any
79 /// instruction can clobber the 'would-be' predicate.
80 ///
81 /// IsDone - True if BB is not to be considered for ifcvt.
82 /// IsBeingAnalyzed - True if BB is currently being analyzed.
83 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
84 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
85 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
86 /// HasFallThrough - True if BB may fallthrough to the following BB.
87 /// IsUnpredicable - True if BB is known to be unpredicable.
88 /// ClobbersPred - True if BB could modify predicates (e.g. has
89 /// cmp, call, etc.)
90 /// NonPredSize - Number of non-predicated instructions.
91 /// BB - Corresponding MachineBasicBlock.
92 /// TrueBB / FalseBB- See AnalyzeBranch().
93 /// BrCond - Conditions for end of block conditional branches.
94 /// Predicate - Predicate used in the BB.
95 struct BBInfo {
96 bool IsDone : 1;
97 bool IsBeingAnalyzed : 1;
98 bool IsAnalyzed : 1;
99 bool IsEnqueued : 1;
100 bool IsBrAnalyzable : 1;
101 bool HasFallThrough : 1;
102 bool IsUnpredicable : 1;
103 bool CannotBeCopied : 1;
104 bool ClobbersPred : 1;
105 unsigned NonPredSize;
106 MachineBasicBlock *BB;
107 MachineBasicBlock *TrueBB;
108 MachineBasicBlock *FalseBB;
Owen Andersond131b5b2008-08-14 22:49:33 +0000109 SmallVector<MachineOperand, 4> BrCond;
110 SmallVector<MachineOperand, 4> Predicate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
112 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
113 HasFallThrough(false), IsUnpredicable(false),
114 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
115 BB(0), TrueBB(0), FalseBB(0) {}
116 };
117
Bob Wilson01320da2010-06-15 18:19:27 +0000118 /// IfcvtToken - Record information about pending if-conversions to attempt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 /// BBI - Corresponding BBInfo.
120 /// Kind - Type of block. See IfcvtKind.
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000121 /// NeedSubsumption - True if the to-be-predicated BB has already been
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 /// predicated.
123 /// NumDups - Number of instructions that would be duplicated due
124 /// to this if-conversion. (For diamonds, the number of
125 /// identical instructions at the beginnings of both
126 /// paths).
127 /// NumDups2 - For diamonds, the number of identical instructions
128 /// at the ends of both paths.
129 struct IfcvtToken {
130 BBInfo &BBI;
131 IfcvtKind Kind;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000132 bool NeedSubsumption;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 unsigned NumDups;
134 unsigned NumDups2;
135 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000136 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137 };
138
139 /// Roots - Basic blocks that do not have successors. These are the starting
140 /// points of Graph traversal.
141 std::vector<MachineBasicBlock*> Roots;
142
143 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
144 /// basic block number.
145 std::vector<BBInfo> BBAnalysis;
146
147 const TargetLowering *TLI;
148 const TargetInstrInfo *TII;
149 bool MadeChange;
Owen Anderson03f2a7b2009-06-24 23:41:44 +0000150 int FnNum;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 public:
152 static char ID;
Bob Wilson93ab5612009-10-28 20:46:46 +0000153 IfConverter() : MachineFunctionPass(&ID), FnNum(-1) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154
155 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga911dfe2008-06-04 09:15:51 +0000156 virtual const char *getPassName() const { return "If Converter"; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157
158 private:
159 bool ReverseBranchCondition(BBInfo &BBI);
160 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
161 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
162 bool FalseBranch, unsigned &Dups) const;
163 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
164 unsigned &Dups1, unsigned &Dups2) const;
165 void ScanInstructions(BBInfo &BBI);
166 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
167 std::vector<IfcvtToken*> &Tokens);
Owen Andersond131b5b2008-08-14 22:49:33 +0000168 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 bool isTriangle = false, bool RevBranch = false);
Bob Wilson89b9c322010-06-15 18:57:15 +0000170 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 void InvalidatePreds(MachineBasicBlock *BB);
172 void RemoveExtraEdges(BBInfo &BBI);
173 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
174 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
175 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
176 unsigned NumDups1, unsigned NumDups2);
177 void PredicateBlock(BBInfo &BBI,
178 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +0000179 SmallVectorImpl<MachineOperand> &Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000181 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 bool IgnoreBr = false);
183 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
184
185 bool MeetIfcvtSizeLimit(unsigned Size) const {
186 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit();
187 }
188
189 // blockAlwaysFallThrough - Block ends without a terminator.
190 bool blockAlwaysFallThrough(BBInfo &BBI) const {
191 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
192 }
193
194 // IfcvtTokenCmp - Used to sort if-conversion candidates.
195 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
196 int Incr1 = (C1->Kind == ICDiamond)
197 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
198 int Incr2 = (C2->Kind == ICDiamond)
199 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
200 if (Incr1 > Incr2)
201 return true;
202 else if (Incr1 == Incr2) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000203 // Favors subsumption.
204 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 return true;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000206 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 // Favors diamond over triangle, etc.
208 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
209 return true;
210 else if (C1->Kind == C2->Kind)
211 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
212 }
213 }
214 return false;
215 }
216 };
217
218 char IfConverter::ID = 0;
219}
220
Bob Wilson93ab5612009-10-28 20:46:46 +0000221static RegisterPass<IfConverter>
222X("if-converter", "If Converter");
223
224FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225
226bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
227 TLI = MF.getTarget().getTargetLowering();
228 TII = MF.getTarget().getInstrInfo();
229 if (!TII) return false;
230
David Greenead778702010-01-04 22:02:01 +0000231 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000232 << MF.getFunction()->getName() << "\'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233
234 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greenead778702010-01-04 22:02:01 +0000235 DEBUG(dbgs() << " skipped\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 return false;
237 }
David Greenead778702010-01-04 22:02:01 +0000238 DEBUG(dbgs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
240 MF.RenumberBlocks();
241 BBAnalysis.resize(MF.getNumBlockIDs());
242
243 // Look for root nodes, i.e. blocks without successors.
244 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000245 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 Roots.push_back(I);
247
248 std::vector<IfcvtToken*> Tokens;
249 MadeChange = false;
250 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
251 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
252 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000253 // Do an initial analysis for each basic block and find all the potential
254 // candidates to perform if-conversion.
Bob Wilson89b9c322010-06-15 18:57:15 +0000255 bool Change = false;
256 AnalyzeBlocks(MF, Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 while (!Tokens.empty()) {
258 IfcvtToken *Token = Tokens.back();
259 Tokens.pop_back();
260 BBInfo &BBI = Token->BBI;
261 IfcvtKind Kind = Token->Kind;
Nuno Lopes06cea782008-11-04 13:02:59 +0000262 unsigned NumDups = Token->NumDups;
Duncan Sands5c2a51a2008-11-04 18:05:30 +0000263 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes06cea782008-11-04 13:02:59 +0000264
265 delete Token;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266
267 // If the block has been evicted out of the queue or it has already been
268 // marked dead (due to it being predicated), then skip it.
269 if (BBI.IsDone)
270 BBI.IsEnqueued = false;
271 if (!BBI.IsEnqueued)
272 continue;
273
274 BBI.IsEnqueued = false;
275
276 bool RetVal = false;
277 switch (Kind) {
278 default: assert(false && "Unexpected!");
279 break;
280 case ICSimple:
281 case ICSimpleFalse: {
282 bool isFalse = Kind == ICSimpleFalse;
283 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
David Greenead778702010-01-04 22:02:01 +0000284 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"")
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000285 << "): BB#" << BBI.BB->getNumber() << " ("
286 << ((Kind == ICSimpleFalse)
287 ? BBI.FalseBB->getNumber()
288 : BBI.TrueBB->getNumber()) << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 RetVal = IfConvertSimple(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000290 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000291 if (RetVal) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 if (isFalse) NumSimpleFalse++;
293 else NumSimple++;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000294 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 break;
296 }
297 case ICTriangle:
298 case ICTriangleRev:
299 case ICTriangleFalse:
300 case ICTriangleFRev: {
301 bool isFalse = Kind == ICTriangleFalse;
302 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
303 if (DisableTriangle && !isFalse && !isRev) break;
304 if (DisableTriangleR && !isFalse && isRev) break;
305 if (DisableTriangleF && isFalse && !isRev) break;
306 if (DisableTriangleFR && isFalse && isRev) break;
David Greenead778702010-01-04 22:02:01 +0000307 DEBUG(dbgs() << "Ifcvt (Triangle");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 if (isFalse)
David Greenead778702010-01-04 22:02:01 +0000309 DEBUG(dbgs() << " false");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310 if (isRev)
David Greenead778702010-01-04 22:02:01 +0000311 DEBUG(dbgs() << " rev");
312 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000313 << BBI.TrueBB->getNumber() << ",F:"
314 << BBI.FalseBB->getNumber() << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 RetVal = IfConvertTriangle(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000316 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 if (RetVal) {
318 if (isFalse) {
319 if (isRev) NumTriangleFRev++;
320 else NumTriangleFalse++;
321 } else {
322 if (isRev) NumTriangleRev++;
323 else NumTriangle++;
324 }
325 }
326 break;
327 }
328 case ICDiamond: {
329 if (DisableDiamond) break;
David Greenead778702010-01-04 22:02:01 +0000330 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000331 << BBI.TrueBB->getNumber() << ",F:"
332 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes06cea782008-11-04 13:02:59 +0000333 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greenead778702010-01-04 22:02:01 +0000334 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 if (RetVal) NumDiamonds++;
336 break;
337 }
338 }
339
340 Change |= RetVal;
341
342 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
343 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
344 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
345 break;
346 }
347
348 if (!Change)
349 break;
350 MadeChange |= Change;
351 }
352
353 // Delete tokens in case of early exit.
354 while (!Tokens.empty()) {
355 IfcvtToken *Token = Tokens.back();
356 Tokens.pop_back();
357 delete Token;
358 }
359
360 Tokens.clear();
361 Roots.clear();
362 BBAnalysis.clear();
363
Evan Cheng9dcb7602009-09-04 07:47:40 +0000364 if (MadeChange) {
Bob Wilson93ab5612009-10-28 20:46:46 +0000365 BranchFolder BF(false);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000366 BF.OptimizeFunction(MF, TII,
367 MF.getTarget().getRegisterInfo(),
368 getAnalysisIfAvailable<MachineModuleInfo>());
369 }
370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371 return MadeChange;
372}
373
374/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
375/// its 'true' successor.
376static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
377 MachineBasicBlock *TrueBB) {
378 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
379 E = BB->succ_end(); SI != E; ++SI) {
380 MachineBasicBlock *SuccBB = *SI;
381 if (SuccBB != TrueBB)
382 return SuccBB;
383 }
384 return NULL;
385}
386
387/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000388/// branch. Swap block's 'true' and 'false' successors.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
390 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
391 TII->RemoveBranch(*BBI.BB);
392 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
393 std::swap(BBI.TrueBB, BBI.FalseBB);
394 return true;
395 }
396 return false;
397}
398
399/// getNextBlock - Returns the next block in the function blocks ordering. If
400/// it is the end, returns NULL.
401static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
402 MachineFunction::iterator I = BB;
403 MachineFunction::iterator E = BB->getParent()->end();
404 if (++I == E)
405 return NULL;
406 return I;
407}
408
409/// ValidSimple - Returns true if the 'true' block (along with its
410/// predecessor) forms a valid simple shape for ifcvt. It also returns the
411/// number of instructions that the ifcvt would need to duplicate if performed
412/// in Dups.
413bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
414 Dups = 0;
415 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
416 return false;
417
418 if (TrueBBI.IsBrAnalyzable)
419 return false;
420
421 if (TrueBBI.BB->pred_size() > 1) {
422 if (TrueBBI.CannotBeCopied ||
423 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
424 return false;
425 Dups = TrueBBI.NonPredSize;
426 }
427
428 return true;
429}
430
431/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
432/// with their common predecessor) forms a valid triangle shape for ifcvt.
433/// If 'FalseBranch' is true, it checks if 'true' block's false branch
434/// branches to the false branch rather than the other way around. It also
435/// returns the number of instructions that the ifcvt would need to duplicate
436/// if performed in 'Dups'.
437bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
438 bool FalseBranch, unsigned &Dups) const {
439 Dups = 0;
440 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
441 return false;
442
443 if (TrueBBI.BB->pred_size() > 1) {
444 if (TrueBBI.CannotBeCopied)
445 return false;
446
447 unsigned Size = TrueBBI.NonPredSize;
448 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000449 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000450 // Ends with an unconditional branch. It will be removed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451 --Size;
452 else {
453 MachineBasicBlock *FExit = FalseBranch
454 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
455 if (FExit)
456 // Require a conditional branch
457 ++Size;
458 }
459 }
460 if (Size > TLI->getIfCvtDupBlockSizeLimit())
461 return false;
462 Dups = Size;
463 }
464
465 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
466 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
467 MachineFunction::iterator I = TrueBBI.BB;
468 if (++I == TrueBBI.BB->getParent()->end())
469 return false;
470 TExit = I;
471 }
472 return TExit && TExit == FalseBBI.BB;
473}
474
475static
476MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
477 const TargetInstrInfo *TII) {
478 MachineBasicBlock::iterator I = BB->end();
479 while (I != BB->begin()) {
480 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000481 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000482 break;
483 }
484 return I;
485}
486
487/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
488/// with their common predecessor) forms a valid diamond shape for ifcvt.
489bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
490 unsigned &Dups1, unsigned &Dups2) const {
491 Dups1 = Dups2 = 0;
492 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
493 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
494 return false;
495
496 MachineBasicBlock *TT = TrueBBI.TrueBB;
497 MachineBasicBlock *FT = FalseBBI.TrueBB;
498
499 if (!TT && blockAlwaysFallThrough(TrueBBI))
500 TT = getNextBlock(TrueBBI.BB);
501 if (!FT && blockAlwaysFallThrough(FalseBBI))
502 FT = getNextBlock(FalseBBI.BB);
503 if (TT != FT)
504 return false;
505 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
506 return false;
507 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
508 return false;
509
510 // FIXME: Allow true block to have an early exit?
511 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
512 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
513 return false;
514
515 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
516 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000517 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
518 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
519 // Skip dbg_value instructions
520 while (TI != TIE && TI->isDebugValue())
521 ++TI;
522 while (FI != FIE && FI->isDebugValue())
523 ++FI;
524 while (TI != TIE && FI != FIE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 if (!TI->isIdenticalTo(FI))
526 break;
527 ++Dups1;
528 ++TI;
529 ++FI;
530 }
531
532 TI = firstNonBranchInst(TrueBBI.BB, TII);
533 FI = firstNonBranchInst(FalseBBI.BB, TII);
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000534 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
535 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
536 // Skip dbg_value instructions
537 while (TI != TIB && TI->isDebugValue())
538 --TI;
539 while (FI != FIB && FI->isDebugValue())
540 --FI;
541 while (TI != TIB && FI != FIB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542 if (!TI->isIdenticalTo(FI))
543 break;
544 ++Dups2;
545 --TI;
546 --FI;
547 }
548
549 return true;
550}
551
552/// ScanInstructions - Scan all the instructions in the block to determine if
553/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000554/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555/// instruction which can clobber a predicate (e.g. condition code register).
556/// If so, the block is not predicable unless it's the last instruction.
557void IfConverter::ScanInstructions(BBInfo &BBI) {
558 if (BBI.IsDone)
559 return;
560
561 bool AlreadyPredicated = BBI.Predicate.size() > 0;
562 // First analyze the end of BB branches.
563 BBI.TrueBB = BBI.FalseBB = NULL;
564 BBI.BrCond.clear();
565 BBI.IsBrAnalyzable =
566 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
567 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
568
569 if (BBI.BrCond.size()) {
570 // No false branch. This BB must end with a conditional branch and a
571 // fallthrough.
572 if (!BBI.FalseBB)
573 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng4eb66e62009-06-15 21:24:34 +0000574 if (!BBI.FalseBB) {
575 // Malformed bcc? True and false blocks are the same?
576 BBI.IsUnpredicable = true;
577 return;
578 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 }
580
581 // Then scan all the instructions.
582 BBI.NonPredSize = 0;
583 BBI.ClobbersPred = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
585 I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +0000586 if (I->isDebugValue())
587 continue;
588
Chris Lattner5b930372008-01-07 07:27:27 +0000589 const TargetInstrDesc &TID = I->getDesc();
590 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 BBI.CannotBeCopied = true;
592
593 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000594 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595
596 if (!isCondBr) {
597 if (!isPredicated)
598 BBI.NonPredSize++;
599 else if (!AlreadyPredicated) {
600 // FIXME: This instruction is already predicated before the
601 // if-conversion pass. It's probably something like a conditional move.
602 // Mark this block unpredicable for now.
603 BBI.IsUnpredicable = true;
604 return;
605 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 }
607
608 if (BBI.ClobbersPred && !isPredicated) {
609 // Predicate modification instruction should end the block (except for
610 // already predicated instructions and end of block branches).
611 if (isCondBr) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000612 // A conditional branch is not predicable, but it may be eliminated.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 continue;
614 }
615
616 // Predicate may have been modified, the subsequent (currently)
617 // unpredicated instructions cannot be correctly predicated.
618 BBI.IsUnpredicable = true;
619 return;
620 }
621
622 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
623 // still potentially predicable.
624 std::vector<MachineOperand> PredDefs;
625 if (TII->DefinesPredicate(I, PredDefs))
626 BBI.ClobbersPred = true;
627
Evan Cheng76fe9892009-11-21 06:20:26 +0000628 if (!TII->isPredicable(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 BBI.IsUnpredicable = true;
630 return;
631 }
632 }
633}
634
635/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
636/// predicated by the specified predicate.
637bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000638 SmallVectorImpl<MachineOperand> &Pred,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 bool isTriangle, bool RevBranch) {
640 // If the block is dead or unpredicable, then it cannot be predicated.
641 if (BBI.IsDone || BBI.IsUnpredicable)
642 return false;
643
644 // If it is already predicated, check if its predicate subsumes the new
645 // predicate.
646 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
647 return false;
648
649 if (BBI.BrCond.size()) {
650 if (!isTriangle)
651 return false;
652
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000653 // Test predicate subsumption.
Owen Andersond131b5b2008-08-14 22:49:33 +0000654 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
655 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 if (RevBranch) {
657 if (TII->ReverseBranchCondition(Cond))
658 return false;
659 }
660 if (TII->ReverseBranchCondition(RevPred) ||
661 !TII->SubsumesPredicate(Cond, RevPred))
662 return false;
663 }
664
665 return true;
666}
667
668/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
669/// the specified block. Record its successors and whether it looks like an
670/// if-conversion candidate.
671IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
672 std::vector<IfcvtToken*> &Tokens) {
673 BBInfo &BBI = BBAnalysis[BB->getNumber()];
674
675 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
676 return BBI;
677
678 BBI.BB = BB;
679 BBI.IsBeingAnalyzed = true;
680
681 ScanInstructions(BBI);
682
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000683 // Unanalyzable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000684 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 BBI.IsBeingAnalyzed = false;
686 BBI.IsAnalyzed = true;
687 return BBI;
688 }
689
690 // Do not ifcvt if either path is a back edge to the entry block.
691 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
692 BBI.IsBeingAnalyzed = false;
693 BBI.IsAnalyzed = true;
694 return BBI;
695 }
696
Evan Cheng4eb66e62009-06-15 21:24:34 +0000697 // Do not ifcvt if true and false fallthrough blocks are the same.
698 if (!BBI.FalseBB) {
699 BBI.IsBeingAnalyzed = false;
700 BBI.IsAnalyzed = true;
701 return BBI;
702 }
703
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
705 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
706
707 if (TrueBBI.IsDone && FalseBBI.IsDone) {
708 BBI.IsBeingAnalyzed = false;
709 BBI.IsAnalyzed = true;
710 return BBI;
711 }
712
Owen Andersond131b5b2008-08-14 22:49:33 +0000713 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
715
716 unsigned Dups = 0;
717 unsigned Dups2 = 0;
718 bool TNeedSub = TrueBBI.Predicate.size() > 0;
719 bool FNeedSub = FalseBBI.Predicate.size() > 0;
720 bool Enqueued = false;
721 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
722 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
723 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
724 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
725 FeasibilityAnalysis(FalseBBI, RevCond)) {
726 // Diamond:
727 // EBB
728 // / \_
729 // | |
730 // TBB FBB
731 // \ /
732 // TailBB
733 // Note TailBB can be empty.
734 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
735 Dups2));
736 Enqueued = true;
737 }
738
739 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
740 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
741 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
742 // Triangle:
743 // EBB
744 // | \_
745 // | |
746 // | TBB
747 // | /
748 // FBB
749 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
750 Enqueued = true;
751 }
752
753 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
754 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
755 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
756 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
757 Enqueued = true;
758 }
759
760 if (ValidSimple(TrueBBI, Dups) &&
761 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
762 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
763 // Simple (split, no rejoin):
764 // EBB
765 // | \_
766 // | |
767 // | TBB---> exit
768 // |
769 // FBB
770 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
771 Enqueued = true;
772 }
773
774 if (CanRevCond) {
775 // Try the other path...
776 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
777 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
778 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
779 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
780 Enqueued = true;
781 }
782
783 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
784 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
785 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
786 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
787 Enqueued = true;
788 }
789
790 if (ValidSimple(FalseBBI, Dups) &&
791 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
792 FeasibilityAnalysis(FalseBBI, RevCond)) {
793 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
794 Enqueued = true;
795 }
796 }
797
798 BBI.IsEnqueued = Enqueued;
799 BBI.IsBeingAnalyzed = false;
800 BBI.IsAnalyzed = true;
801 return BBI;
802}
803
804/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson89b9c322010-06-15 18:57:15 +0000805/// candidates.
806void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 std::vector<IfcvtToken*> &Tokens) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 std::set<MachineBasicBlock*> Visited;
809 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
810 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
811 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
812 MachineBasicBlock *BB = *I;
813 AnalyzeBlock(BB, Tokens);
814 }
815 }
816
817 // Sort to favor more complex ifcvt scheme.
818 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819}
820
821/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
822/// that all the intervening blocks are empty (given BB can fall through to its
823/// next block).
824static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
825 MachineFunction::iterator I = BB;
826 MachineFunction::iterator TI = ToBB;
827 MachineFunction::iterator E = BB->getParent()->end();
828 while (++I != TI)
829 if (I == E || !I->empty())
830 return false;
831 return true;
832}
833
834/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
835/// to determine if it can be if-converted. If predecessor is already enqueued,
836/// dequeue it!
837void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
838 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
839 E = BB->pred_end(); PI != E; ++PI) {
840 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
841 if (PBBI.IsDone || PBBI.BB == BB)
842 continue;
843 PBBI.IsAnalyzed = false;
844 PBBI.IsEnqueued = false;
845 }
846}
847
848/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
849///
850static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
851 const TargetInstrInfo *TII) {
Dan Gohmane458ea82008-08-22 16:07:55 +0000852 SmallVector<MachineOperand, 0> NoCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
854}
855
856/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
857/// successors.
858void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
859 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Andersond131b5b2008-08-14 22:49:33 +0000860 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
862 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
863}
864
865/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
866///
867bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
868 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
869 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
870 BBInfo *CvtBBI = &TrueBBI;
871 BBInfo *NextBBI = &FalseBBI;
872
Owen Andersond131b5b2008-08-14 22:49:33 +0000873 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874 if (Kind == ICSimpleFalse)
875 std::swap(CvtBBI, NextBBI);
876
877 if (CvtBBI->IsDone ||
878 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
879 // Something has changed. It's no longer safe to predicate this block.
880 BBI.IsAnalyzed = false;
881 CvtBBI->IsAnalyzed = false;
882 return false;
883 }
884
885 if (Kind == ICSimpleFalse)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000886 if (TII->ReverseBranchCondition(Cond))
887 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888
889 if (CvtBBI->BB->pred_size() > 1) {
890 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000891 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 // the entry block.
893 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
894 } else {
895 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
896
897 // Merge converted block into entry block.
898 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
899 MergeBlocks(BBI, *CvtBBI);
900 }
901
902 bool IterIfcvt = true;
903 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
904 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
905 BBI.HasFallThrough = false;
906 // Now ifcvt'd block will look like this:
907 // BB:
908 // ...
909 // t, f = cmp
910 // if t op
911 // b BBf
912 //
913 // We cannot further ifcvt this block because the unconditional branch
914 // will have to be predicated on the new condition, that will not be
915 // available if cmp executes.
916 IterIfcvt = false;
917 }
918
919 RemoveExtraEdges(BBI);
920
921 // Update block info. BB can be iteratively if-converted.
922 if (!IterIfcvt)
923 BBI.IsDone = true;
924 InvalidatePreds(BBI.BB);
925 CvtBBI->IsDone = true;
926
927 // FIXME: Must maintain LiveIns.
928 return true;
929}
930
931/// IfConvertTriangle - If convert a triangle sub-CFG.
932///
933bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
934 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
935 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
936 BBInfo *CvtBBI = &TrueBBI;
937 BBInfo *NextBBI = &FalseBBI;
938
Owen Andersond131b5b2008-08-14 22:49:33 +0000939 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
941 std::swap(CvtBBI, NextBBI);
942
943 if (CvtBBI->IsDone ||
944 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
945 // Something has changed. It's no longer safe to predicate this block.
946 BBI.IsAnalyzed = false;
947 CvtBBI->IsAnalyzed = false;
948 return false;
949 }
950
951 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000952 if (TII->ReverseBranchCondition(Cond))
953 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954
955 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000956 if (ReverseBranchCondition(*CvtBBI)) {
957 // BB has been changed, modify its predecessors (except for this
958 // one) so they don't get ifcvt'ed based on bad intel.
959 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
960 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
961 MachineBasicBlock *PBB = *PI;
962 if (PBB == BBI.BB)
963 continue;
964 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
965 if (PBBI.IsEnqueued) {
966 PBBI.IsAnalyzed = false;
967 PBBI.IsEnqueued = false;
968 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 }
970 }
971 }
972
973 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
974 bool DupBB = CvtBBI->BB->pred_size() > 1;
975 if (DupBB) {
976 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000977 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 // the entry block.
979 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
980 } else {
981 // Predicate the 'true' block after removing its branch.
982 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
983 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 // Now merge the entry of the triangle with the true block.
986 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
987 MergeBlocks(BBI, *CvtBBI);
988 }
989
990 // If 'true' block has a 'false' successor, add an exit branch to it.
991 if (HasEarlyExit) {
Owen Andersond131b5b2008-08-14 22:49:33 +0000992 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
993 CvtBBI->BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 if (TII->ReverseBranchCondition(RevCond))
995 assert(false && "Unable to reverse branch condition!");
996 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
997 BBI.BB->addSuccessor(CvtBBI->FalseBB);
998 }
999
1000 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001001 // predecessors. Otherwise, add an unconditional branch to 'false'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 bool FalseBBDead = false;
1003 bool IterIfcvt = true;
1004 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1005 if (!isFallThrough) {
1006 // Only merge them if the true block does not fallthrough to the false
1007 // block. By not merging them, we make it possible to iteratively
1008 // ifcvt the blocks.
1009 if (!HasEarlyExit &&
1010 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1011 MergeBlocks(BBI, *NextBBI);
1012 FalseBBDead = true;
1013 } else {
1014 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1015 BBI.HasFallThrough = false;
1016 }
1017 // Mixed predicated and unpredicated code. This cannot be iteratively
1018 // predicated.
1019 IterIfcvt = false;
1020 }
1021
1022 RemoveExtraEdges(BBI);
1023
1024 // Update block info. BB can be iteratively if-converted.
1025 if (!IterIfcvt)
1026 BBI.IsDone = true;
1027 InvalidatePreds(BBI.BB);
1028 CvtBBI->IsDone = true;
1029 if (FalseBBDead)
1030 NextBBI->IsDone = true;
1031
1032 // FIXME: Must maintain LiveIns.
1033 return true;
1034}
1035
1036/// IfConvertDiamond - If convert a diamond sub-CFG.
1037///
1038bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1039 unsigned NumDups1, unsigned NumDups2) {
1040 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1041 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1042 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001043 // True block must fall through or end with an unanalyzable terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 if (!TailBB) {
1045 if (blockAlwaysFallThrough(TrueBBI))
1046 TailBB = FalseBBI.TrueBB;
1047 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1048 }
1049
1050 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1051 TrueBBI.BB->pred_size() > 1 ||
1052 FalseBBI.BB->pred_size() > 1) {
1053 // Something has changed. It's no longer safe to predicate these blocks.
1054 BBI.IsAnalyzed = false;
1055 TrueBBI.IsAnalyzed = false;
1056 FalseBBI.IsAnalyzed = false;
1057 return false;
1058 }
1059
1060 // Merge the 'true' and 'false' blocks by copying the instructions
1061 // from the 'false' block to the 'true' block. That is, unless the true
1062 // block would clobber the predicate, in that case, do the opposite.
1063 BBInfo *BBI1 = &TrueBBI;
1064 BBInfo *BBI2 = &FalseBBI;
Owen Andersond131b5b2008-08-14 22:49:33 +00001065 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001066 if (TII->ReverseBranchCondition(RevCond))
1067 assert(false && "Unable to reverse branch condition!");
Owen Andersond131b5b2008-08-14 22:49:33 +00001068 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1069 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070
1071 // Figure out the more profitable ordering.
1072 bool DoSwap = false;
1073 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1074 DoSwap = true;
1075 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1076 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1077 DoSwap = true;
1078 }
1079 if (DoSwap) {
1080 std::swap(BBI1, BBI2);
1081 std::swap(Cond1, Cond2);
1082 }
1083
1084 // Remove the conditional branch from entry to the blocks.
1085 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1086
1087 // Remove the duplicated instructions at the beginnings of both paths.
1088 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1089 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachf8648062010-06-14 21:30:32 +00001090 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1091 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1092 // Skip dbg_value instructions
1093 while (DI1 != DIE1 && DI1->isDebugValue())
1094 ++DI1;
1095 while (DI2 != DIE2 && DI2->isDebugValue())
1096 ++DI2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 BBI1->NonPredSize -= NumDups1;
1098 BBI2->NonPredSize -= NumDups1;
1099 while (NumDups1 != 0) {
1100 ++DI1;
1101 ++DI2;
1102 --NumDups1;
1103 }
1104 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1105 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1106
1107 // Predicate the 'true' block after removing its branch.
1108 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1109 DI1 = BBI1->BB->end();
Jim Grosbachf8648062010-06-14 21:30:32 +00001110 for (unsigned i = 0; i != NumDups2; ) {
1111 // NumDups2 only counted non-dbg_value instructions, so this won't
1112 // run off the head of the list.
1113 assert (DI1 != BBI1->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 --DI1;
Jim Grosbachf8648062010-06-14 21:30:32 +00001115 // skip dbg_value instructions
1116 if (!DI1->isDebugValue())
1117 ++i;
1118 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 BBI1->BB->erase(DI1, BBI1->BB->end());
1120 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1);
1121
1122 // Predicate the 'false' block.
1123 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1124 DI2 = BBI2->BB->end();
1125 while (NumDups2 != 0) {
Jim Grosbachf8648062010-06-14 21:30:32 +00001126 // NumDups2 only counted non-dbg_value instructions, so this won't
1127 // run off the head of the list.
1128 assert (DI2 != BBI2->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129 --DI2;
Jim Grosbachf8648062010-06-14 21:30:32 +00001130 // skip dbg_value instructions
1131 if (!DI2->isDebugValue())
1132 --NumDups2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 }
1134 PredicateBlock(*BBI2, DI2, *Cond2);
1135
1136 // Merge the true block into the entry of the diamond.
1137 MergeBlocks(BBI, *BBI1);
1138 MergeBlocks(BBI, *BBI2);
1139
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001140 // If the if-converted block falls through or unconditionally branches into
1141 // the tail block, and the tail block does not have other predecessors, then
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 // fold the tail block in as well. Otherwise, unless it falls through to the
1143 // tail, add a unconditional branch to it.
1144 if (TailBB) {
1145 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1146 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1147 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1148 MergeBlocks(BBI, TailBBI);
1149 TailBBI.IsDone = true;
1150 } else {
1151 InsertUncondBranch(BBI.BB, TailBB, TII);
1152 BBI.HasFallThrough = false;
1153 }
1154 }
1155
1156 RemoveExtraEdges(BBI);
1157
1158 // Update block info.
1159 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1160 InvalidatePreds(BBI.BB);
1161
1162 // FIXME: Must maintain LiveIns.
1163 return true;
1164}
1165
1166/// PredicateBlock - Predicate instructions from the start of the block to the
1167/// specified end with the specified condition.
1168void IfConverter::PredicateBlock(BBInfo &BBI,
1169 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +00001170 SmallVectorImpl<MachineOperand> &Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +00001172 if (I->isDebugValue() || TII->isPredicated(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173 continue;
1174 if (!TII->PredicateInstruction(I, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001175#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001176 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001177#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001178 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 }
1180 }
1181
1182 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1183
1184 BBI.IsAnalyzed = false;
1185 BBI.NonPredSize = 0;
1186
1187 NumIfConvBBs++;
1188}
1189
1190/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1191/// the destination block. Skip end of block branches if IgnoreBr is true.
1192void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +00001193 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 bool IgnoreBr) {
Dan Gohman221a4372008-07-07 23:14:23 +00001195 MachineFunction &MF = *ToBBI.BB->getParent();
1196
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001197 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1198 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001199 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 bool isPredicated = TII->isPredicated(I);
1201 // Do not copy the end of the block branches.
Chris Lattner5b930372008-01-07 07:27:27 +00001202 if (IgnoreBr && !isPredicated && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 break;
1204
Dan Gohman221a4372008-07-07 23:14:23 +00001205 MachineInstr *MI = MF.CloneMachineInstr(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1207 ToBBI.NonPredSize++;
1208
Jim Grosbach3c47a2c2010-06-04 23:01:26 +00001209 if (!isPredicated && !MI->isDebugValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 if (!TII->PredicateInstruction(MI, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001211#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001212 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001213#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001214 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 }
1216 }
1217
1218 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1219 FromBBI.BB->succ_end());
1220 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1221 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1222
1223 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1224 MachineBasicBlock *Succ = Succs[i];
1225 // Fallthrough edge can't be transferred.
1226 if (Succ == FallThrough)
1227 continue;
Dan Gohman710011c2009-05-05 21:10:19 +00001228 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 }
1230
1231 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1232 std::back_inserter(ToBBI.Predicate));
1233 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1234
1235 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1236 ToBBI.IsAnalyzed = false;
1237
1238 NumDupBBs++;
1239}
1240
1241/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1242///
1243void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1244 ToBBI.BB->splice(ToBBI.BB->end(),
1245 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1246
Bob Wilsonf3dc37d2009-05-14 18:08:41 +00001247 // Redirect all branches to FromBB to ToBB.
1248 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1249 FromBBI.BB->pred_end());
1250 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1251 MachineBasicBlock *Pred = Preds[i];
1252 if (Pred == ToBBI.BB)
1253 continue;
1254 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1255 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256
1257 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1258 FromBBI.BB->succ_end());
1259 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1260 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1261
1262 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1263 MachineBasicBlock *Succ = Succs[i];
1264 // Fallthrough edge can't be transferred.
1265 if (Succ == FallThrough)
1266 continue;
1267 FromBBI.BB->removeSuccessor(Succ);
Dan Gohman710011c2009-05-05 21:10:19 +00001268 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 }
1270
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001271 // Now FromBBI always falls through to the next block!
Bob Wilson58c9e3c2009-05-13 23:48:58 +00001272 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 FromBBI.BB->addSuccessor(NBB);
1274
1275 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1276 std::back_inserter(ToBBI.Predicate));
1277 FromBBI.Predicate.clear();
1278
1279 ToBBI.NonPredSize += FromBBI.NonPredSize;
1280 FromBBI.NonPredSize = 0;
1281
1282 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1283 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1284 ToBBI.IsAnalyzed = false;
1285 FromBBI.IsAnalyzed = false;
1286}