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