blob: a77ccb766ff60737b03d03706d8ce50cebfddd0b [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;
106 std::vector<MachineOperand> BrCond;
107 std::vector<MachineOperand> Predicate;
108 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;
149 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
150
151 virtual bool runOnMachineFunction(MachineFunction &MF);
152 virtual const char *getPassName() const { return "If converter"; }
153
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);
164 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
165 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,
176 std::vector<MachineOperand> &Cond);
177 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
178 std::vector<MachineOperand> &Cond,
179 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
218FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
219
220bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
221 TLI = MF.getTarget().getTargetLowering();
222 TII = MF.getTarget().getInstrInfo();
223 if (!TII) return false;
224
225 static int FnNum = -1;
226 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
227 << MF.getFunction()->getName() << "\'";
228
229 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
230 DOUT << " skipped\n";
231 return false;
232 }
233 DOUT << "\n";
234
235 MF.RenumberBlocks();
236 BBAnalysis.resize(MF.getNumBlockIDs());
237
238 // Look for root nodes, i.e. blocks without successors.
239 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000240 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 Roots.push_back(I);
242
243 std::vector<IfcvtToken*> Tokens;
244 MadeChange = false;
245 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
246 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
247 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
248 // Do an intial analysis for each basic block and finding all the potential
249 // candidates to perform if-convesion.
250 bool Change = AnalyzeBlocks(MF, Tokens);
251 while (!Tokens.empty()) {
252 IfcvtToken *Token = Tokens.back();
253 Tokens.pop_back();
254 BBInfo &BBI = Token->BBI;
255 IfcvtKind Kind = Token->Kind;
256
257 // If the block has been evicted out of the queue or it has already been
258 // marked dead (due to it being predicated), then skip it.
259 if (BBI.IsDone)
260 BBI.IsEnqueued = false;
261 if (!BBI.IsEnqueued)
262 continue;
263
264 BBI.IsEnqueued = false;
265
266 bool RetVal = false;
267 switch (Kind) {
268 default: assert(false && "Unexpected!");
269 break;
270 case ICSimple:
271 case ICSimpleFalse: {
272 bool isFalse = Kind == ICSimpleFalse;
273 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
274 DOUT << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"")
275 << "): BB#" << BBI.BB->getNumber() << " ("
276 << ((Kind == ICSimpleFalse)
277 ? BBI.FalseBB->getNumber()
278 : BBI.TrueBB->getNumber()) << ") ";
279 RetVal = IfConvertSimple(BBI, Kind);
280 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000281 if (RetVal) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 if (isFalse) NumSimpleFalse++;
283 else NumSimple++;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000284 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 break;
286 }
287 case ICTriangle:
288 case ICTriangleRev:
289 case ICTriangleFalse:
290 case ICTriangleFRev: {
291 bool isFalse = Kind == ICTriangleFalse;
292 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
293 if (DisableTriangle && !isFalse && !isRev) break;
294 if (DisableTriangleR && !isFalse && isRev) break;
295 if (DisableTriangleF && isFalse && !isRev) break;
296 if (DisableTriangleFR && isFalse && isRev) break;
297 DOUT << "Ifcvt (Triangle";
298 if (isFalse)
299 DOUT << " false";
300 if (isRev)
301 DOUT << " rev";
302 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
303 << BBI.TrueBB->getNumber() << ",F:"
304 << BBI.FalseBB->getNumber() << ") ";
305 RetVal = IfConvertTriangle(BBI, Kind);
306 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
307 if (RetVal) {
308 if (isFalse) {
309 if (isRev) NumTriangleFRev++;
310 else NumTriangleFalse++;
311 } else {
312 if (isRev) NumTriangleRev++;
313 else NumTriangle++;
314 }
315 }
316 break;
317 }
318 case ICDiamond: {
319 if (DisableDiamond) break;
320 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
321 << BBI.TrueBB->getNumber() << ",F:"
322 << BBI.FalseBB->getNumber() << ") ";
323 RetVal = IfConvertDiamond(BBI, Kind, Token->NumDups, Token->NumDups2);
324 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
325 if (RetVal) NumDiamonds++;
326 break;
327 }
328 }
329
330 Change |= RetVal;
331
332 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
333 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
334 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
335 break;
336 }
337
338 if (!Change)
339 break;
340 MadeChange |= Change;
341 }
342
343 // Delete tokens in case of early exit.
344 while (!Tokens.empty()) {
345 IfcvtToken *Token = Tokens.back();
346 Tokens.pop_back();
347 delete Token;
348 }
349
350 Tokens.clear();
351 Roots.clear();
352 BBAnalysis.clear();
353
354 return MadeChange;
355}
356
357/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
358/// its 'true' successor.
359static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
360 MachineBasicBlock *TrueBB) {
361 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
362 E = BB->succ_end(); SI != E; ++SI) {
363 MachineBasicBlock *SuccBB = *SI;
364 if (SuccBB != TrueBB)
365 return SuccBB;
366 }
367 return NULL;
368}
369
370/// ReverseBranchCondition - Reverse the condition of the end of the block
371/// branchs. Swap block's 'true' and 'false' successors.
372bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
373 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
374 TII->RemoveBranch(*BBI.BB);
375 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
376 std::swap(BBI.TrueBB, BBI.FalseBB);
377 return true;
378 }
379 return false;
380}
381
382/// getNextBlock - Returns the next block in the function blocks ordering. If
383/// it is the end, returns NULL.
384static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
385 MachineFunction::iterator I = BB;
386 MachineFunction::iterator E = BB->getParent()->end();
387 if (++I == E)
388 return NULL;
389 return I;
390}
391
392/// ValidSimple - Returns true if the 'true' block (along with its
393/// predecessor) forms a valid simple shape for ifcvt. It also returns the
394/// number of instructions that the ifcvt would need to duplicate if performed
395/// in Dups.
396bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
397 Dups = 0;
398 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
399 return false;
400
401 if (TrueBBI.IsBrAnalyzable)
402 return false;
403
404 if (TrueBBI.BB->pred_size() > 1) {
405 if (TrueBBI.CannotBeCopied ||
406 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
407 return false;
408 Dups = TrueBBI.NonPredSize;
409 }
410
411 return true;
412}
413
414/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
415/// with their common predecessor) forms a valid triangle shape for ifcvt.
416/// If 'FalseBranch' is true, it checks if 'true' block's false branch
417/// branches to the false branch rather than the other way around. It also
418/// returns the number of instructions that the ifcvt would need to duplicate
419/// if performed in 'Dups'.
420bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
421 bool FalseBranch, unsigned &Dups) const {
422 Dups = 0;
423 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
424 return false;
425
426 if (TrueBBI.BB->pred_size() > 1) {
427 if (TrueBBI.CannotBeCopied)
428 return false;
429
430 unsigned Size = TrueBBI.NonPredSize;
431 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000432 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 // End with an unconditional branch. It will be removed.
434 --Size;
435 else {
436 MachineBasicBlock *FExit = FalseBranch
437 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
438 if (FExit)
439 // Require a conditional branch
440 ++Size;
441 }
442 }
443 if (Size > TLI->getIfCvtDupBlockSizeLimit())
444 return false;
445 Dups = Size;
446 }
447
448 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
449 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
450 MachineFunction::iterator I = TrueBBI.BB;
451 if (++I == TrueBBI.BB->getParent()->end())
452 return false;
453 TExit = I;
454 }
455 return TExit && TExit == FalseBBI.BB;
456}
457
458static
459MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
460 const TargetInstrInfo *TII) {
461 MachineBasicBlock::iterator I = BB->end();
462 while (I != BB->begin()) {
463 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000464 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465 break;
466 }
467 return I;
468}
469
470/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
471/// with their common predecessor) forms a valid diamond shape for ifcvt.
472bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
473 unsigned &Dups1, unsigned &Dups2) const {
474 Dups1 = Dups2 = 0;
475 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
476 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
477 return false;
478
479 MachineBasicBlock *TT = TrueBBI.TrueBB;
480 MachineBasicBlock *FT = FalseBBI.TrueBB;
481
482 if (!TT && blockAlwaysFallThrough(TrueBBI))
483 TT = getNextBlock(TrueBBI.BB);
484 if (!FT && blockAlwaysFallThrough(FalseBBI))
485 FT = getNextBlock(FalseBBI.BB);
486 if (TT != FT)
487 return false;
488 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
489 return false;
490 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
491 return false;
492
493 // FIXME: Allow true block to have an early exit?
494 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
495 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
496 return false;
497
498 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
499 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
500 while (TI != TrueBBI.BB->end() && FI != FalseBBI.BB->end()) {
501 if (!TI->isIdenticalTo(FI))
502 break;
503 ++Dups1;
504 ++TI;
505 ++FI;
506 }
507
508 TI = firstNonBranchInst(TrueBBI.BB, TII);
509 FI = firstNonBranchInst(FalseBBI.BB, TII);
510 while (TI != TrueBBI.BB->begin() && FI != FalseBBI.BB->begin()) {
511 if (!TI->isIdenticalTo(FI))
512 break;
513 ++Dups2;
514 --TI;
515 --FI;
516 }
517
518 return true;
519}
520
521/// ScanInstructions - Scan all the instructions in the block to determine if
522/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000523/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524/// instruction which can clobber a predicate (e.g. condition code register).
525/// If so, the block is not predicable unless it's the last instruction.
526void IfConverter::ScanInstructions(BBInfo &BBI) {
527 if (BBI.IsDone)
528 return;
529
530 bool AlreadyPredicated = BBI.Predicate.size() > 0;
531 // First analyze the end of BB branches.
532 BBI.TrueBB = BBI.FalseBB = NULL;
533 BBI.BrCond.clear();
534 BBI.IsBrAnalyzable =
535 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
536 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
537
538 if (BBI.BrCond.size()) {
539 // No false branch. This BB must end with a conditional branch and a
540 // fallthrough.
541 if (!BBI.FalseBB)
542 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
543 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
544 }
545
546 // Then scan all the instructions.
547 BBI.NonPredSize = 0;
548 BBI.ClobbersPred = false;
549 bool SeenCondBr = false;
550 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
551 I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +0000552 const TargetInstrDesc &TID = I->getDesc();
553 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 BBI.CannotBeCopied = true;
555
556 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000557 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558
559 if (!isCondBr) {
560 if (!isPredicated)
561 BBI.NonPredSize++;
562 else if (!AlreadyPredicated) {
563 // FIXME: This instruction is already predicated before the
564 // if-conversion pass. It's probably something like a conditional move.
565 // Mark this block unpredicable for now.
566 BBI.IsUnpredicable = true;
567 return;
568 }
569
570 }
571
572 if (BBI.ClobbersPred && !isPredicated) {
573 // Predicate modification instruction should end the block (except for
574 // already predicated instructions and end of block branches).
575 if (isCondBr) {
576 SeenCondBr = true;
577
578 // Conditional branches is not predicable. But it may be eliminated.
579 continue;
580 }
581
582 // Predicate may have been modified, the subsequent (currently)
583 // unpredicated instructions cannot be correctly predicated.
584 BBI.IsUnpredicable = true;
585 return;
586 }
587
588 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
589 // still potentially predicable.
590 std::vector<MachineOperand> PredDefs;
591 if (TII->DefinesPredicate(I, PredDefs))
592 BBI.ClobbersPred = true;
593
Chris Lattner5b930372008-01-07 07:27:27 +0000594 if (!TID.isPredicable()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595 BBI.IsUnpredicable = true;
596 return;
597 }
598 }
599}
600
601/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
602/// predicated by the specified predicate.
603bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
604 std::vector<MachineOperand> &Pred,
605 bool isTriangle, bool RevBranch) {
606 // If the block is dead or unpredicable, then it cannot be predicated.
607 if (BBI.IsDone || BBI.IsUnpredicable)
608 return false;
609
610 // If it is already predicated, check if its predicate subsumes the new
611 // predicate.
612 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
613 return false;
614
615 if (BBI.BrCond.size()) {
616 if (!isTriangle)
617 return false;
618
619 // Test predicate subsumsion.
620 std::vector<MachineOperand> RevPred(Pred);
621 std::vector<MachineOperand> Cond(BBI.BrCond);
622 if (RevBranch) {
623 if (TII->ReverseBranchCondition(Cond))
624 return false;
625 }
626 if (TII->ReverseBranchCondition(RevPred) ||
627 !TII->SubsumesPredicate(Cond, RevPred))
628 return false;
629 }
630
631 return true;
632}
633
634/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
635/// the specified block. Record its successors and whether it looks like an
636/// if-conversion candidate.
637IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
638 std::vector<IfcvtToken*> &Tokens) {
639 BBInfo &BBI = BBAnalysis[BB->getNumber()];
640
641 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
642 return BBI;
643
644 BBI.BB = BB;
645 BBI.IsBeingAnalyzed = true;
646
647 ScanInstructions(BBI);
648
649 // Unanalyable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000650 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 BBI.IsBeingAnalyzed = false;
652 BBI.IsAnalyzed = true;
653 return BBI;
654 }
655
656 // Do not ifcvt if either path is a back edge to the entry block.
657 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
658 BBI.IsBeingAnalyzed = false;
659 BBI.IsAnalyzed = true;
660 return BBI;
661 }
662
663 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
664 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
665
666 if (TrueBBI.IsDone && FalseBBI.IsDone) {
667 BBI.IsBeingAnalyzed = false;
668 BBI.IsAnalyzed = true;
669 return BBI;
670 }
671
672 std::vector<MachineOperand> RevCond(BBI.BrCond);
673 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
674
675 unsigned Dups = 0;
676 unsigned Dups2 = 0;
677 bool TNeedSub = TrueBBI.Predicate.size() > 0;
678 bool FNeedSub = FalseBBI.Predicate.size() > 0;
679 bool Enqueued = false;
680 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
681 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
682 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
683 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
684 FeasibilityAnalysis(FalseBBI, RevCond)) {
685 // Diamond:
686 // EBB
687 // / \_
688 // | |
689 // TBB FBB
690 // \ /
691 // TailBB
692 // Note TailBB can be empty.
693 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
694 Dups2));
695 Enqueued = true;
696 }
697
698 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
699 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
700 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
701 // Triangle:
702 // EBB
703 // | \_
704 // | |
705 // | TBB
706 // | /
707 // FBB
708 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
709 Enqueued = true;
710 }
711
712 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
713 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
714 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
715 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
716 Enqueued = true;
717 }
718
719 if (ValidSimple(TrueBBI, Dups) &&
720 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
721 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
722 // Simple (split, no rejoin):
723 // EBB
724 // | \_
725 // | |
726 // | TBB---> exit
727 // |
728 // FBB
729 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
730 Enqueued = true;
731 }
732
733 if (CanRevCond) {
734 // Try the other path...
735 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
736 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
737 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
738 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
739 Enqueued = true;
740 }
741
742 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
743 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
744 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
745 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
746 Enqueued = true;
747 }
748
749 if (ValidSimple(FalseBBI, Dups) &&
750 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
751 FeasibilityAnalysis(FalseBBI, RevCond)) {
752 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
753 Enqueued = true;
754 }
755 }
756
757 BBI.IsEnqueued = Enqueued;
758 BBI.IsBeingAnalyzed = false;
759 BBI.IsAnalyzed = true;
760 return BBI;
761}
762
763/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
764/// candidates. It returns true if any CFG restructuring is done to expose more
765/// if-conversion opportunities.
766bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
767 std::vector<IfcvtToken*> &Tokens) {
768 bool Change = false;
769 std::set<MachineBasicBlock*> Visited;
770 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
771 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
772 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
773 MachineBasicBlock *BB = *I;
774 AnalyzeBlock(BB, Tokens);
775 }
776 }
777
778 // Sort to favor more complex ifcvt scheme.
779 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
780
781 return Change;
782}
783
784/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
785/// that all the intervening blocks are empty (given BB can fall through to its
786/// next block).
787static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
788 MachineFunction::iterator I = BB;
789 MachineFunction::iterator TI = ToBB;
790 MachineFunction::iterator E = BB->getParent()->end();
791 while (++I != TI)
792 if (I == E || !I->empty())
793 return false;
794 return true;
795}
796
797/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
798/// to determine if it can be if-converted. If predecessor is already enqueued,
799/// dequeue it!
800void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
801 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
802 E = BB->pred_end(); PI != E; ++PI) {
803 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
804 if (PBBI.IsDone || PBBI.BB == BB)
805 continue;
806 PBBI.IsAnalyzed = false;
807 PBBI.IsEnqueued = false;
808 }
809}
810
811/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
812///
813static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
814 const TargetInstrInfo *TII) {
815 std::vector<MachineOperand> NoCond;
816 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
817}
818
819/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
820/// successors.
821void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
822 MachineBasicBlock *TBB = NULL, *FBB = NULL;
823 std::vector<MachineOperand> Cond;
824 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
825 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
826}
827
828/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
829///
830bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
831 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
832 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
833 BBInfo *CvtBBI = &TrueBBI;
834 BBInfo *NextBBI = &FalseBBI;
835
836 std::vector<MachineOperand> Cond(BBI.BrCond);
837 if (Kind == ICSimpleFalse)
838 std::swap(CvtBBI, NextBBI);
839
840 if (CvtBBI->IsDone ||
841 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
842 // Something has changed. It's no longer safe to predicate this block.
843 BBI.IsAnalyzed = false;
844 CvtBBI->IsAnalyzed = false;
845 return false;
846 }
847
848 if (Kind == ICSimpleFalse)
849 TII->ReverseBranchCondition(Cond);
850
851 if (CvtBBI->BB->pred_size() > 1) {
852 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
853 // Copy instructions in the true block, predicate them add them to
854 // the entry block.
855 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
856 } else {
857 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
858
859 // Merge converted block into entry block.
860 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
861 MergeBlocks(BBI, *CvtBBI);
862 }
863
864 bool IterIfcvt = true;
865 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
866 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
867 BBI.HasFallThrough = false;
868 // Now ifcvt'd block will look like this:
869 // BB:
870 // ...
871 // t, f = cmp
872 // if t op
873 // b BBf
874 //
875 // We cannot further ifcvt this block because the unconditional branch
876 // will have to be predicated on the new condition, that will not be
877 // available if cmp executes.
878 IterIfcvt = false;
879 }
880
881 RemoveExtraEdges(BBI);
882
883 // Update block info. BB can be iteratively if-converted.
884 if (!IterIfcvt)
885 BBI.IsDone = true;
886 InvalidatePreds(BBI.BB);
887 CvtBBI->IsDone = true;
888
889 // FIXME: Must maintain LiveIns.
890 return true;
891}
892
893/// IfConvertTriangle - If convert a triangle sub-CFG.
894///
895bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
896 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
897 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
898 BBInfo *CvtBBI = &TrueBBI;
899 BBInfo *NextBBI = &FalseBBI;
900
901 std::vector<MachineOperand> Cond(BBI.BrCond);
902 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
903 std::swap(CvtBBI, NextBBI);
904
905 if (CvtBBI->IsDone ||
906 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
907 // Something has changed. It's no longer safe to predicate this block.
908 BBI.IsAnalyzed = false;
909 CvtBBI->IsAnalyzed = false;
910 return false;
911 }
912
913 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
914 TII->ReverseBranchCondition(Cond);
915
916 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
917 ReverseBranchCondition(*CvtBBI);
918 // BB has been changed, modify its predecessors (except for this
919 // one) so they don't get ifcvt'ed based on bad intel.
920 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
921 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
922 MachineBasicBlock *PBB = *PI;
923 if (PBB == BBI.BB)
924 continue;
925 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
926 if (PBBI.IsEnqueued) {
927 PBBI.IsAnalyzed = false;
928 PBBI.IsEnqueued = false;
929 }
930 }
931 }
932
933 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
934 bool DupBB = CvtBBI->BB->pred_size() > 1;
935 if (DupBB) {
936 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
937 // Copy instructions in the true block, predicate them add them to
938 // the entry block.
939 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
940 } else {
941 // Predicate the 'true' block after removing its branch.
942 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
943 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
944 }
945
946 if (!DupBB) {
947 // Now merge the entry of the triangle with the true block.
948 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
949 MergeBlocks(BBI, *CvtBBI);
950 }
951
952 // If 'true' block has a 'false' successor, add an exit branch to it.
953 if (HasEarlyExit) {
954 std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
955 if (TII->ReverseBranchCondition(RevCond))
956 assert(false && "Unable to reverse branch condition!");
957 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
958 BBI.BB->addSuccessor(CvtBBI->FalseBB);
959 }
960
961 // Merge in the 'false' block if the 'false' block has no other
962 // predecessors. Otherwise, add a unconditional branch from to 'false'.
963 bool FalseBBDead = false;
964 bool IterIfcvt = true;
965 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
966 if (!isFallThrough) {
967 // Only merge them if the true block does not fallthrough to the false
968 // block. By not merging them, we make it possible to iteratively
969 // ifcvt the blocks.
970 if (!HasEarlyExit &&
971 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
972 MergeBlocks(BBI, *NextBBI);
973 FalseBBDead = true;
974 } else {
975 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
976 BBI.HasFallThrough = false;
977 }
978 // Mixed predicated and unpredicated code. This cannot be iteratively
979 // predicated.
980 IterIfcvt = false;
981 }
982
983 RemoveExtraEdges(BBI);
984
985 // Update block info. BB can be iteratively if-converted.
986 if (!IterIfcvt)
987 BBI.IsDone = true;
988 InvalidatePreds(BBI.BB);
989 CvtBBI->IsDone = true;
990 if (FalseBBDead)
991 NextBBI->IsDone = true;
992
993 // FIXME: Must maintain LiveIns.
994 return true;
995}
996
997/// IfConvertDiamond - If convert a diamond sub-CFG.
998///
999bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1000 unsigned NumDups1, unsigned NumDups2) {
1001 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1002 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1003 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1004 // True block must fall through or ended with unanalyzable terminator.
1005 if (!TailBB) {
1006 if (blockAlwaysFallThrough(TrueBBI))
1007 TailBB = FalseBBI.TrueBB;
1008 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1009 }
1010
1011 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1012 TrueBBI.BB->pred_size() > 1 ||
1013 FalseBBI.BB->pred_size() > 1) {
1014 // Something has changed. It's no longer safe to predicate these blocks.
1015 BBI.IsAnalyzed = false;
1016 TrueBBI.IsAnalyzed = false;
1017 FalseBBI.IsAnalyzed = false;
1018 return false;
1019 }
1020
1021 // Merge the 'true' and 'false' blocks by copying the instructions
1022 // from the 'false' block to the 'true' block. That is, unless the true
1023 // block would clobber the predicate, in that case, do the opposite.
1024 BBInfo *BBI1 = &TrueBBI;
1025 BBInfo *BBI2 = &FalseBBI;
1026 std::vector<MachineOperand> RevCond(BBI.BrCond);
1027 TII->ReverseBranchCondition(RevCond);
1028 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
1029 std::vector<MachineOperand> *Cond2 = &RevCond;
1030
1031 // Figure out the more profitable ordering.
1032 bool DoSwap = false;
1033 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1034 DoSwap = true;
1035 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1036 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1037 DoSwap = true;
1038 }
1039 if (DoSwap) {
1040 std::swap(BBI1, BBI2);
1041 std::swap(Cond1, Cond2);
1042 }
1043
1044 // Remove the conditional branch from entry to the blocks.
1045 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1046
1047 // Remove the duplicated instructions at the beginnings of both paths.
1048 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1049 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1050 BBI1->NonPredSize -= NumDups1;
1051 BBI2->NonPredSize -= NumDups1;
1052 while (NumDups1 != 0) {
1053 ++DI1;
1054 ++DI2;
1055 --NumDups1;
1056 }
1057 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1058 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1059
1060 // Predicate the 'true' block after removing its branch.
1061 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1062 DI1 = BBI1->BB->end();
1063 for (unsigned i = 0; i != NumDups2; ++i)
1064 --DI1;
1065 BBI1->BB->erase(DI1, BBI1->BB->end());
1066 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1);
1067
1068 // Predicate the 'false' block.
1069 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1070 DI2 = BBI2->BB->end();
1071 while (NumDups2 != 0) {
1072 --DI2;
1073 --NumDups2;
1074 }
1075 PredicateBlock(*BBI2, DI2, *Cond2);
1076
1077 // Merge the true block into the entry of the diamond.
1078 MergeBlocks(BBI, *BBI1);
1079 MergeBlocks(BBI, *BBI2);
1080
1081 // If the if-converted block fallthrough or unconditionally branch into the
1082 // tail block, and the tail block does not have other predecessors, then
1083 // fold the tail block in as well. Otherwise, unless it falls through to the
1084 // tail, add a unconditional branch to it.
1085 if (TailBB) {
1086 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1087 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1088 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1089 MergeBlocks(BBI, TailBBI);
1090 TailBBI.IsDone = true;
1091 } else {
1092 InsertUncondBranch(BBI.BB, TailBB, TII);
1093 BBI.HasFallThrough = false;
1094 }
1095 }
1096
1097 RemoveExtraEdges(BBI);
1098
1099 // Update block info.
1100 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1101 InvalidatePreds(BBI.BB);
1102
1103 // FIXME: Must maintain LiveIns.
1104 return true;
1105}
1106
1107/// PredicateBlock - Predicate instructions from the start of the block to the
1108/// specified end with the specified condition.
1109void IfConverter::PredicateBlock(BBInfo &BBI,
1110 MachineBasicBlock::iterator E,
1111 std::vector<MachineOperand> &Cond) {
1112 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1113 if (TII->isPredicated(I))
1114 continue;
1115 if (!TII->PredicateInstruction(I, Cond)) {
1116 cerr << "Unable to predicate " << *I << "!\n";
1117 abort();
1118 }
1119 }
1120
1121 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1122
1123 BBI.IsAnalyzed = false;
1124 BBI.NonPredSize = 0;
1125
1126 NumIfConvBBs++;
1127}
1128
1129/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1130/// the destination block. Skip end of block branches if IgnoreBr is true.
1131void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1132 std::vector<MachineOperand> &Cond,
1133 bool IgnoreBr) {
1134 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1135 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001136 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 bool isPredicated = TII->isPredicated(I);
1138 // Do not copy the end of the block branches.
Chris Lattner5b930372008-01-07 07:27:27 +00001139 if (IgnoreBr && !isPredicated && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 break;
1141
1142 MachineInstr *MI = I->clone();
1143 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1144 ToBBI.NonPredSize++;
1145
1146 if (!isPredicated)
1147 if (!TII->PredicateInstruction(MI, Cond)) {
1148 cerr << "Unable to predicate " << *MI << "!\n";
1149 abort();
1150 }
1151 }
1152
1153 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1154 FromBBI.BB->succ_end());
1155 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1156 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1157
1158 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1159 MachineBasicBlock *Succ = Succs[i];
1160 // Fallthrough edge can't be transferred.
1161 if (Succ == FallThrough)
1162 continue;
1163 if (!ToBBI.BB->isSuccessor(Succ))
1164 ToBBI.BB->addSuccessor(Succ);
1165 }
1166
1167 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1168 std::back_inserter(ToBBI.Predicate));
1169 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1170
1171 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1172 ToBBI.IsAnalyzed = false;
1173
1174 NumDupBBs++;
1175}
1176
1177/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1178///
1179void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1180 ToBBI.BB->splice(ToBBI.BB->end(),
1181 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1182
1183 // Redirect all branches to FromBB to ToBB.
1184 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1185 FromBBI.BB->pred_end());
1186 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1187 MachineBasicBlock *Pred = Preds[i];
1188 if (Pred == ToBBI.BB)
1189 continue;
1190 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1191 }
1192
1193 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1194 FromBBI.BB->succ_end());
1195 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1196 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1197
1198 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1199 MachineBasicBlock *Succ = Succs[i];
1200 // Fallthrough edge can't be transferred.
1201 if (Succ == FallThrough)
1202 continue;
1203 FromBBI.BB->removeSuccessor(Succ);
1204 if (!ToBBI.BB->isSuccessor(Succ))
1205 ToBBI.BB->addSuccessor(Succ);
1206 }
1207
1208 // Now FromBBI always fall through to the next block!
1209 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1210 FromBBI.BB->addSuccessor(NBB);
1211
1212 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1213 std::back_inserter(ToBBI.Predicate));
1214 FromBBI.Predicate.clear();
1215
1216 ToBBI.NonPredSize += FromBBI.NonPredSize;
1217 FromBBI.NonPredSize = 0;
1218
1219 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1220 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1221 ToBBI.IsAnalyzed = false;
1222 FromBBI.IsAnalyzed = false;
1223}