blob: be9e1f113b56b8019bd1c2ed5280c4c161ab233f [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
118 /// IfcvtToken - Record information about pending if-conversions to attemp:
119 /// 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;
Bob Wilsonafe63292009-10-27 23:49:38 +0000151 CodeGenOpt::Level OptLevel;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 public:
153 static char ID;
Bob Wilsonafe63292009-10-27 23:49:38 +0000154 IfConverter(CodeGenOpt::Level OL) :
155 MachineFunctionPass(&ID), FnNum(-1), OptLevel(OL) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156
157 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga911dfe2008-06-04 09:15:51 +0000158 virtual const char *getPassName() const { return "If Converter"; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159
160 private:
161 bool ReverseBranchCondition(BBInfo &BBI);
162 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
163 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
164 bool FalseBranch, unsigned &Dups) const;
165 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
166 unsigned &Dups1, unsigned &Dups2) const;
167 void ScanInstructions(BBInfo &BBI);
168 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
169 std::vector<IfcvtToken*> &Tokens);
Owen Andersond131b5b2008-08-14 22:49:33 +0000170 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 bool isTriangle = false, bool RevBranch = false);
172 bool AnalyzeBlocks(MachineFunction &MF,
173 std::vector<IfcvtToken*> &Tokens);
174 void InvalidatePreds(MachineBasicBlock *BB);
175 void RemoveExtraEdges(BBInfo &BBI);
176 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
177 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
178 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
179 unsigned NumDups1, unsigned NumDups2);
180 void PredicateBlock(BBInfo &BBI,
181 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +0000182 SmallVectorImpl<MachineOperand> &Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000184 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 bool IgnoreBr = false);
186 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
187
188 bool MeetIfcvtSizeLimit(unsigned Size) const {
189 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit();
190 }
191
192 // blockAlwaysFallThrough - Block ends without a terminator.
193 bool blockAlwaysFallThrough(BBInfo &BBI) const {
194 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
195 }
196
197 // IfcvtTokenCmp - Used to sort if-conversion candidates.
198 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
199 int Incr1 = (C1->Kind == ICDiamond)
200 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
201 int Incr2 = (C2->Kind == ICDiamond)
202 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
203 if (Incr1 > Incr2)
204 return true;
205 else if (Incr1 == Incr2) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000206 // Favors subsumption.
207 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 return true;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000209 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 // Favors diamond over triangle, etc.
211 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
212 return true;
213 else if (C1->Kind == C2->Kind)
214 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
215 }
216 }
217 return false;
218 }
219 };
220
221 char IfConverter::ID = 0;
222}
223
Bob Wilsonafe63292009-10-27 23:49:38 +0000224FunctionPass *llvm::createIfConverterPass(CodeGenOpt::Level OptLevel) {
225 return new IfConverter(OptLevel);
226}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227
228bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
229 TLI = MF.getTarget().getTargetLowering();
230 TII = MF.getTarget().getInstrInfo();
231 if (!TII) return false;
232
Daniel Dunbar005975c2009-07-25 00:23:56 +0000233 DEBUG(errs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000234 << MF.getFunction()->getName() << "\'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235
236 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000237 DEBUG(errs() << " skipped\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 return false;
239 }
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000240 DEBUG(errs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241
242 MF.RenumberBlocks();
243 BBAnalysis.resize(MF.getNumBlockIDs());
244
245 // Look for root nodes, i.e. blocks without successors.
246 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000247 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 Roots.push_back(I);
249
250 std::vector<IfcvtToken*> Tokens;
251 MadeChange = false;
252 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
253 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
254 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000255 // Do an initial analysis for each basic block and find all the potential
256 // candidates to perform if-conversion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 bool Change = AnalyzeBlocks(MF, Tokens);
258 while (!Tokens.empty()) {
259 IfcvtToken *Token = Tokens.back();
260 Tokens.pop_back();
261 BBInfo &BBI = Token->BBI;
262 IfcvtKind Kind = Token->Kind;
Nuno Lopes06cea782008-11-04 13:02:59 +0000263 unsigned NumDups = Token->NumDups;
Duncan Sands5c2a51a2008-11-04 18:05:30 +0000264 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes06cea782008-11-04 13:02:59 +0000265
266 delete Token;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267
268 // If the block has been evicted out of the queue or it has already been
269 // marked dead (due to it being predicated), then skip it.
270 if (BBI.IsDone)
271 BBI.IsEnqueued = false;
272 if (!BBI.IsEnqueued)
273 continue;
274
275 BBI.IsEnqueued = false;
276
277 bool RetVal = false;
278 switch (Kind) {
279 default: assert(false && "Unexpected!");
280 break;
281 case ICSimple:
282 case ICSimpleFalse: {
283 bool isFalse = Kind == ICSimpleFalse;
284 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000285 DEBUG(errs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"")
286 << "): BB#" << BBI.BB->getNumber() << " ("
287 << ((Kind == ICSimpleFalse)
288 ? BBI.FalseBB->getNumber()
289 : BBI.TrueBB->getNumber()) << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 RetVal = IfConvertSimple(BBI, Kind);
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000291 DEBUG(errs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000292 if (RetVal) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 if (isFalse) NumSimpleFalse++;
294 else NumSimple++;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000295 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 break;
297 }
298 case ICTriangle:
299 case ICTriangleRev:
300 case ICTriangleFalse:
301 case ICTriangleFRev: {
302 bool isFalse = Kind == ICTriangleFalse;
303 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
304 if (DisableTriangle && !isFalse && !isRev) break;
305 if (DisableTriangleR && !isFalse && isRev) break;
306 if (DisableTriangleF && isFalse && !isRev) break;
307 if (DisableTriangleFR && isFalse && isRev) break;
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000308 DEBUG(errs() << "Ifcvt (Triangle");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 if (isFalse)
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000310 DEBUG(errs() << " false");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311 if (isRev)
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000312 DEBUG(errs() << " rev");
313 DEBUG(errs() << "): BB#" << BBI.BB->getNumber() << " (T:"
314 << BBI.TrueBB->getNumber() << ",F:"
315 << BBI.FalseBB->getNumber() << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 RetVal = IfConvertTriangle(BBI, Kind);
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000317 DEBUG(errs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 if (RetVal) {
319 if (isFalse) {
320 if (isRev) NumTriangleFRev++;
321 else NumTriangleFalse++;
322 } else {
323 if (isRev) NumTriangleRev++;
324 else NumTriangle++;
325 }
326 }
327 break;
328 }
329 case ICDiamond: {
330 if (DisableDiamond) break;
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000331 DEBUG(errs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
332 << BBI.TrueBB->getNumber() << ",F:"
333 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes06cea782008-11-04 13:02:59 +0000334 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000335 DEBUG(errs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 if (RetVal) NumDiamonds++;
337 break;
338 }
339 }
340
341 Change |= RetVal;
342
343 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
344 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
345 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
346 break;
347 }
348
349 if (!Change)
350 break;
351 MadeChange |= Change;
352 }
353
354 // Delete tokens in case of early exit.
355 while (!Tokens.empty()) {
356 IfcvtToken *Token = Tokens.back();
357 Tokens.pop_back();
358 delete Token;
359 }
360
361 Tokens.clear();
362 Roots.clear();
363 BBAnalysis.clear();
364
Evan Cheng9dcb7602009-09-04 07:47:40 +0000365 if (MadeChange) {
Bob Wilsonafe63292009-10-27 23:49:38 +0000366 BranchFolder BF(false, OptLevel);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000367 BF.OptimizeFunction(MF, TII,
368 MF.getTarget().getRegisterInfo(),
369 getAnalysisIfAvailable<MachineModuleInfo>());
370 }
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 return MadeChange;
373}
374
375/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
376/// its 'true' successor.
377static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
378 MachineBasicBlock *TrueBB) {
379 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
380 E = BB->succ_end(); SI != E; ++SI) {
381 MachineBasicBlock *SuccBB = *SI;
382 if (SuccBB != TrueBB)
383 return SuccBB;
384 }
385 return NULL;
386}
387
388/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000389/// branch. Swap block's 'true' and 'false' successors.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
391 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
392 TII->RemoveBranch(*BBI.BB);
393 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
394 std::swap(BBI.TrueBB, BBI.FalseBB);
395 return true;
396 }
397 return false;
398}
399
400/// getNextBlock - Returns the next block in the function blocks ordering. If
401/// it is the end, returns NULL.
402static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
403 MachineFunction::iterator I = BB;
404 MachineFunction::iterator E = BB->getParent()->end();
405 if (++I == E)
406 return NULL;
407 return I;
408}
409
410/// ValidSimple - Returns true if the 'true' block (along with its
411/// predecessor) forms a valid simple shape for ifcvt. It also returns the
412/// number of instructions that the ifcvt would need to duplicate if performed
413/// in Dups.
414bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
415 Dups = 0;
416 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
417 return false;
418
419 if (TrueBBI.IsBrAnalyzable)
420 return false;
421
422 if (TrueBBI.BB->pred_size() > 1) {
423 if (TrueBBI.CannotBeCopied ||
424 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
425 return false;
426 Dups = TrueBBI.NonPredSize;
427 }
428
429 return true;
430}
431
432/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
433/// with their common predecessor) forms a valid triangle shape for ifcvt.
434/// If 'FalseBranch' is true, it checks if 'true' block's false branch
435/// branches to the false branch rather than the other way around. It also
436/// returns the number of instructions that the ifcvt would need to duplicate
437/// if performed in 'Dups'.
438bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
439 bool FalseBranch, unsigned &Dups) const {
440 Dups = 0;
441 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
442 return false;
443
444 if (TrueBBI.BB->pred_size() > 1) {
445 if (TrueBBI.CannotBeCopied)
446 return false;
447
448 unsigned Size = TrueBBI.NonPredSize;
449 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000450 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000451 // Ends with an unconditional branch. It will be removed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 --Size;
453 else {
454 MachineBasicBlock *FExit = FalseBranch
455 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
456 if (FExit)
457 // Require a conditional branch
458 ++Size;
459 }
460 }
461 if (Size > TLI->getIfCvtDupBlockSizeLimit())
462 return false;
463 Dups = Size;
464 }
465
466 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
467 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
468 MachineFunction::iterator I = TrueBBI.BB;
469 if (++I == TrueBBI.BB->getParent()->end())
470 return false;
471 TExit = I;
472 }
473 return TExit && TExit == FalseBBI.BB;
474}
475
476static
477MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
478 const TargetInstrInfo *TII) {
479 MachineBasicBlock::iterator I = BB->end();
480 while (I != BB->begin()) {
481 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000482 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 break;
484 }
485 return I;
486}
487
488/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
489/// with their common predecessor) forms a valid diamond shape for ifcvt.
490bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
491 unsigned &Dups1, unsigned &Dups2) const {
492 Dups1 = Dups2 = 0;
493 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
494 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
495 return false;
496
497 MachineBasicBlock *TT = TrueBBI.TrueBB;
498 MachineBasicBlock *FT = FalseBBI.TrueBB;
499
500 if (!TT && blockAlwaysFallThrough(TrueBBI))
501 TT = getNextBlock(TrueBBI.BB);
502 if (!FT && blockAlwaysFallThrough(FalseBBI))
503 FT = getNextBlock(FalseBBI.BB);
504 if (TT != FT)
505 return false;
506 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
507 return false;
508 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
509 return false;
510
511 // FIXME: Allow true block to have an early exit?
512 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
513 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
514 return false;
515
516 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
517 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
518 while (TI != TrueBBI.BB->end() && FI != FalseBBI.BB->end()) {
519 if (!TI->isIdenticalTo(FI))
520 break;
521 ++Dups1;
522 ++TI;
523 ++FI;
524 }
525
526 TI = firstNonBranchInst(TrueBBI.BB, TII);
527 FI = firstNonBranchInst(FalseBBI.BB, TII);
528 while (TI != TrueBBI.BB->begin() && FI != FalseBBI.BB->begin()) {
529 if (!TI->isIdenticalTo(FI))
530 break;
531 ++Dups2;
532 --TI;
533 --FI;
534 }
535
536 return true;
537}
538
539/// ScanInstructions - Scan all the instructions in the block to determine if
540/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000541/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542/// instruction which can clobber a predicate (e.g. condition code register).
543/// If so, the block is not predicable unless it's the last instruction.
544void IfConverter::ScanInstructions(BBInfo &BBI) {
545 if (BBI.IsDone)
546 return;
547
548 bool AlreadyPredicated = BBI.Predicate.size() > 0;
549 // First analyze the end of BB branches.
550 BBI.TrueBB = BBI.FalseBB = NULL;
551 BBI.BrCond.clear();
552 BBI.IsBrAnalyzable =
553 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
554 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
555
556 if (BBI.BrCond.size()) {
557 // No false branch. This BB must end with a conditional branch and a
558 // fallthrough.
559 if (!BBI.FalseBB)
560 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng4eb66e62009-06-15 21:24:34 +0000561 if (!BBI.FalseBB) {
562 // Malformed bcc? True and false blocks are the same?
563 BBI.IsUnpredicable = true;
564 return;
565 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 }
567
568 // Then scan all the instructions.
569 BBI.NonPredSize = 0;
570 BBI.ClobbersPred = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
572 I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +0000573 const TargetInstrDesc &TID = I->getDesc();
574 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 BBI.CannotBeCopied = true;
576
577 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000578 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579
580 if (!isCondBr) {
581 if (!isPredicated)
582 BBI.NonPredSize++;
583 else if (!AlreadyPredicated) {
584 // FIXME: This instruction is already predicated before the
585 // if-conversion pass. It's probably something like a conditional move.
586 // Mark this block unpredicable for now.
587 BBI.IsUnpredicable = true;
588 return;
589 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 }
591
592 if (BBI.ClobbersPred && !isPredicated) {
593 // Predicate modification instruction should end the block (except for
594 // already predicated instructions and end of block branches).
595 if (isCondBr) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000596 // A conditional branch is not predicable, but it may be eliminated.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597 continue;
598 }
599
600 // Predicate may have been modified, the subsequent (currently)
601 // unpredicated instructions cannot be correctly predicated.
602 BBI.IsUnpredicable = true;
603 return;
604 }
605
606 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
607 // still potentially predicable.
608 std::vector<MachineOperand> PredDefs;
609 if (TII->DefinesPredicate(I, PredDefs))
610 BBI.ClobbersPred = true;
611
Chris Lattner5b930372008-01-07 07:27:27 +0000612 if (!TID.isPredicable()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 BBI.IsUnpredicable = true;
614 return;
615 }
616 }
617}
618
619/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
620/// predicated by the specified predicate.
621bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000622 SmallVectorImpl<MachineOperand> &Pred,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 bool isTriangle, bool RevBranch) {
624 // If the block is dead or unpredicable, then it cannot be predicated.
625 if (BBI.IsDone || BBI.IsUnpredicable)
626 return false;
627
628 // If it is already predicated, check if its predicate subsumes the new
629 // predicate.
630 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
631 return false;
632
633 if (BBI.BrCond.size()) {
634 if (!isTriangle)
635 return false;
636
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000637 // Test predicate subsumption.
Owen Andersond131b5b2008-08-14 22:49:33 +0000638 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
639 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 if (RevBranch) {
641 if (TII->ReverseBranchCondition(Cond))
642 return false;
643 }
644 if (TII->ReverseBranchCondition(RevPred) ||
645 !TII->SubsumesPredicate(Cond, RevPred))
646 return false;
647 }
648
649 return true;
650}
651
652/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
653/// the specified block. Record its successors and whether it looks like an
654/// if-conversion candidate.
655IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
656 std::vector<IfcvtToken*> &Tokens) {
657 BBInfo &BBI = BBAnalysis[BB->getNumber()];
658
659 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
660 return BBI;
661
662 BBI.BB = BB;
663 BBI.IsBeingAnalyzed = true;
664
665 ScanInstructions(BBI);
666
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000667 // Unanalyzable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000668 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 BBI.IsBeingAnalyzed = false;
670 BBI.IsAnalyzed = true;
671 return BBI;
672 }
673
674 // Do not ifcvt if either path is a back edge to the entry block.
675 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
676 BBI.IsBeingAnalyzed = false;
677 BBI.IsAnalyzed = true;
678 return BBI;
679 }
680
Evan Cheng4eb66e62009-06-15 21:24:34 +0000681 // Do not ifcvt if true and false fallthrough blocks are the same.
682 if (!BBI.FalseBB) {
683 BBI.IsBeingAnalyzed = false;
684 BBI.IsAnalyzed = true;
685 return BBI;
686 }
687
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
689 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
690
691 if (TrueBBI.IsDone && FalseBBI.IsDone) {
692 BBI.IsBeingAnalyzed = false;
693 BBI.IsAnalyzed = true;
694 return BBI;
695 }
696
Owen Andersond131b5b2008-08-14 22:49:33 +0000697 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
699
700 unsigned Dups = 0;
701 unsigned Dups2 = 0;
702 bool TNeedSub = TrueBBI.Predicate.size() > 0;
703 bool FNeedSub = FalseBBI.Predicate.size() > 0;
704 bool Enqueued = false;
705 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
706 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
707 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
708 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
709 FeasibilityAnalysis(FalseBBI, RevCond)) {
710 // Diamond:
711 // EBB
712 // / \_
713 // | |
714 // TBB FBB
715 // \ /
716 // TailBB
717 // Note TailBB can be empty.
718 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
719 Dups2));
720 Enqueued = true;
721 }
722
723 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
724 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
725 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
726 // Triangle:
727 // EBB
728 // | \_
729 // | |
730 // | TBB
731 // | /
732 // FBB
733 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
734 Enqueued = true;
735 }
736
737 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
738 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
739 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
740 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
741 Enqueued = true;
742 }
743
744 if (ValidSimple(TrueBBI, Dups) &&
745 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
746 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
747 // Simple (split, no rejoin):
748 // EBB
749 // | \_
750 // | |
751 // | TBB---> exit
752 // |
753 // FBB
754 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
755 Enqueued = true;
756 }
757
758 if (CanRevCond) {
759 // Try the other path...
760 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
761 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
762 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
763 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
764 Enqueued = true;
765 }
766
767 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
768 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
769 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
770 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
771 Enqueued = true;
772 }
773
774 if (ValidSimple(FalseBBI, Dups) &&
775 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
776 FeasibilityAnalysis(FalseBBI, RevCond)) {
777 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
778 Enqueued = true;
779 }
780 }
781
782 BBI.IsEnqueued = Enqueued;
783 BBI.IsBeingAnalyzed = false;
784 BBI.IsAnalyzed = true;
785 return BBI;
786}
787
788/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
789/// candidates. It returns true if any CFG restructuring is done to expose more
790/// if-conversion opportunities.
791bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
792 std::vector<IfcvtToken*> &Tokens) {
793 bool Change = false;
794 std::set<MachineBasicBlock*> Visited;
795 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
796 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
797 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
798 MachineBasicBlock *BB = *I;
799 AnalyzeBlock(BB, Tokens);
800 }
801 }
802
803 // Sort to favor more complex ifcvt scheme.
804 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
805
806 return Change;
807}
808
809/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
810/// that all the intervening blocks are empty (given BB can fall through to its
811/// next block).
812static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
813 MachineFunction::iterator I = BB;
814 MachineFunction::iterator TI = ToBB;
815 MachineFunction::iterator E = BB->getParent()->end();
816 while (++I != TI)
817 if (I == E || !I->empty())
818 return false;
819 return true;
820}
821
822/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
823/// to determine if it can be if-converted. If predecessor is already enqueued,
824/// dequeue it!
825void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
826 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
827 E = BB->pred_end(); PI != E; ++PI) {
828 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
829 if (PBBI.IsDone || PBBI.BB == BB)
830 continue;
831 PBBI.IsAnalyzed = false;
832 PBBI.IsEnqueued = false;
833 }
834}
835
836/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
837///
838static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
839 const TargetInstrInfo *TII) {
Dan Gohmane458ea82008-08-22 16:07:55 +0000840 SmallVector<MachineOperand, 0> NoCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
842}
843
844/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
845/// successors.
846void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
847 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Andersond131b5b2008-08-14 22:49:33 +0000848 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
850 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
851}
852
853/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
854///
855bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
856 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
857 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
858 BBInfo *CvtBBI = &TrueBBI;
859 BBInfo *NextBBI = &FalseBBI;
860
Owen Andersond131b5b2008-08-14 22:49:33 +0000861 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 if (Kind == ICSimpleFalse)
863 std::swap(CvtBBI, NextBBI);
864
865 if (CvtBBI->IsDone ||
866 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
867 // Something has changed. It's no longer safe to predicate this block.
868 BBI.IsAnalyzed = false;
869 CvtBBI->IsAnalyzed = false;
870 return false;
871 }
872
873 if (Kind == ICSimpleFalse)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000874 if (TII->ReverseBranchCondition(Cond))
875 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876
877 if (CvtBBI->BB->pred_size() > 1) {
878 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000879 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 // the entry block.
881 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
882 } else {
883 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
884
885 // Merge converted block into entry block.
886 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
887 MergeBlocks(BBI, *CvtBBI);
888 }
889
890 bool IterIfcvt = true;
891 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
892 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
893 BBI.HasFallThrough = false;
894 // Now ifcvt'd block will look like this:
895 // BB:
896 // ...
897 // t, f = cmp
898 // if t op
899 // b BBf
900 //
901 // We cannot further ifcvt this block because the unconditional branch
902 // will have to be predicated on the new condition, that will not be
903 // available if cmp executes.
904 IterIfcvt = false;
905 }
906
907 RemoveExtraEdges(BBI);
908
909 // Update block info. BB can be iteratively if-converted.
910 if (!IterIfcvt)
911 BBI.IsDone = true;
912 InvalidatePreds(BBI.BB);
913 CvtBBI->IsDone = true;
914
915 // FIXME: Must maintain LiveIns.
916 return true;
917}
918
919/// IfConvertTriangle - If convert a triangle sub-CFG.
920///
921bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
922 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
923 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
924 BBInfo *CvtBBI = &TrueBBI;
925 BBInfo *NextBBI = &FalseBBI;
926
Owen Andersond131b5b2008-08-14 22:49:33 +0000927 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
929 std::swap(CvtBBI, NextBBI);
930
931 if (CvtBBI->IsDone ||
932 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
933 // Something has changed. It's no longer safe to predicate this block.
934 BBI.IsAnalyzed = false;
935 CvtBBI->IsAnalyzed = false;
936 return false;
937 }
938
939 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000940 if (TII->ReverseBranchCondition(Cond))
941 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942
943 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000944 if (ReverseBranchCondition(*CvtBBI)) {
945 // BB has been changed, modify its predecessors (except for this
946 // one) so they don't get ifcvt'ed based on bad intel.
947 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
948 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
949 MachineBasicBlock *PBB = *PI;
950 if (PBB == BBI.BB)
951 continue;
952 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
953 if (PBBI.IsEnqueued) {
954 PBBI.IsAnalyzed = false;
955 PBBI.IsEnqueued = false;
956 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 }
958 }
959 }
960
961 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
962 bool DupBB = CvtBBI->BB->pred_size() > 1;
963 if (DupBB) {
964 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000965 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966 // the entry block.
967 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
968 } else {
969 // Predicate the 'true' block after removing its branch.
970 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
971 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 // Now merge the entry of the triangle with the true block.
974 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
975 MergeBlocks(BBI, *CvtBBI);
976 }
977
978 // If 'true' block has a 'false' successor, add an exit branch to it.
979 if (HasEarlyExit) {
Owen Andersond131b5b2008-08-14 22:49:33 +0000980 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
981 CvtBBI->BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 if (TII->ReverseBranchCondition(RevCond))
983 assert(false && "Unable to reverse branch condition!");
984 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
985 BBI.BB->addSuccessor(CvtBBI->FalseBB);
986 }
987
988 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000989 // predecessors. Otherwise, add an unconditional branch to 'false'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 bool FalseBBDead = false;
991 bool IterIfcvt = true;
992 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
993 if (!isFallThrough) {
994 // Only merge them if the true block does not fallthrough to the false
995 // block. By not merging them, we make it possible to iteratively
996 // ifcvt the blocks.
997 if (!HasEarlyExit &&
998 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
999 MergeBlocks(BBI, *NextBBI);
1000 FalseBBDead = true;
1001 } else {
1002 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1003 BBI.HasFallThrough = false;
1004 }
1005 // Mixed predicated and unpredicated code. This cannot be iteratively
1006 // predicated.
1007 IterIfcvt = false;
1008 }
1009
1010 RemoveExtraEdges(BBI);
1011
1012 // Update block info. BB can be iteratively if-converted.
1013 if (!IterIfcvt)
1014 BBI.IsDone = true;
1015 InvalidatePreds(BBI.BB);
1016 CvtBBI->IsDone = true;
1017 if (FalseBBDead)
1018 NextBBI->IsDone = true;
1019
1020 // FIXME: Must maintain LiveIns.
1021 return true;
1022}
1023
1024/// IfConvertDiamond - If convert a diamond sub-CFG.
1025///
1026bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1027 unsigned NumDups1, unsigned NumDups2) {
1028 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1029 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1030 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001031 // True block must fall through or end with an unanalyzable terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 if (!TailBB) {
1033 if (blockAlwaysFallThrough(TrueBBI))
1034 TailBB = FalseBBI.TrueBB;
1035 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1036 }
1037
1038 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1039 TrueBBI.BB->pred_size() > 1 ||
1040 FalseBBI.BB->pred_size() > 1) {
1041 // Something has changed. It's no longer safe to predicate these blocks.
1042 BBI.IsAnalyzed = false;
1043 TrueBBI.IsAnalyzed = false;
1044 FalseBBI.IsAnalyzed = false;
1045 return false;
1046 }
1047
1048 // Merge the 'true' and 'false' blocks by copying the instructions
1049 // from the 'false' block to the 'true' block. That is, unless the true
1050 // block would clobber the predicate, in that case, do the opposite.
1051 BBInfo *BBI1 = &TrueBBI;
1052 BBInfo *BBI2 = &FalseBBI;
Owen Andersond131b5b2008-08-14 22:49:33 +00001053 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001054 if (TII->ReverseBranchCondition(RevCond))
1055 assert(false && "Unable to reverse branch condition!");
Owen Andersond131b5b2008-08-14 22:49:33 +00001056 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1057 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058
1059 // Figure out the more profitable ordering.
1060 bool DoSwap = false;
1061 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1062 DoSwap = true;
1063 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1064 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1065 DoSwap = true;
1066 }
1067 if (DoSwap) {
1068 std::swap(BBI1, BBI2);
1069 std::swap(Cond1, Cond2);
1070 }
1071
1072 // Remove the conditional branch from entry to the blocks.
1073 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1074
1075 // Remove the duplicated instructions at the beginnings of both paths.
1076 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1077 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1078 BBI1->NonPredSize -= NumDups1;
1079 BBI2->NonPredSize -= NumDups1;
1080 while (NumDups1 != 0) {
1081 ++DI1;
1082 ++DI2;
1083 --NumDups1;
1084 }
1085 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1086 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1087
1088 // Predicate the 'true' block after removing its branch.
1089 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1090 DI1 = BBI1->BB->end();
1091 for (unsigned i = 0; i != NumDups2; ++i)
1092 --DI1;
1093 BBI1->BB->erase(DI1, BBI1->BB->end());
1094 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1);
1095
1096 // Predicate the 'false' block.
1097 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1098 DI2 = BBI2->BB->end();
1099 while (NumDups2 != 0) {
1100 --DI2;
1101 --NumDups2;
1102 }
1103 PredicateBlock(*BBI2, DI2, *Cond2);
1104
1105 // Merge the true block into the entry of the diamond.
1106 MergeBlocks(BBI, *BBI1);
1107 MergeBlocks(BBI, *BBI2);
1108
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001109 // If the if-converted block falls through or unconditionally branches into
1110 // the tail block, and the tail block does not have other predecessors, then
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 // fold the tail block in as well. Otherwise, unless it falls through to the
1112 // tail, add a unconditional branch to it.
1113 if (TailBB) {
1114 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1115 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1116 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1117 MergeBlocks(BBI, TailBBI);
1118 TailBBI.IsDone = true;
1119 } else {
1120 InsertUncondBranch(BBI.BB, TailBB, TII);
1121 BBI.HasFallThrough = false;
1122 }
1123 }
1124
1125 RemoveExtraEdges(BBI);
1126
1127 // Update block info.
1128 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1129 InvalidatePreds(BBI.BB);
1130
1131 // FIXME: Must maintain LiveIns.
1132 return true;
1133}
1134
1135/// PredicateBlock - Predicate instructions from the start of the block to the
1136/// specified end with the specified condition.
1137void IfConverter::PredicateBlock(BBInfo &BBI,
1138 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +00001139 SmallVectorImpl<MachineOperand> &Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1141 if (TII->isPredicated(I))
1142 continue;
1143 if (!TII->PredicateInstruction(I, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001144#ifndef NDEBUG
Chris Lattnerd71b0b02009-08-23 03:41:05 +00001145 errs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001146#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001147 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 }
1149 }
1150
1151 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1152
1153 BBI.IsAnalyzed = false;
1154 BBI.NonPredSize = 0;
1155
1156 NumIfConvBBs++;
1157}
1158
1159/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1160/// the destination block. Skip end of block branches if IgnoreBr is true.
1161void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +00001162 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 bool IgnoreBr) {
Dan Gohman221a4372008-07-07 23:14:23 +00001164 MachineFunction &MF = *ToBBI.BB->getParent();
1165
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1167 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001168 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 bool isPredicated = TII->isPredicated(I);
1170 // Do not copy the end of the block branches.
Chris Lattner5b930372008-01-07 07:27:27 +00001171 if (IgnoreBr && !isPredicated && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 break;
1173
Dan Gohman221a4372008-07-07 23:14:23 +00001174 MachineInstr *MI = MF.CloneMachineInstr(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1176 ToBBI.NonPredSize++;
1177
1178 if (!isPredicated)
1179 if (!TII->PredicateInstruction(MI, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001180#ifndef NDEBUG
Chris Lattnerd71b0b02009-08-23 03:41:05 +00001181 errs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001182#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001183 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 }
1185 }
1186
1187 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1188 FromBBI.BB->succ_end());
1189 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1190 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1191
1192 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1193 MachineBasicBlock *Succ = Succs[i];
1194 // Fallthrough edge can't be transferred.
1195 if (Succ == FallThrough)
1196 continue;
Dan Gohman710011c2009-05-05 21:10:19 +00001197 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 }
1199
1200 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1201 std::back_inserter(ToBBI.Predicate));
1202 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1203
1204 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1205 ToBBI.IsAnalyzed = false;
1206
1207 NumDupBBs++;
1208}
1209
1210/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1211///
1212void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1213 ToBBI.BB->splice(ToBBI.BB->end(),
1214 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1215
Bob Wilsonf3dc37d2009-05-14 18:08:41 +00001216 // Redirect all branches to FromBB to ToBB.
1217 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1218 FromBBI.BB->pred_end());
1219 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1220 MachineBasicBlock *Pred = Preds[i];
1221 if (Pred == ToBBI.BB)
1222 continue;
1223 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1224 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225
1226 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1227 FromBBI.BB->succ_end());
1228 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1229 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1230
1231 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1232 MachineBasicBlock *Succ = Succs[i];
1233 // Fallthrough edge can't be transferred.
1234 if (Succ == FallThrough)
1235 continue;
1236 FromBBI.BB->removeSuccessor(Succ);
Dan Gohman710011c2009-05-05 21:10:19 +00001237 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 }
1239
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001240 // Now FromBBI always falls through to the next block!
Bob Wilson58c9e3c2009-05-13 23:48:58 +00001241 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 FromBBI.BB->addSuccessor(NBB);
1243
1244 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1245 std::back_inserter(ToBBI.Predicate));
1246 FromBBI.Predicate.clear();
1247
1248 ToBBI.NonPredSize += FromBBI.NonPredSize;
1249 FromBBI.NonPredSize = 0;
1250
1251 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1252 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1253 ToBBI.IsAnalyzed = false;
1254 FromBBI.IsAnalyzed = false;
1255}