It turns out most of the thumb2 instructions are not allowed to touch SP. The semanti...
[llvm/avr.git] / lib / CodeGen / IfConversion.cpp
blob9dbd6d1241caabd354e4b2fb2c571bc43946ba86
1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the machine instruction level if-conversion pass.
12 //===----------------------------------------------------------------------===//
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/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/ADT/DepthFirstIterator.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/STLExtras.h"
29 using namespace llvm;
31 // Hidden options for help debugging.
32 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
33 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
34 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
35 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
36 cl::init(false), cl::Hidden);
37 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
38 cl::init(false), cl::Hidden);
39 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
40 cl::init(false), cl::Hidden);
41 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
42 cl::init(false), cl::Hidden);
43 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
44 cl::init(false), cl::Hidden);
45 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
46 cl::init(false), cl::Hidden);
47 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
48 cl::init(false), cl::Hidden);
50 STATISTIC(NumSimple, "Number of simple if-conversions performed");
51 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
52 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
53 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
54 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
55 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
56 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
57 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
58 STATISTIC(NumDupBBs, "Number of duplicated blocks");
60 namespace {
61 class VISIBILITY_HIDDEN IfConverter : public MachineFunctionPass {
62 enum IfcvtKind {
63 ICNotClassfied, // BB data valid, but not classified.
64 ICSimpleFalse, // Same as ICSimple, but on the false path.
65 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
66 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
67 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
68 ICTriangleFalse, // Same as ICTriangle, but on the false path.
69 ICTriangle, // BB is entry of a triangle sub-CFG.
70 ICDiamond // BB is entry of a diamond sub-CFG.
73 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
74 /// if-conversion feasibility analysis. This includes results from
75 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
76 /// classification, and common tail block of its successors (if it's a
77 /// diamond shape), its size, whether it's predicable, and whether any
78 /// instruction can clobber the 'would-be' predicate.
79 ///
80 /// IsDone - True if BB is not to be considered for ifcvt.
81 /// IsBeingAnalyzed - True if BB is currently being analyzed.
82 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
83 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
84 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
85 /// HasFallThrough - True if BB may fallthrough to the following BB.
86 /// IsUnpredicable - True if BB is known to be unpredicable.
87 /// ClobbersPred - True if BB could modify predicates (e.g. has
88 /// cmp, call, etc.)
89 /// NonPredSize - Number of non-predicated instructions.
90 /// BB - Corresponding MachineBasicBlock.
91 /// TrueBB / FalseBB- See AnalyzeBranch().
92 /// BrCond - Conditions for end of block conditional branches.
93 /// Predicate - Predicate used in the BB.
94 struct BBInfo {
95 bool IsDone : 1;
96 bool IsBeingAnalyzed : 1;
97 bool IsAnalyzed : 1;
98 bool IsEnqueued : 1;
99 bool IsBrAnalyzable : 1;
100 bool HasFallThrough : 1;
101 bool IsUnpredicable : 1;
102 bool CannotBeCopied : 1;
103 bool ClobbersPred : 1;
104 unsigned NonPredSize;
105 MachineBasicBlock *BB;
106 MachineBasicBlock *TrueBB;
107 MachineBasicBlock *FalseBB;
108 SmallVector<MachineOperand, 4> BrCond;
109 SmallVector<MachineOperand, 4> Predicate;
110 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
111 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
112 HasFallThrough(false), IsUnpredicable(false),
113 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
114 BB(0), TrueBB(0), FalseBB(0) {}
117 /// IfcvtToken - Record information about pending if-conversions to attemp:
118 /// BBI - Corresponding BBInfo.
119 /// Kind - Type of block. See IfcvtKind.
120 /// NeedSubsumption - True if the to-be-predicated BB has already been
121 /// predicated.
122 /// NumDups - Number of instructions that would be duplicated due
123 /// to this if-conversion. (For diamonds, the number of
124 /// identical instructions at the beginnings of both
125 /// paths).
126 /// NumDups2 - For diamonds, the number of identical instructions
127 /// at the ends of both paths.
128 struct IfcvtToken {
129 BBInfo &BBI;
130 IfcvtKind Kind;
131 bool NeedSubsumption;
132 unsigned NumDups;
133 unsigned NumDups2;
134 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
135 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
138 /// Roots - Basic blocks that do not have successors. These are the starting
139 /// points of Graph traversal.
140 std::vector<MachineBasicBlock*> Roots;
142 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
143 /// basic block number.
144 std::vector<BBInfo> BBAnalysis;
146 const TargetLowering *TLI;
147 const TargetInstrInfo *TII;
148 bool MadeChange;
149 int FnNum;
150 public:
151 static char ID;
152 IfConverter() : MachineFunctionPass(&ID), FnNum(-1) {}
154 virtual bool runOnMachineFunction(MachineFunction &MF);
155 virtual const char *getPassName() const { return "If Converter"; }
157 private:
158 bool ReverseBranchCondition(BBInfo &BBI);
159 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
160 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
161 bool FalseBranch, unsigned &Dups) const;
162 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
163 unsigned &Dups1, unsigned &Dups2) const;
164 void ScanInstructions(BBInfo &BBI);
165 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
166 std::vector<IfcvtToken*> &Tokens);
167 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
168 bool isTriangle = false, bool RevBranch = false);
169 bool AnalyzeBlocks(MachineFunction &MF,
170 std::vector<IfcvtToken*> &Tokens);
171 void InvalidatePreds(MachineBasicBlock *BB);
172 void RemoveExtraEdges(BBInfo &BBI);
173 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
174 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
175 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
176 unsigned NumDups1, unsigned NumDups2);
177 void PredicateBlock(BBInfo &BBI,
178 MachineBasicBlock::iterator E,
179 SmallVectorImpl<MachineOperand> &Cond);
180 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
181 SmallVectorImpl<MachineOperand> &Cond,
182 bool IgnoreBr = false);
183 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
185 bool MeetIfcvtSizeLimit(unsigned Size) const {
186 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit();
189 // blockAlwaysFallThrough - Block ends without a terminator.
190 bool blockAlwaysFallThrough(BBInfo &BBI) const {
191 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
194 // IfcvtTokenCmp - Used to sort if-conversion candidates.
195 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
196 int Incr1 = (C1->Kind == ICDiamond)
197 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
198 int Incr2 = (C2->Kind == ICDiamond)
199 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
200 if (Incr1 > Incr2)
201 return true;
202 else if (Incr1 == Incr2) {
203 // Favors subsumption.
204 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
205 return true;
206 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
207 // Favors diamond over triangle, etc.
208 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
209 return true;
210 else if (C1->Kind == C2->Kind)
211 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
214 return false;
218 char IfConverter::ID = 0;
221 static RegisterPass<IfConverter>
222 X("if-converter", "If Converter");
224 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
226 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
227 TLI = MF.getTarget().getTargetLowering();
228 TII = MF.getTarget().getInstrInfo();
229 if (!TII) return false;
231 DEBUG(errs() << "\nIfcvt: function (" << ++FnNum << ") \'"
232 << MF.getFunction()->getName() << "\'");
234 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
235 DOUT << " skipped\n";
236 return false;
238 DOUT << "\n";
240 MF.RenumberBlocks();
241 BBAnalysis.resize(MF.getNumBlockIDs());
243 // Look for root nodes, i.e. blocks without successors.
244 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
245 if (I->succ_empty())
246 Roots.push_back(I);
248 std::vector<IfcvtToken*> Tokens;
249 MadeChange = false;
250 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
251 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
252 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
253 // Do an initial analysis for each basic block and find all the potential
254 // candidates to perform if-conversion.
255 bool Change = AnalyzeBlocks(MF, Tokens);
256 while (!Tokens.empty()) {
257 IfcvtToken *Token = Tokens.back();
258 Tokens.pop_back();
259 BBInfo &BBI = Token->BBI;
260 IfcvtKind Kind = Token->Kind;
261 unsigned NumDups = Token->NumDups;
262 unsigned NumDups2 = Token->NumDups2;
264 delete Token;
266 // If the block has been evicted out of the queue or it has already been
267 // marked dead (due to it being predicated), then skip it.
268 if (BBI.IsDone)
269 BBI.IsEnqueued = false;
270 if (!BBI.IsEnqueued)
271 continue;
273 BBI.IsEnqueued = false;
275 bool RetVal = false;
276 switch (Kind) {
277 default: assert(false && "Unexpected!");
278 break;
279 case ICSimple:
280 case ICSimpleFalse: {
281 bool isFalse = Kind == ICSimpleFalse;
282 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
283 DOUT << "Ifcvt (Simple" << (Kind == ICSimpleFalse ? " false" :"")
284 << "): BB#" << BBI.BB->getNumber() << " ("
285 << ((Kind == ICSimpleFalse)
286 ? BBI.FalseBB->getNumber()
287 : BBI.TrueBB->getNumber()) << ") ";
288 RetVal = IfConvertSimple(BBI, Kind);
289 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
290 if (RetVal) {
291 if (isFalse) NumSimpleFalse++;
292 else NumSimple++;
294 break;
296 case ICTriangle:
297 case ICTriangleRev:
298 case ICTriangleFalse:
299 case ICTriangleFRev: {
300 bool isFalse = Kind == ICTriangleFalse;
301 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
302 if (DisableTriangle && !isFalse && !isRev) break;
303 if (DisableTriangleR && !isFalse && isRev) break;
304 if (DisableTriangleF && isFalse && !isRev) break;
305 if (DisableTriangleFR && isFalse && isRev) break;
306 DOUT << "Ifcvt (Triangle";
307 if (isFalse)
308 DOUT << " false";
309 if (isRev)
310 DOUT << " rev";
311 DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
312 << BBI.TrueBB->getNumber() << ",F:"
313 << BBI.FalseBB->getNumber() << ") ";
314 RetVal = IfConvertTriangle(BBI, Kind);
315 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
316 if (RetVal) {
317 if (isFalse) {
318 if (isRev) NumTriangleFRev++;
319 else NumTriangleFalse++;
320 } else {
321 if (isRev) NumTriangleRev++;
322 else NumTriangle++;
325 break;
327 case ICDiamond: {
328 if (DisableDiamond) break;
329 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
330 << BBI.TrueBB->getNumber() << ",F:"
331 << BBI.FalseBB->getNumber() << ") ";
332 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
333 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
334 if (RetVal) NumDiamonds++;
335 break;
339 Change |= RetVal;
341 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
342 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
343 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
344 break;
347 if (!Change)
348 break;
349 MadeChange |= Change;
352 // Delete tokens in case of early exit.
353 while (!Tokens.empty()) {
354 IfcvtToken *Token = Tokens.back();
355 Tokens.pop_back();
356 delete Token;
359 Tokens.clear();
360 Roots.clear();
361 BBAnalysis.clear();
363 return MadeChange;
366 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
367 /// its 'true' successor.
368 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
369 MachineBasicBlock *TrueBB) {
370 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
371 E = BB->succ_end(); SI != E; ++SI) {
372 MachineBasicBlock *SuccBB = *SI;
373 if (SuccBB != TrueBB)
374 return SuccBB;
376 return NULL;
379 /// ReverseBranchCondition - Reverse the condition of the end of the block
380 /// branch. Swap block's 'true' and 'false' successors.
381 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
382 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
383 TII->RemoveBranch(*BBI.BB);
384 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
385 std::swap(BBI.TrueBB, BBI.FalseBB);
386 return true;
388 return false;
391 /// getNextBlock - Returns the next block in the function blocks ordering. If
392 /// it is the end, returns NULL.
393 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
394 MachineFunction::iterator I = BB;
395 MachineFunction::iterator E = BB->getParent()->end();
396 if (++I == E)
397 return NULL;
398 return I;
401 /// ValidSimple - Returns true if the 'true' block (along with its
402 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
403 /// number of instructions that the ifcvt would need to duplicate if performed
404 /// in Dups.
405 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
406 Dups = 0;
407 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
408 return false;
410 if (TrueBBI.IsBrAnalyzable)
411 return false;
413 if (TrueBBI.BB->pred_size() > 1) {
414 if (TrueBBI.CannotBeCopied ||
415 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
416 return false;
417 Dups = TrueBBI.NonPredSize;
420 return true;
423 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
424 /// with their common predecessor) forms a valid triangle shape for ifcvt.
425 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
426 /// branches to the false branch rather than the other way around. It also
427 /// returns the number of instructions that the ifcvt would need to duplicate
428 /// if performed in 'Dups'.
429 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
430 bool FalseBranch, unsigned &Dups) const {
431 Dups = 0;
432 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
433 return false;
435 if (TrueBBI.BB->pred_size() > 1) {
436 if (TrueBBI.CannotBeCopied)
437 return false;
439 unsigned Size = TrueBBI.NonPredSize;
440 if (TrueBBI.IsBrAnalyzable) {
441 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
442 // Ends with an unconditional branch. It will be removed.
443 --Size;
444 else {
445 MachineBasicBlock *FExit = FalseBranch
446 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
447 if (FExit)
448 // Require a conditional branch
449 ++Size;
452 if (Size > TLI->getIfCvtDupBlockSizeLimit())
453 return false;
454 Dups = Size;
457 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
458 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
459 MachineFunction::iterator I = TrueBBI.BB;
460 if (++I == TrueBBI.BB->getParent()->end())
461 return false;
462 TExit = I;
464 return TExit && TExit == FalseBBI.BB;
467 static
468 MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
469 const TargetInstrInfo *TII) {
470 MachineBasicBlock::iterator I = BB->end();
471 while (I != BB->begin()) {
472 --I;
473 if (!I->getDesc().isBranch())
474 break;
476 return I;
479 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
480 /// with their common predecessor) forms a valid diamond shape for ifcvt.
481 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
482 unsigned &Dups1, unsigned &Dups2) const {
483 Dups1 = Dups2 = 0;
484 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
485 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
486 return false;
488 MachineBasicBlock *TT = TrueBBI.TrueBB;
489 MachineBasicBlock *FT = FalseBBI.TrueBB;
491 if (!TT && blockAlwaysFallThrough(TrueBBI))
492 TT = getNextBlock(TrueBBI.BB);
493 if (!FT && blockAlwaysFallThrough(FalseBBI))
494 FT = getNextBlock(FalseBBI.BB);
495 if (TT != FT)
496 return false;
497 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
498 return false;
499 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
500 return false;
502 // FIXME: Allow true block to have an early exit?
503 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
504 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
505 return false;
507 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
508 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
509 while (TI != TrueBBI.BB->end() && FI != FalseBBI.BB->end()) {
510 if (!TI->isIdenticalTo(FI))
511 break;
512 ++Dups1;
513 ++TI;
514 ++FI;
517 TI = firstNonBranchInst(TrueBBI.BB, TII);
518 FI = firstNonBranchInst(FalseBBI.BB, TII);
519 while (TI != TrueBBI.BB->begin() && FI != FalseBBI.BB->begin()) {
520 if (!TI->isIdenticalTo(FI))
521 break;
522 ++Dups2;
523 --TI;
524 --FI;
527 return true;
530 /// ScanInstructions - Scan all the instructions in the block to determine if
531 /// the block is predicable. In most cases, that means all the instructions
532 /// in the block are isPredicable(). Also checks if the block contains any
533 /// instruction which can clobber a predicate (e.g. condition code register).
534 /// If so, the block is not predicable unless it's the last instruction.
535 void IfConverter::ScanInstructions(BBInfo &BBI) {
536 if (BBI.IsDone)
537 return;
539 bool AlreadyPredicated = BBI.Predicate.size() > 0;
540 // First analyze the end of BB branches.
541 BBI.TrueBB = BBI.FalseBB = NULL;
542 BBI.BrCond.clear();
543 BBI.IsBrAnalyzable =
544 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
545 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
547 if (BBI.BrCond.size()) {
548 // No false branch. This BB must end with a conditional branch and a
549 // fallthrough.
550 if (!BBI.FalseBB)
551 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
552 if (!BBI.FalseBB) {
553 // Malformed bcc? True and false blocks are the same?
554 BBI.IsUnpredicable = true;
555 return;
559 // Then scan all the instructions.
560 BBI.NonPredSize = 0;
561 BBI.ClobbersPred = false;
562 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
563 I != E; ++I) {
564 const TargetInstrDesc &TID = I->getDesc();
565 if (TID.isNotDuplicable())
566 BBI.CannotBeCopied = true;
568 bool isPredicated = TII->isPredicated(I);
569 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
571 if (!isCondBr) {
572 if (!isPredicated)
573 BBI.NonPredSize++;
574 else if (!AlreadyPredicated) {
575 // FIXME: This instruction is already predicated before the
576 // if-conversion pass. It's probably something like a conditional move.
577 // Mark this block unpredicable for now.
578 BBI.IsUnpredicable = true;
579 return;
583 if (BBI.ClobbersPred && !isPredicated) {
584 // Predicate modification instruction should end the block (except for
585 // already predicated instructions and end of block branches).
586 if (isCondBr) {
587 // A conditional branch is not predicable, but it may be eliminated.
588 continue;
591 // Predicate may have been modified, the subsequent (currently)
592 // unpredicated instructions cannot be correctly predicated.
593 BBI.IsUnpredicable = true;
594 return;
597 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
598 // still potentially predicable.
599 std::vector<MachineOperand> PredDefs;
600 if (TII->DefinesPredicate(I, PredDefs))
601 BBI.ClobbersPred = true;
603 if (!TID.isPredicable()) {
604 BBI.IsUnpredicable = true;
605 return;
610 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
611 /// predicated by the specified predicate.
612 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
613 SmallVectorImpl<MachineOperand> &Pred,
614 bool isTriangle, bool RevBranch) {
615 // If the block is dead or unpredicable, then it cannot be predicated.
616 if (BBI.IsDone || BBI.IsUnpredicable)
617 return false;
619 // If it is already predicated, check if its predicate subsumes the new
620 // predicate.
621 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
622 return false;
624 if (BBI.BrCond.size()) {
625 if (!isTriangle)
626 return false;
628 // Test predicate subsumption.
629 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
630 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
631 if (RevBranch) {
632 if (TII->ReverseBranchCondition(Cond))
633 return false;
635 if (TII->ReverseBranchCondition(RevPred) ||
636 !TII->SubsumesPredicate(Cond, RevPred))
637 return false;
640 return true;
643 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
644 /// the specified block. Record its successors and whether it looks like an
645 /// if-conversion candidate.
646 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
647 std::vector<IfcvtToken*> &Tokens) {
648 BBInfo &BBI = BBAnalysis[BB->getNumber()];
650 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
651 return BBI;
653 BBI.BB = BB;
654 BBI.IsBeingAnalyzed = true;
656 ScanInstructions(BBI);
658 // Unanalyzable or ends with fallthrough or unconditional branch.
659 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
660 BBI.IsBeingAnalyzed = false;
661 BBI.IsAnalyzed = true;
662 return BBI;
665 // Do not ifcvt if either path is a back edge to the entry block.
666 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
667 BBI.IsBeingAnalyzed = false;
668 BBI.IsAnalyzed = true;
669 return BBI;
672 // Do not ifcvt if true and false fallthrough blocks are the same.
673 if (!BBI.FalseBB) {
674 BBI.IsBeingAnalyzed = false;
675 BBI.IsAnalyzed = true;
676 return BBI;
679 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
680 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
682 if (TrueBBI.IsDone && FalseBBI.IsDone) {
683 BBI.IsBeingAnalyzed = false;
684 BBI.IsAnalyzed = true;
685 return BBI;
688 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
689 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
691 unsigned Dups = 0;
692 unsigned Dups2 = 0;
693 bool TNeedSub = TrueBBI.Predicate.size() > 0;
694 bool FNeedSub = FalseBBI.Predicate.size() > 0;
695 bool Enqueued = false;
696 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
697 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
698 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
699 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
700 FeasibilityAnalysis(FalseBBI, RevCond)) {
701 // Diamond:
702 // EBB
703 // / \_
704 // | |
705 // TBB FBB
706 // \ /
707 // TailBB
708 // Note TailBB can be empty.
709 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
710 Dups2));
711 Enqueued = true;
714 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
715 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
716 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
717 // Triangle:
718 // EBB
719 // | \_
720 // | |
721 // | TBB
722 // | /
723 // FBB
724 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
725 Enqueued = true;
728 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
729 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
730 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
731 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
732 Enqueued = true;
735 if (ValidSimple(TrueBBI, Dups) &&
736 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
737 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
738 // Simple (split, no rejoin):
739 // EBB
740 // | \_
741 // | |
742 // | TBB---> exit
743 // |
744 // FBB
745 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
746 Enqueued = true;
749 if (CanRevCond) {
750 // Try the other path...
751 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
752 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
753 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
754 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
755 Enqueued = true;
758 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
759 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
760 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
761 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
762 Enqueued = true;
765 if (ValidSimple(FalseBBI, Dups) &&
766 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
767 FeasibilityAnalysis(FalseBBI, RevCond)) {
768 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
769 Enqueued = true;
773 BBI.IsEnqueued = Enqueued;
774 BBI.IsBeingAnalyzed = false;
775 BBI.IsAnalyzed = true;
776 return BBI;
779 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
780 /// candidates. It returns true if any CFG restructuring is done to expose more
781 /// if-conversion opportunities.
782 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
783 std::vector<IfcvtToken*> &Tokens) {
784 bool Change = false;
785 std::set<MachineBasicBlock*> Visited;
786 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
787 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
788 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
789 MachineBasicBlock *BB = *I;
790 AnalyzeBlock(BB, Tokens);
794 // Sort to favor more complex ifcvt scheme.
795 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
797 return Change;
800 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
801 /// that all the intervening blocks are empty (given BB can fall through to its
802 /// next block).
803 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
804 MachineFunction::iterator I = BB;
805 MachineFunction::iterator TI = ToBB;
806 MachineFunction::iterator E = BB->getParent()->end();
807 while (++I != TI)
808 if (I == E || !I->empty())
809 return false;
810 return true;
813 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
814 /// to determine if it can be if-converted. If predecessor is already enqueued,
815 /// dequeue it!
816 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
817 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
818 E = BB->pred_end(); PI != E; ++PI) {
819 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
820 if (PBBI.IsDone || PBBI.BB == BB)
821 continue;
822 PBBI.IsAnalyzed = false;
823 PBBI.IsEnqueued = false;
827 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
829 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
830 const TargetInstrInfo *TII) {
831 SmallVector<MachineOperand, 0> NoCond;
832 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
835 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
836 /// successors.
837 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
838 MachineBasicBlock *TBB = NULL, *FBB = NULL;
839 SmallVector<MachineOperand, 4> Cond;
840 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
841 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
844 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
846 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
847 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
848 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
849 BBInfo *CvtBBI = &TrueBBI;
850 BBInfo *NextBBI = &FalseBBI;
852 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
853 if (Kind == ICSimpleFalse)
854 std::swap(CvtBBI, NextBBI);
856 if (CvtBBI->IsDone ||
857 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
858 // Something has changed. It's no longer safe to predicate this block.
859 BBI.IsAnalyzed = false;
860 CvtBBI->IsAnalyzed = false;
861 return false;
864 if (Kind == ICSimpleFalse)
865 if (TII->ReverseBranchCondition(Cond))
866 assert(false && "Unable to reverse branch condition!");
868 if (CvtBBI->BB->pred_size() > 1) {
869 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
870 // Copy instructions in the true block, predicate them, and add them to
871 // the entry block.
872 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
873 } else {
874 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
876 // Merge converted block into entry block.
877 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
878 MergeBlocks(BBI, *CvtBBI);
881 bool IterIfcvt = true;
882 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
883 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
884 BBI.HasFallThrough = false;
885 // Now ifcvt'd block will look like this:
886 // BB:
887 // ...
888 // t, f = cmp
889 // if t op
890 // b BBf
892 // We cannot further ifcvt this block because the unconditional branch
893 // will have to be predicated on the new condition, that will not be
894 // available if cmp executes.
895 IterIfcvt = false;
898 RemoveExtraEdges(BBI);
900 // Update block info. BB can be iteratively if-converted.
901 if (!IterIfcvt)
902 BBI.IsDone = true;
903 InvalidatePreds(BBI.BB);
904 CvtBBI->IsDone = true;
906 // FIXME: Must maintain LiveIns.
907 return true;
910 /// IfConvertTriangle - If convert a triangle sub-CFG.
912 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
913 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
914 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
915 BBInfo *CvtBBI = &TrueBBI;
916 BBInfo *NextBBI = &FalseBBI;
918 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
919 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
920 std::swap(CvtBBI, NextBBI);
922 if (CvtBBI->IsDone ||
923 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
924 // Something has changed. It's no longer safe to predicate this block.
925 BBI.IsAnalyzed = false;
926 CvtBBI->IsAnalyzed = false;
927 return false;
930 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
931 if (TII->ReverseBranchCondition(Cond))
932 assert(false && "Unable to reverse branch condition!");
934 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
935 if (ReverseBranchCondition(*CvtBBI)) {
936 // BB has been changed, modify its predecessors (except for this
937 // one) so they don't get ifcvt'ed based on bad intel.
938 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
939 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
940 MachineBasicBlock *PBB = *PI;
941 if (PBB == BBI.BB)
942 continue;
943 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
944 if (PBBI.IsEnqueued) {
945 PBBI.IsAnalyzed = false;
946 PBBI.IsEnqueued = false;
952 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
953 bool DupBB = CvtBBI->BB->pred_size() > 1;
954 if (DupBB) {
955 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
956 // Copy instructions in the true block, predicate them, and add them to
957 // the entry block.
958 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
959 } else {
960 // Predicate the 'true' block after removing its branch.
961 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
962 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
964 // Now merge the entry of the triangle with the true block.
965 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
966 MergeBlocks(BBI, *CvtBBI);
969 // If 'true' block has a 'false' successor, add an exit branch to it.
970 if (HasEarlyExit) {
971 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
972 CvtBBI->BrCond.end());
973 if (TII->ReverseBranchCondition(RevCond))
974 assert(false && "Unable to reverse branch condition!");
975 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
976 BBI.BB->addSuccessor(CvtBBI->FalseBB);
979 // Merge in the 'false' block if the 'false' block has no other
980 // predecessors. Otherwise, add an unconditional branch to 'false'.
981 bool FalseBBDead = false;
982 bool IterIfcvt = true;
983 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
984 if (!isFallThrough) {
985 // Only merge them if the true block does not fallthrough to the false
986 // block. By not merging them, we make it possible to iteratively
987 // ifcvt the blocks.
988 if (!HasEarlyExit &&
989 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
990 MergeBlocks(BBI, *NextBBI);
991 FalseBBDead = true;
992 } else {
993 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
994 BBI.HasFallThrough = false;
996 // Mixed predicated and unpredicated code. This cannot be iteratively
997 // predicated.
998 IterIfcvt = false;
1001 RemoveExtraEdges(BBI);
1003 // Update block info. BB can be iteratively if-converted.
1004 if (!IterIfcvt)
1005 BBI.IsDone = true;
1006 InvalidatePreds(BBI.BB);
1007 CvtBBI->IsDone = true;
1008 if (FalseBBDead)
1009 NextBBI->IsDone = true;
1011 // FIXME: Must maintain LiveIns.
1012 return true;
1015 /// IfConvertDiamond - If convert a diamond sub-CFG.
1017 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1018 unsigned NumDups1, unsigned NumDups2) {
1019 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1020 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1021 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1022 // True block must fall through or end with an unanalyzable terminator.
1023 if (!TailBB) {
1024 if (blockAlwaysFallThrough(TrueBBI))
1025 TailBB = FalseBBI.TrueBB;
1026 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1029 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1030 TrueBBI.BB->pred_size() > 1 ||
1031 FalseBBI.BB->pred_size() > 1) {
1032 // Something has changed. It's no longer safe to predicate these blocks.
1033 BBI.IsAnalyzed = false;
1034 TrueBBI.IsAnalyzed = false;
1035 FalseBBI.IsAnalyzed = false;
1036 return false;
1039 // Merge the 'true' and 'false' blocks by copying the instructions
1040 // from the 'false' block to the 'true' block. That is, unless the true
1041 // block would clobber the predicate, in that case, do the opposite.
1042 BBInfo *BBI1 = &TrueBBI;
1043 BBInfo *BBI2 = &FalseBBI;
1044 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1045 if (TII->ReverseBranchCondition(RevCond))
1046 assert(false && "Unable to reverse branch condition!");
1047 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1048 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1050 // Figure out the more profitable ordering.
1051 bool DoSwap = false;
1052 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1053 DoSwap = true;
1054 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1055 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1056 DoSwap = true;
1058 if (DoSwap) {
1059 std::swap(BBI1, BBI2);
1060 std::swap(Cond1, Cond2);
1063 // Remove the conditional branch from entry to the blocks.
1064 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1066 // Remove the duplicated instructions at the beginnings of both paths.
1067 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1068 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1069 BBI1->NonPredSize -= NumDups1;
1070 BBI2->NonPredSize -= NumDups1;
1071 while (NumDups1 != 0) {
1072 ++DI1;
1073 ++DI2;
1074 --NumDups1;
1076 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1077 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1079 // Predicate the 'true' block after removing its branch.
1080 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1081 DI1 = BBI1->BB->end();
1082 for (unsigned i = 0; i != NumDups2; ++i)
1083 --DI1;
1084 BBI1->BB->erase(DI1, BBI1->BB->end());
1085 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1);
1087 // Predicate the 'false' block.
1088 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1089 DI2 = BBI2->BB->end();
1090 while (NumDups2 != 0) {
1091 --DI2;
1092 --NumDups2;
1094 PredicateBlock(*BBI2, DI2, *Cond2);
1096 // Merge the true block into the entry of the diamond.
1097 MergeBlocks(BBI, *BBI1);
1098 MergeBlocks(BBI, *BBI2);
1100 // If the if-converted block falls through or unconditionally branches into
1101 // the tail block, and the tail block does not have other predecessors, then
1102 // fold the tail block in as well. Otherwise, unless it falls through to the
1103 // tail, add a unconditional branch to it.
1104 if (TailBB) {
1105 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1106 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1107 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1108 MergeBlocks(BBI, TailBBI);
1109 TailBBI.IsDone = true;
1110 } else {
1111 InsertUncondBranch(BBI.BB, TailBB, TII);
1112 BBI.HasFallThrough = false;
1116 RemoveExtraEdges(BBI);
1118 // Update block info.
1119 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1120 InvalidatePreds(BBI.BB);
1122 // FIXME: Must maintain LiveIns.
1123 return true;
1126 /// PredicateBlock - Predicate instructions from the start of the block to the
1127 /// specified end with the specified condition.
1128 void IfConverter::PredicateBlock(BBInfo &BBI,
1129 MachineBasicBlock::iterator E,
1130 SmallVectorImpl<MachineOperand> &Cond) {
1131 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1132 if (TII->isPredicated(I))
1133 continue;
1134 if (!TII->PredicateInstruction(I, Cond)) {
1135 #ifndef NDEBUG
1136 cerr << "Unable to predicate " << *I << "!\n";
1137 #endif
1138 llvm_unreachable(0);
1142 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1144 BBI.IsAnalyzed = false;
1145 BBI.NonPredSize = 0;
1147 NumIfConvBBs++;
1150 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1151 /// the destination block. Skip end of block branches if IgnoreBr is true.
1152 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1153 SmallVectorImpl<MachineOperand> &Cond,
1154 bool IgnoreBr) {
1155 MachineFunction &MF = *ToBBI.BB->getParent();
1157 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1158 E = FromBBI.BB->end(); I != E; ++I) {
1159 const TargetInstrDesc &TID = I->getDesc();
1160 bool isPredicated = TII->isPredicated(I);
1161 // Do not copy the end of the block branches.
1162 if (IgnoreBr && !isPredicated && TID.isBranch())
1163 break;
1165 MachineInstr *MI = MF.CloneMachineInstr(I);
1166 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1167 ToBBI.NonPredSize++;
1169 if (!isPredicated)
1170 if (!TII->PredicateInstruction(MI, Cond)) {
1171 #ifndef NDEBUG
1172 cerr << "Unable to predicate " << *I << "!\n";
1173 #endif
1174 llvm_unreachable(0);
1178 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1179 FromBBI.BB->succ_end());
1180 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1181 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1183 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1184 MachineBasicBlock *Succ = Succs[i];
1185 // Fallthrough edge can't be transferred.
1186 if (Succ == FallThrough)
1187 continue;
1188 ToBBI.BB->addSuccessor(Succ);
1191 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1192 std::back_inserter(ToBBI.Predicate));
1193 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1195 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1196 ToBBI.IsAnalyzed = false;
1198 NumDupBBs++;
1201 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1203 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1204 ToBBI.BB->splice(ToBBI.BB->end(),
1205 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1207 // Redirect all branches to FromBB to ToBB.
1208 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1209 FromBBI.BB->pred_end());
1210 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1211 MachineBasicBlock *Pred = Preds[i];
1212 if (Pred == ToBBI.BB)
1213 continue;
1214 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1217 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1218 FromBBI.BB->succ_end());
1219 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1220 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1222 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1223 MachineBasicBlock *Succ = Succs[i];
1224 // Fallthrough edge can't be transferred.
1225 if (Succ == FallThrough)
1226 continue;
1227 FromBBI.BB->removeSuccessor(Succ);
1228 ToBBI.BB->addSuccessor(Succ);
1231 // Now FromBBI always falls through to the next block!
1232 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1233 FromBBI.BB->addSuccessor(NBB);
1235 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1236 std::back_inserter(ToBBI.Predicate));
1237 FromBBI.Predicate.clear();
1239 ToBBI.NonPredSize += FromBBI.NonPredSize;
1240 FromBBI.NonPredSize = 0;
1242 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1243 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1244 ToBBI.IsAnalyzed = false;
1245 FromBBI.IsAnalyzed = false;