blob: 8d212a606fdf305012b13e8e20decadcb19923c0 [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"
15#include "llvm/Function.h"
16#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineModuleInfo.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/Target/TargetInstrInfo.h"
20#include "llvm/Target/TargetLowering.h"
21#include "llvm/Target/TargetMachine.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/STLExtras.h"
27using namespace llvm;
28
Chris Lattner4335bff2008-01-07 05:40:58 +000029// Hidden options for help debugging.
30static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
34 cl::init(false), cl::Hidden);
35static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
36 cl::init(false), cl::Hidden);
37static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
38 cl::init(false), cl::Hidden);
39static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
40 cl::init(false), cl::Hidden);
41static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
42 cl::init(false), cl::Hidden);
43static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
44 cl::init(false), cl::Hidden);
45static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
46 cl::init(false), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047
48STATISTIC(NumSimple, "Number of simple if-conversions performed");
49STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
50STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
51STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
52STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
53STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
54STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
55STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
56STATISTIC(NumDupBBs, "Number of duplicated blocks");
57
58namespace {
Evan Cheng45c1edb2008-02-28 00:43:03 +000059 class VISIBILITY_HIDDEN IfConverter : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060 enum IfcvtKind {
61 ICNotClassfied, // BB data valid, but not classified.
62 ICSimpleFalse, // Same as ICSimple, but on the false path.
63 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
64 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
65 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
66 ICTriangleFalse, // Same as ICTriangle, but on the false path.
67 ICTriangle, // BB is entry of a triangle sub-CFG.
68 ICDiamond // BB is entry of a diamond sub-CFG.
69 };
70
71 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
72 /// if-conversion feasibility analysis. This includes results from
73 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
74 /// classification, and common tail block of its successors (if it's a
75 /// diamond shape), its size, whether it's predicable, and whether any
76 /// instruction can clobber the 'would-be' predicate.
77 ///
78 /// IsDone - True if BB is not to be considered for ifcvt.
79 /// IsBeingAnalyzed - True if BB is currently being analyzed.
80 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
81 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
82 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
83 /// HasFallThrough - True if BB may fallthrough to the following BB.
84 /// IsUnpredicable - True if BB is known to be unpredicable.
85 /// ClobbersPred - True if BB could modify predicates (e.g. has
86 /// cmp, call, etc.)
87 /// NonPredSize - Number of non-predicated instructions.
88 /// BB - Corresponding MachineBasicBlock.
89 /// TrueBB / FalseBB- See AnalyzeBranch().
90 /// BrCond - Conditions for end of block conditional branches.
91 /// Predicate - Predicate used in the BB.
92 struct BBInfo {
93 bool IsDone : 1;
94 bool IsBeingAnalyzed : 1;
95 bool IsAnalyzed : 1;
96 bool IsEnqueued : 1;
97 bool IsBrAnalyzable : 1;
98 bool HasFallThrough : 1;
99 bool IsUnpredicable : 1;
100 bool CannotBeCopied : 1;
101 bool ClobbersPred : 1;
102 unsigned NonPredSize;
103 MachineBasicBlock *BB;
104 MachineBasicBlock *TrueBB;
105 MachineBasicBlock *FalseBB;
Owen Andersond131b5b2008-08-14 22:49:33 +0000106 SmallVector<MachineOperand, 4> BrCond;
107 SmallVector<MachineOperand, 4> Predicate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
109 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
110 HasFallThrough(false), IsUnpredicable(false),
111 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
112 BB(0), TrueBB(0), FalseBB(0) {}
113 };
114
115 /// IfcvtToken - Record information about pending if-conversions to attemp:
116 /// BBI - Corresponding BBInfo.
117 /// Kind - Type of block. See IfcvtKind.
118 /// NeedSubsumsion - True if the to be predicated BB has already been
119 /// predicated.
120 /// NumDups - Number of instructions that would be duplicated due
121 /// to this if-conversion. (For diamonds, the number of
122 /// identical instructions at the beginnings of both
123 /// paths).
124 /// NumDups2 - For diamonds, the number of identical instructions
125 /// at the ends of both paths.
126 struct IfcvtToken {
127 BBInfo &BBI;
128 IfcvtKind Kind;
129 bool NeedSubsumsion;
130 unsigned NumDups;
131 unsigned NumDups2;
132 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
133 : BBI(b), Kind(k), NeedSubsumsion(s), NumDups(d), NumDups2(d2) {}
134 };
135
136 /// Roots - Basic blocks that do not have successors. These are the starting
137 /// points of Graph traversal.
138 std::vector<MachineBasicBlock*> Roots;
139
140 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
141 /// basic block number.
142 std::vector<BBInfo> BBAnalysis;
143
144 const TargetLowering *TLI;
145 const TargetInstrInfo *TII;
146 bool MadeChange;
147 public:
148 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +0000149 IfConverter() : MachineFunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
151 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga911dfe2008-06-04 09:15:51 +0000152 virtual const char *getPassName() const { return "If Converter"; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153
154 private:
155 bool ReverseBranchCondition(BBInfo &BBI);
156 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
157 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
158 bool FalseBranch, unsigned &Dups) const;
159 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
160 unsigned &Dups1, unsigned &Dups2) const;
161 void ScanInstructions(BBInfo &BBI);
162 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
163 std::vector<IfcvtToken*> &Tokens);
Owen Andersond131b5b2008-08-14 22:49:33 +0000164 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 bool isTriangle = false, bool RevBranch = false);
166 bool AnalyzeBlocks(MachineFunction &MF,
167 std::vector<IfcvtToken*> &Tokens);
168 void InvalidatePreds(MachineBasicBlock *BB);
169 void RemoveExtraEdges(BBInfo &BBI);
170 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
171 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
172 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
173 unsigned NumDups1, unsigned NumDups2);
174 void PredicateBlock(BBInfo &BBI,
175 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +0000176 SmallVectorImpl<MachineOperand> &Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000178 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 bool IgnoreBr = false);
180 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
181
182 bool MeetIfcvtSizeLimit(unsigned Size) const {
183 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit();
184 }
185
186 // blockAlwaysFallThrough - Block ends without a terminator.
187 bool blockAlwaysFallThrough(BBInfo &BBI) const {
188 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
189 }
190
191 // IfcvtTokenCmp - Used to sort if-conversion candidates.
192 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
193 int Incr1 = (C1->Kind == ICDiamond)
194 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
195 int Incr2 = (C2->Kind == ICDiamond)
196 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
197 if (Incr1 > Incr2)
198 return true;
199 else if (Incr1 == Incr2) {
200 // Favors subsumsion.
201 if (C1->NeedSubsumsion == false && C2->NeedSubsumsion == true)
202 return true;
203 else if (C1->NeedSubsumsion == C2->NeedSubsumsion) {
204 // Favors diamond over triangle, etc.
205 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
206 return true;
207 else if (C1->Kind == C2->Kind)
208 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
209 }
210 }
211 return false;
212 }
213 };
214
215 char IfConverter::ID = 0;
216}
217
Evan Chenga911dfe2008-06-04 09:15:51 +0000218static RegisterPass<IfConverter>
219X("if-converter", "If Converter");
220
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
222
223bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
224 TLI = MF.getTarget().getTargetLowering();
225 TII = MF.getTarget().getInstrInfo();
226 if (!TII) return false;
227
228 static int FnNum = -1;
229 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
230 << MF.getFunction()->getName() << "\'";
231
232 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
233 DOUT << " skipped\n";
234 return false;
235 }
236 DOUT << "\n";
237
238 MF.RenumberBlocks();
239 BBAnalysis.resize(MF.getNumBlockIDs());
240
241 // Look for root nodes, i.e. blocks without successors.
242 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000243 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 Roots.push_back(I);
245
246 std::vector<IfcvtToken*> Tokens;
247 MadeChange = false;
248 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
249 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
250 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
251 // Do an intial analysis for each basic block and finding all the potential
252 // candidates to perform if-convesion.
253 bool Change = AnalyzeBlocks(MF, Tokens);
254 while (!Tokens.empty()) {
255 IfcvtToken *Token = Tokens.back();
256 Tokens.pop_back();
257 BBInfo &BBI = Token->BBI;
258 IfcvtKind Kind = Token->Kind;
Nuno Lopes06cea782008-11-04 13:02:59 +0000259 unsigned NumDups = Token->NumDups;
Duncan Sands5c2a51a2008-11-04 18:05:30 +0000260 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes06cea782008-11-04 13:02:59 +0000261
262 delete Token;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263
264 // If the block has been evicted out of the queue or it has already been
265 // marked dead (due to it being predicated), then skip it.
266 if (BBI.IsDone)
267 BBI.IsEnqueued = false;
268 if (!BBI.IsEnqueued)
269 continue;
270
271 BBI.IsEnqueued = false;
272
273 bool RetVal = false;
274 switch (Kind) {
275 default: assert(false && "Unexpected!");
276 break;
277 case ICSimple:
278 case ICSimpleFalse: {
279 bool isFalse = Kind == ICSimpleFalse;
280 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
281 DOUT << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"")
282 << "): BB#" << BBI.BB->getNumber() << " ("
283 << ((Kind == ICSimpleFalse)
284 ? BBI.FalseBB->getNumber()
285 : BBI.TrueBB->getNumber()) << ") ";
286 RetVal = IfConvertSimple(BBI, Kind);
287 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000288 if (RetVal) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 if (isFalse) NumSimpleFalse++;
290 else NumSimple++;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000291 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 break;
293 }
294 case ICTriangle:
295 case ICTriangleRev:
296 case ICTriangleFalse:
297 case ICTriangleFRev: {
298 bool isFalse = Kind == ICTriangleFalse;
299 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
300 if (DisableTriangle && !isFalse && !isRev) break;
301 if (DisableTriangleR && !isFalse && isRev) break;
302 if (DisableTriangleF && isFalse && !isRev) break;
303 if (DisableTriangleFR && isFalse && isRev) break;
304 DOUT << "Ifcvt (Triangle";
305 if (isFalse)
306 DOUT << " false";
307 if (isRev)
308 DOUT << " rev";
309 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
310 << BBI.TrueBB->getNumber() << ",F:"
311 << BBI.FalseBB->getNumber() << ") ";
312 RetVal = IfConvertTriangle(BBI, Kind);
313 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
314 if (RetVal) {
315 if (isFalse) {
316 if (isRev) NumTriangleFRev++;
317 else NumTriangleFalse++;
318 } else {
319 if (isRev) NumTriangleRev++;
320 else NumTriangle++;
321 }
322 }
323 break;
324 }
325 case ICDiamond: {
326 if (DisableDiamond) break;
327 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
328 << BBI.TrueBB->getNumber() << ",F:"
329 << BBI.FalseBB->getNumber() << ") ";
Nuno Lopes06cea782008-11-04 13:02:59 +0000330 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
332 if (RetVal) NumDiamonds++;
333 break;
334 }
335 }
336
337 Change |= RetVal;
338
339 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
340 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
341 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
342 break;
343 }
344
345 if (!Change)
346 break;
347 MadeChange |= Change;
348 }
349
350 // Delete tokens in case of early exit.
351 while (!Tokens.empty()) {
352 IfcvtToken *Token = Tokens.back();
353 Tokens.pop_back();
354 delete Token;
355 }
356
357 Tokens.clear();
358 Roots.clear();
359 BBAnalysis.clear();
360
361 return MadeChange;
362}
363
364/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
365/// its 'true' successor.
366static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
367 MachineBasicBlock *TrueBB) {
368 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
369 E = BB->succ_end(); SI != E; ++SI) {
370 MachineBasicBlock *SuccBB = *SI;
371 if (SuccBB != TrueBB)
372 return SuccBB;
373 }
374 return NULL;
375}
376
377/// ReverseBranchCondition - Reverse the condition of the end of the block
378/// branchs. Swap block's 'true' and 'false' successors.
379bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
380 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
381 TII->RemoveBranch(*BBI.BB);
382 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
383 std::swap(BBI.TrueBB, BBI.FalseBB);
384 return true;
385 }
386 return false;
387}
388
389/// getNextBlock - Returns the next block in the function blocks ordering. If
390/// it is the end, returns NULL.
391static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
392 MachineFunction::iterator I = BB;
393 MachineFunction::iterator E = BB->getParent()->end();
394 if (++I == E)
395 return NULL;
396 return I;
397}
398
399/// ValidSimple - Returns true if the 'true' block (along with its
400/// predecessor) forms a valid simple shape for ifcvt. It also returns the
401/// number of instructions that the ifcvt would need to duplicate if performed
402/// in Dups.
403bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
404 Dups = 0;
405 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
406 return false;
407
408 if (TrueBBI.IsBrAnalyzable)
409 return false;
410
411 if (TrueBBI.BB->pred_size() > 1) {
412 if (TrueBBI.CannotBeCopied ||
413 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
414 return false;
415 Dups = TrueBBI.NonPredSize;
416 }
417
418 return true;
419}
420
421/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
422/// with their common predecessor) forms a valid triangle shape for ifcvt.
423/// If 'FalseBranch' is true, it checks if 'true' block's false branch
424/// branches to the false branch rather than the other way around. It also
425/// returns the number of instructions that the ifcvt would need to duplicate
426/// if performed in 'Dups'.
427bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
428 bool FalseBranch, unsigned &Dups) const {
429 Dups = 0;
430 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
431 return false;
432
433 if (TrueBBI.BB->pred_size() > 1) {
434 if (TrueBBI.CannotBeCopied)
435 return false;
436
437 unsigned Size = TrueBBI.NonPredSize;
438 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000439 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 // End with an unconditional branch. It will be removed.
441 --Size;
442 else {
443 MachineBasicBlock *FExit = FalseBranch
444 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
445 if (FExit)
446 // Require a conditional branch
447 ++Size;
448 }
449 }
450 if (Size > TLI->getIfCvtDupBlockSizeLimit())
451 return false;
452 Dups = Size;
453 }
454
455 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
456 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
457 MachineFunction::iterator I = TrueBBI.BB;
458 if (++I == TrueBBI.BB->getParent()->end())
459 return false;
460 TExit = I;
461 }
462 return TExit && TExit == FalseBBI.BB;
463}
464
465static
466MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
467 const TargetInstrInfo *TII) {
468 MachineBasicBlock::iterator I = BB->end();
469 while (I != BB->begin()) {
470 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000471 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 break;
473 }
474 return I;
475}
476
477/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
478/// with their common predecessor) forms a valid diamond shape for ifcvt.
479bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
480 unsigned &Dups1, unsigned &Dups2) const {
481 Dups1 = Dups2 = 0;
482 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
483 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
484 return false;
485
486 MachineBasicBlock *TT = TrueBBI.TrueBB;
487 MachineBasicBlock *FT = FalseBBI.TrueBB;
488
489 if (!TT && blockAlwaysFallThrough(TrueBBI))
490 TT = getNextBlock(TrueBBI.BB);
491 if (!FT && blockAlwaysFallThrough(FalseBBI))
492 FT = getNextBlock(FalseBBI.BB);
493 if (TT != FT)
494 return false;
495 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
496 return false;
497 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
498 return false;
499
500 // FIXME: Allow true block to have an early exit?
501 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
502 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
503 return false;
504
505 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
506 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
507 while (TI != TrueBBI.BB->end() && FI != FalseBBI.BB->end()) {
508 if (!TI->isIdenticalTo(FI))
509 break;
510 ++Dups1;
511 ++TI;
512 ++FI;
513 }
514
515 TI = firstNonBranchInst(TrueBBI.BB, TII);
516 FI = firstNonBranchInst(FalseBBI.BB, TII);
517 while (TI != TrueBBI.BB->begin() && FI != FalseBBI.BB->begin()) {
518 if (!TI->isIdenticalTo(FI))
519 break;
520 ++Dups2;
521 --TI;
522 --FI;
523 }
524
525 return true;
526}
527
528/// ScanInstructions - Scan all the instructions in the block to determine if
529/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000530/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531/// instruction which can clobber a predicate (e.g. condition code register).
532/// If so, the block is not predicable unless it's the last instruction.
533void IfConverter::ScanInstructions(BBInfo &BBI) {
534 if (BBI.IsDone)
535 return;
536
537 bool AlreadyPredicated = BBI.Predicate.size() > 0;
538 // First analyze the end of BB branches.
539 BBI.TrueBB = BBI.FalseBB = NULL;
540 BBI.BrCond.clear();
541 BBI.IsBrAnalyzable =
542 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
543 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
544
545 if (BBI.BrCond.size()) {
546 // No false branch. This BB must end with a conditional branch and a
547 // fallthrough.
548 if (!BBI.FalseBB)
549 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
550 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
551 }
552
553 // Then scan all the instructions.
554 BBI.NonPredSize = 0;
555 BBI.ClobbersPred = false;
556 bool SeenCondBr = false;
557 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
558 I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +0000559 const TargetInstrDesc &TID = I->getDesc();
560 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 BBI.CannotBeCopied = true;
562
563 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000564 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565
566 if (!isCondBr) {
567 if (!isPredicated)
568 BBI.NonPredSize++;
569 else if (!AlreadyPredicated) {
570 // FIXME: This instruction is already predicated before the
571 // if-conversion pass. It's probably something like a conditional move.
572 // Mark this block unpredicable for now.
573 BBI.IsUnpredicable = true;
574 return;
575 }
576
577 }
578
579 if (BBI.ClobbersPred && !isPredicated) {
580 // Predicate modification instruction should end the block (except for
581 // already predicated instructions and end of block branches).
582 if (isCondBr) {
583 SeenCondBr = true;
584
585 // Conditional branches is not predicable. But it may be eliminated.
586 continue;
587 }
588
589 // Predicate may have been modified, the subsequent (currently)
590 // unpredicated instructions cannot be correctly predicated.
591 BBI.IsUnpredicable = true;
592 return;
593 }
594
595 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
596 // still potentially predicable.
597 std::vector<MachineOperand> PredDefs;
598 if (TII->DefinesPredicate(I, PredDefs))
599 BBI.ClobbersPred = true;
600
Chris Lattner5b930372008-01-07 07:27:27 +0000601 if (!TID.isPredicable()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 BBI.IsUnpredicable = true;
603 return;
604 }
605 }
606}
607
608/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
609/// predicated by the specified predicate.
610bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000611 SmallVectorImpl<MachineOperand> &Pred,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612 bool isTriangle, bool RevBranch) {
613 // If the block is dead or unpredicable, then it cannot be predicated.
614 if (BBI.IsDone || BBI.IsUnpredicable)
615 return false;
616
617 // If it is already predicated, check if its predicate subsumes the new
618 // predicate.
619 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
620 return false;
621
622 if (BBI.BrCond.size()) {
623 if (!isTriangle)
624 return false;
625
626 // Test predicate subsumsion.
Owen Andersond131b5b2008-08-14 22:49:33 +0000627 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
628 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 if (RevBranch) {
630 if (TII->ReverseBranchCondition(Cond))
631 return false;
632 }
633 if (TII->ReverseBranchCondition(RevPred) ||
634 !TII->SubsumesPredicate(Cond, RevPred))
635 return false;
636 }
637
638 return true;
639}
640
641/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
642/// the specified block. Record its successors and whether it looks like an
643/// if-conversion candidate.
644IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
645 std::vector<IfcvtToken*> &Tokens) {
646 BBInfo &BBI = BBAnalysis[BB->getNumber()];
647
648 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
649 return BBI;
650
651 BBI.BB = BB;
652 BBI.IsBeingAnalyzed = true;
653
654 ScanInstructions(BBI);
655
656 // Unanalyable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000657 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 BBI.IsBeingAnalyzed = false;
659 BBI.IsAnalyzed = true;
660 return BBI;
661 }
662
663 // Do not ifcvt if either path is a back edge to the entry block.
664 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
665 BBI.IsBeingAnalyzed = false;
666 BBI.IsAnalyzed = true;
667 return BBI;
668 }
669
670 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
671 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
672
673 if (TrueBBI.IsDone && FalseBBI.IsDone) {
674 BBI.IsBeingAnalyzed = false;
675 BBI.IsAnalyzed = true;
676 return BBI;
677 }
678
Owen Andersond131b5b2008-08-14 22:49:33 +0000679 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
681
682 unsigned Dups = 0;
683 unsigned Dups2 = 0;
684 bool TNeedSub = TrueBBI.Predicate.size() > 0;
685 bool FNeedSub = FalseBBI.Predicate.size() > 0;
686 bool Enqueued = false;
687 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
688 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
689 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
690 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
691 FeasibilityAnalysis(FalseBBI, RevCond)) {
692 // Diamond:
693 // EBB
694 // / \_
695 // | |
696 // TBB FBB
697 // \ /
698 // TailBB
699 // Note TailBB can be empty.
700 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
701 Dups2));
702 Enqueued = true;
703 }
704
705 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
706 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
707 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
708 // Triangle:
709 // EBB
710 // | \_
711 // | |
712 // | TBB
713 // | /
714 // FBB
715 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
716 Enqueued = true;
717 }
718
719 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
720 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
721 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
722 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
723 Enqueued = true;
724 }
725
726 if (ValidSimple(TrueBBI, Dups) &&
727 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
728 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
729 // Simple (split, no rejoin):
730 // EBB
731 // | \_
732 // | |
733 // | TBB---> exit
734 // |
735 // FBB
736 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
737 Enqueued = true;
738 }
739
740 if (CanRevCond) {
741 // Try the other path...
742 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
743 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
744 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
745 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
746 Enqueued = true;
747 }
748
749 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
750 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
751 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
752 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
753 Enqueued = true;
754 }
755
756 if (ValidSimple(FalseBBI, Dups) &&
757 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
758 FeasibilityAnalysis(FalseBBI, RevCond)) {
759 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
760 Enqueued = true;
761 }
762 }
763
764 BBI.IsEnqueued = Enqueued;
765 BBI.IsBeingAnalyzed = false;
766 BBI.IsAnalyzed = true;
767 return BBI;
768}
769
770/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
771/// candidates. It returns true if any CFG restructuring is done to expose more
772/// if-conversion opportunities.
773bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
774 std::vector<IfcvtToken*> &Tokens) {
775 bool Change = false;
776 std::set<MachineBasicBlock*> Visited;
777 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
778 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
779 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
780 MachineBasicBlock *BB = *I;
781 AnalyzeBlock(BB, Tokens);
782 }
783 }
784
785 // Sort to favor more complex ifcvt scheme.
786 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
787
788 return Change;
789}
790
791/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
792/// that all the intervening blocks are empty (given BB can fall through to its
793/// next block).
794static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
795 MachineFunction::iterator I = BB;
796 MachineFunction::iterator TI = ToBB;
797 MachineFunction::iterator E = BB->getParent()->end();
798 while (++I != TI)
799 if (I == E || !I->empty())
800 return false;
801 return true;
802}
803
804/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
805/// to determine if it can be if-converted. If predecessor is already enqueued,
806/// dequeue it!
807void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
808 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
809 E = BB->pred_end(); PI != E; ++PI) {
810 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
811 if (PBBI.IsDone || PBBI.BB == BB)
812 continue;
813 PBBI.IsAnalyzed = false;
814 PBBI.IsEnqueued = false;
815 }
816}
817
818/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
819///
820static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
821 const TargetInstrInfo *TII) {
Dan Gohmane458ea82008-08-22 16:07:55 +0000822 SmallVector<MachineOperand, 0> NoCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
824}
825
826/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
827/// successors.
828void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
829 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Andersond131b5b2008-08-14 22:49:33 +0000830 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
832 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
833}
834
835/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
836///
837bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
838 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
839 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
840 BBInfo *CvtBBI = &TrueBBI;
841 BBInfo *NextBBI = &FalseBBI;
842
Owen Andersond131b5b2008-08-14 22:49:33 +0000843 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 if (Kind == ICSimpleFalse)
845 std::swap(CvtBBI, NextBBI);
846
847 if (CvtBBI->IsDone ||
848 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
849 // Something has changed. It's no longer safe to predicate this block.
850 BBI.IsAnalyzed = false;
851 CvtBBI->IsAnalyzed = false;
852 return false;
853 }
854
855 if (Kind == ICSimpleFalse)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000856 if (TII->ReverseBranchCondition(Cond))
857 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858
859 if (CvtBBI->BB->pred_size() > 1) {
860 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
861 // Copy instructions in the true block, predicate them add them to
862 // the entry block.
863 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
864 } else {
865 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
866
867 // Merge converted block into entry block.
868 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
869 MergeBlocks(BBI, *CvtBBI);
870 }
871
872 bool IterIfcvt = true;
873 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
874 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
875 BBI.HasFallThrough = false;
876 // Now ifcvt'd block will look like this:
877 // BB:
878 // ...
879 // t, f = cmp
880 // if t op
881 // b BBf
882 //
883 // We cannot further ifcvt this block because the unconditional branch
884 // will have to be predicated on the new condition, that will not be
885 // available if cmp executes.
886 IterIfcvt = false;
887 }
888
889 RemoveExtraEdges(BBI);
890
891 // Update block info. BB can be iteratively if-converted.
892 if (!IterIfcvt)
893 BBI.IsDone = true;
894 InvalidatePreds(BBI.BB);
895 CvtBBI->IsDone = true;
896
897 // FIXME: Must maintain LiveIns.
898 return true;
899}
900
901/// IfConvertTriangle - If convert a triangle sub-CFG.
902///
903bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
904 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
905 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
906 BBInfo *CvtBBI = &TrueBBI;
907 BBInfo *NextBBI = &FalseBBI;
908
Owen Andersond131b5b2008-08-14 22:49:33 +0000909 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
911 std::swap(CvtBBI, NextBBI);
912
913 if (CvtBBI->IsDone ||
914 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
915 // Something has changed. It's no longer safe to predicate this block.
916 BBI.IsAnalyzed = false;
917 CvtBBI->IsAnalyzed = false;
918 return false;
919 }
920
921 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000922 if (TII->ReverseBranchCondition(Cond))
923 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924
925 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000926 if (ReverseBranchCondition(*CvtBBI)) {
927 // BB has been changed, modify its predecessors (except for this
928 // one) so they don't get ifcvt'ed based on bad intel.
929 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
930 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
931 MachineBasicBlock *PBB = *PI;
932 if (PBB == BBI.BB)
933 continue;
934 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
935 if (PBBI.IsEnqueued) {
936 PBBI.IsAnalyzed = false;
937 PBBI.IsEnqueued = false;
938 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 }
940 }
941 }
942
943 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
944 bool DupBB = CvtBBI->BB->pred_size() > 1;
945 if (DupBB) {
946 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
947 // Copy instructions in the true block, predicate them add them to
948 // the entry block.
949 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
950 } else {
951 // Predicate the 'true' block after removing its branch.
952 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
953 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
954 }
955
956 if (!DupBB) {
957 // Now merge the entry of the triangle with the true block.
958 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
959 MergeBlocks(BBI, *CvtBBI);
960 }
961
962 // If 'true' block has a 'false' successor, add an exit branch to it.
963 if (HasEarlyExit) {
Owen Andersond131b5b2008-08-14 22:49:33 +0000964 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
965 CvtBBI->BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966 if (TII->ReverseBranchCondition(RevCond))
967 assert(false && "Unable to reverse branch condition!");
968 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
969 BBI.BB->addSuccessor(CvtBBI->FalseBB);
970 }
971
972 // Merge in the 'false' block if the 'false' block has no other
973 // predecessors. Otherwise, add a unconditional branch from to 'false'.
974 bool FalseBBDead = false;
975 bool IterIfcvt = true;
976 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
977 if (!isFallThrough) {
978 // Only merge them if the true block does not fallthrough to the false
979 // block. By not merging them, we make it possible to iteratively
980 // ifcvt the blocks.
981 if (!HasEarlyExit &&
982 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
983 MergeBlocks(BBI, *NextBBI);
984 FalseBBDead = true;
985 } else {
986 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
987 BBI.HasFallThrough = false;
988 }
989 // Mixed predicated and unpredicated code. This cannot be iteratively
990 // predicated.
991 IterIfcvt = false;
992 }
993
994 RemoveExtraEdges(BBI);
995
996 // Update block info. BB can be iteratively if-converted.
997 if (!IterIfcvt)
998 BBI.IsDone = true;
999 InvalidatePreds(BBI.BB);
1000 CvtBBI->IsDone = true;
1001 if (FalseBBDead)
1002 NextBBI->IsDone = true;
1003
1004 // FIXME: Must maintain LiveIns.
1005 return true;
1006}
1007
1008/// IfConvertDiamond - If convert a diamond sub-CFG.
1009///
1010bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1011 unsigned NumDups1, unsigned NumDups2) {
1012 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1013 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1014 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1015 // True block must fall through or ended with unanalyzable terminator.
1016 if (!TailBB) {
1017 if (blockAlwaysFallThrough(TrueBBI))
1018 TailBB = FalseBBI.TrueBB;
1019 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1020 }
1021
1022 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1023 TrueBBI.BB->pred_size() > 1 ||
1024 FalseBBI.BB->pred_size() > 1) {
1025 // Something has changed. It's no longer safe to predicate these blocks.
1026 BBI.IsAnalyzed = false;
1027 TrueBBI.IsAnalyzed = false;
1028 FalseBBI.IsAnalyzed = false;
1029 return false;
1030 }
1031
1032 // Merge the 'true' and 'false' blocks by copying the instructions
1033 // from the 'false' block to the 'true' block. That is, unless the true
1034 // block would clobber the predicate, in that case, do the opposite.
1035 BBInfo *BBI1 = &TrueBBI;
1036 BBInfo *BBI2 = &FalseBBI;
Owen Andersond131b5b2008-08-14 22:49:33 +00001037 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001038 if (TII->ReverseBranchCondition(RevCond))
1039 assert(false && "Unable to reverse branch condition!");
Owen Andersond131b5b2008-08-14 22:49:33 +00001040 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1041 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042
1043 // Figure out the more profitable ordering.
1044 bool DoSwap = false;
1045 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1046 DoSwap = true;
1047 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1048 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1049 DoSwap = true;
1050 }
1051 if (DoSwap) {
1052 std::swap(BBI1, BBI2);
1053 std::swap(Cond1, Cond2);
1054 }
1055
1056 // Remove the conditional branch from entry to the blocks.
1057 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1058
1059 // Remove the duplicated instructions at the beginnings of both paths.
1060 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1061 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1062 BBI1->NonPredSize -= NumDups1;
1063 BBI2->NonPredSize -= NumDups1;
1064 while (NumDups1 != 0) {
1065 ++DI1;
1066 ++DI2;
1067 --NumDups1;
1068 }
1069 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1070 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1071
1072 // Predicate the 'true' block after removing its branch.
1073 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1074 DI1 = BBI1->BB->end();
1075 for (unsigned i = 0; i != NumDups2; ++i)
1076 --DI1;
1077 BBI1->BB->erase(DI1, BBI1->BB->end());
1078 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1);
1079
1080 // Predicate the 'false' block.
1081 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1082 DI2 = BBI2->BB->end();
1083 while (NumDups2 != 0) {
1084 --DI2;
1085 --NumDups2;
1086 }
1087 PredicateBlock(*BBI2, DI2, *Cond2);
1088
1089 // Merge the true block into the entry of the diamond.
1090 MergeBlocks(BBI, *BBI1);
1091 MergeBlocks(BBI, *BBI2);
1092
1093 // If the if-converted block fallthrough or unconditionally branch into the
1094 // tail block, and the tail block does not have other predecessors, then
1095 // fold the tail block in as well. Otherwise, unless it falls through to the
1096 // tail, add a unconditional branch to it.
1097 if (TailBB) {
1098 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1099 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1100 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1101 MergeBlocks(BBI, TailBBI);
1102 TailBBI.IsDone = true;
1103 } else {
1104 InsertUncondBranch(BBI.BB, TailBB, TII);
1105 BBI.HasFallThrough = false;
1106 }
1107 }
1108
1109 RemoveExtraEdges(BBI);
1110
1111 // Update block info.
1112 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1113 InvalidatePreds(BBI.BB);
1114
1115 // FIXME: Must maintain LiveIns.
1116 return true;
1117}
1118
1119/// PredicateBlock - Predicate instructions from the start of the block to the
1120/// specified end with the specified condition.
1121void IfConverter::PredicateBlock(BBInfo &BBI,
1122 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +00001123 SmallVectorImpl<MachineOperand> &Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1125 if (TII->isPredicated(I))
1126 continue;
1127 if (!TII->PredicateInstruction(I, Cond)) {
1128 cerr << "Unable to predicate " << *I << "!\n";
1129 abort();
1130 }
1131 }
1132
1133 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1134
1135 BBI.IsAnalyzed = false;
1136 BBI.NonPredSize = 0;
1137
1138 NumIfConvBBs++;
1139}
1140
1141/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1142/// the destination block. Skip end of block branches if IgnoreBr is true.
1143void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +00001144 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 bool IgnoreBr) {
Dan Gohman221a4372008-07-07 23:14:23 +00001146 MachineFunction &MF = *ToBBI.BB->getParent();
1147
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1149 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001150 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151 bool isPredicated = TII->isPredicated(I);
1152 // Do not copy the end of the block branches.
Chris Lattner5b930372008-01-07 07:27:27 +00001153 if (IgnoreBr && !isPredicated && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 break;
1155
Dan Gohman221a4372008-07-07 23:14:23 +00001156 MachineInstr *MI = MF.CloneMachineInstr(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001157 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1158 ToBBI.NonPredSize++;
1159
1160 if (!isPredicated)
1161 if (!TII->PredicateInstruction(MI, Cond)) {
1162 cerr << "Unable to predicate " << *MI << "!\n";
1163 abort();
1164 }
1165 }
1166
1167 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1168 FromBBI.BB->succ_end());
1169 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1170 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1171
1172 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1173 MachineBasicBlock *Succ = Succs[i];
1174 // Fallthrough edge can't be transferred.
1175 if (Succ == FallThrough)
1176 continue;
1177 if (!ToBBI.BB->isSuccessor(Succ))
1178 ToBBI.BB->addSuccessor(Succ);
1179 }
1180
1181 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1182 std::back_inserter(ToBBI.Predicate));
1183 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1184
1185 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1186 ToBBI.IsAnalyzed = false;
1187
1188 NumDupBBs++;
1189}
1190
1191/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1192///
1193void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1194 ToBBI.BB->splice(ToBBI.BB->end(),
1195 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1196
1197 // Redirect all branches to FromBB to ToBB.
1198 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1199 FromBBI.BB->pred_end());
1200 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1201 MachineBasicBlock *Pred = Preds[i];
1202 if (Pred == ToBBI.BB)
1203 continue;
1204 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1205 }
1206
1207 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1208 FromBBI.BB->succ_end());
1209 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1210 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1211
1212 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1213 MachineBasicBlock *Succ = Succs[i];
1214 // Fallthrough edge can't be transferred.
1215 if (Succ == FallThrough)
1216 continue;
1217 FromBBI.BB->removeSuccessor(Succ);
1218 if (!ToBBI.BB->isSuccessor(Succ))
1219 ToBBI.BB->addSuccessor(Succ);
1220 }
1221
1222 // Now FromBBI always fall through to the next block!
1223 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1224 FromBBI.BB->addSuccessor(NBB);
1225
1226 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1227 std::back_inserter(ToBBI.Predicate));
1228 FromBBI.Predicate.clear();
1229
1230 ToBBI.NonPredSize += FromBBI.NonPredSize;
1231 FromBBI.NonPredSize = 0;
1232
1233 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1234 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1235 ToBBI.IsAnalyzed = false;
1236 FromBBI.IsAnalyzed = false;
1237}