1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "simplifycfg"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Type.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/Statistic.h"
36 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
38 /// SafeToMergeTerminators - Return true if it is safe to merge these two
39 /// terminator instructions together.
41 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
42 if (SI1 == SI2) return false; // Can't merge with self!
44 // It is not safe to merge these two switch instructions if they have a common
45 // successor, and if that successor has a PHI node, and if *that* PHI node has
46 // conflicting incoming values from the two switch blocks.
47 BasicBlock *SI1BB = SI1->getParent();
48 BasicBlock *SI2BB = SI2->getParent();
49 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
51 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
52 if (SI1Succs.count(*I))
53 for (BasicBlock::iterator BBI = (*I)->begin();
54 isa<PHINode>(BBI); ++BBI) {
55 PHINode *PN = cast<PHINode>(BBI);
56 if (PN->getIncomingValueForBlock(SI1BB) !=
57 PN->getIncomingValueForBlock(SI2BB))
64 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
65 /// now be entries in it from the 'NewPred' block. The values that will be
66 /// flowing into the PHI nodes will be the same as those coming in from
67 /// ExistPred, an existing predecessor of Succ.
68 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
69 BasicBlock *ExistPred) {
70 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
71 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
72 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
75 for (BasicBlock::iterator I = Succ->begin();
76 (PN = dyn_cast<PHINode>(I)); ++I)
77 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
80 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
81 /// almost-empty BB ending in an unconditional branch to Succ, into succ.
83 /// Assumption: Succ is the single successor for BB.
85 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
86 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
88 DOUT << "Looking to fold " << BB->getNameStart() << " into "
89 << Succ->getNameStart() << "\n";
90 // Shortcut, if there is only a single predecessor it must be BB and merging
92 if (Succ->getSinglePredecessor()) return true;
94 typedef SmallPtrSet<Instruction*, 16> InstrSet;
97 // Make a list of all phi nodes in BB
98 BasicBlock::iterator BBI = BB->begin();
99 while (isa<PHINode>(*BBI)) BBPHIs.insert(BBI++);
101 // Make a list of the predecessors of BB
102 typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
103 BlockSet BBPreds(pred_begin(BB), pred_end(BB));
105 // Use that list to make another list of common predecessors of BB and Succ
106 BlockSet CommonPreds;
107 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
109 if (BBPreds.count(*PI))
110 CommonPreds.insert(*PI);
112 // Shortcut, if there are no common predecessors, merging is always safe
113 if (CommonPreds.empty())
116 // Look at all the phi nodes in Succ, to see if they present a conflict when
117 // merging these blocks
118 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
119 PHINode *PN = cast<PHINode>(I);
121 // If the incoming value from BB is again a PHINode in
122 // BB which has the same incoming value for *PI as PN does, we can
123 // merge the phi nodes and then the blocks can still be merged
124 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
125 if (BBPN && BBPN->getParent() == BB) {
126 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
128 if (BBPN->getIncomingValueForBlock(*PI)
129 != PN->getIncomingValueForBlock(*PI)) {
130 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
131 << Succ->getNameStart() << " is conflicting with "
132 << BBPN->getNameStart() << " with regard to common predecessor "
133 << (*PI)->getNameStart() << "\n";
137 // Remove this phinode from the list of phis in BB, since it has been
141 Value* Val = PN->getIncomingValueForBlock(BB);
142 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
144 // See if the incoming value for the common predecessor is equal to the
145 // one for BB, in which case this phi node will not prevent the merging
147 if (Val != PN->getIncomingValueForBlock(*PI)) {
148 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
149 << Succ->getNameStart() << " is conflicting with regard to common "
150 << "predecessor " << (*PI)->getNameStart() << "\n";
157 // If there are any other phi nodes in BB that don't have a phi node in Succ
158 // to merge with, they must be moved to Succ completely. However, for any
159 // predecessors of Succ, branches will be added to the phi node that just
160 // point to itself. So, for any common predecessors, this must not cause
162 for (InstrSet::iterator I = BBPHIs.begin(), E = BBPHIs.end();
164 PHINode *PN = cast<PHINode>(*I);
165 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
167 if (PN->getIncomingValueForBlock(*PI) != PN) {
168 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
169 << BB->getNameStart() << " is conflicting with regard to common "
170 << "predecessor " << (*PI)->getNameStart() << "\n";
178 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
179 /// branch to Succ, and contains no instructions other than PHI nodes and the
180 /// branch. If possible, eliminate BB.
181 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
183 // Check to see if merging these blocks would cause conflicts for any of the
184 // phi nodes in BB or Succ. If not, we can safely merge.
185 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
187 DOUT << "Killing Trivial BB: \n" << *BB;
189 if (isa<PHINode>(Succ->begin())) {
190 // If there is more than one pred of succ, and there are PHI nodes in
191 // the successor, then we need to add incoming edges for the PHI nodes
193 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
195 // Loop over all of the PHI nodes in the successor of BB.
196 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
197 PHINode *PN = cast<PHINode>(I);
198 Value *OldVal = PN->removeIncomingValue(BB, false);
199 assert(OldVal && "No entry in PHI for Pred BB!");
201 // If this incoming value is one of the PHI nodes in BB, the new entries
202 // in the PHI node are the entries from the old PHI.
203 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
204 PHINode *OldValPN = cast<PHINode>(OldVal);
205 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
206 // Note that, since we are merging phi nodes and BB and Succ might
207 // have common predecessors, we could end up with a phi node with
208 // identical incoming branches. This will be cleaned up later (and
209 // will trigger asserts if we try to clean it up now, without also
210 // simplifying the corresponding conditional branch).
211 PN->addIncoming(OldValPN->getIncomingValue(i),
212 OldValPN->getIncomingBlock(i));
214 // Add an incoming value for each of the new incoming values.
215 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
216 PN->addIncoming(OldVal, BBPreds[i]);
221 if (isa<PHINode>(&BB->front())) {
222 SmallVector<BasicBlock*, 16>
223 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
225 // Move all PHI nodes in BB to Succ if they are alive, otherwise
227 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
228 if (PN->use_empty()) {
229 // Just remove the dead phi. This happens if Succ's PHIs were the only
230 // users of the PHI nodes.
231 PN->eraseFromParent();
235 // The instruction is alive, so this means that BB must dominate all
236 // predecessors of Succ (Since all uses of the PN are after its
237 // definition, so in Succ or a block dominated by Succ. If a predecessor
238 // of Succ would not be dominated by BB, PN would violate the def before
239 // use SSA demand). Therefore, we can simply move the phi node to the
241 Succ->getInstList().splice(Succ->begin(),
242 BB->getInstList(), BB->begin());
244 // We need to add new entries for the PHI node to account for
245 // predecessors of Succ that the PHI node does not take into
246 // account. At this point, since we know that BB dominated succ and all
247 // of its predecessors, this means that we should any newly added
248 // incoming edges should use the PHI node itself as the value for these
249 // edges, because they are loop back edges.
250 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
251 if (OldSuccPreds[i] != BB)
252 PN->addIncoming(PN, OldSuccPreds[i]);
256 // Everything that jumped to BB now goes to Succ.
257 BB->replaceAllUsesWith(Succ);
258 if (!Succ->hasName()) Succ->takeName(BB);
259 BB->eraseFromParent(); // Delete the old basic block.
263 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
264 /// presumably PHI nodes in it), check to see if the merge at this block is due
265 /// to an "if condition". If so, return the boolean condition that determines
266 /// which entry into BB will be taken. Also, return by references the block
267 /// that will be entered from if the condition is true, and the block that will
268 /// be entered if the condition is false.
271 static Value *GetIfCondition(BasicBlock *BB,
272 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
273 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
274 "Function can only handle blocks with 2 predecessors!");
275 BasicBlock *Pred1 = *pred_begin(BB);
276 BasicBlock *Pred2 = *++pred_begin(BB);
278 // We can only handle branches. Other control flow will be lowered to
279 // branches if possible anyway.
280 if (!isa<BranchInst>(Pred1->getTerminator()) ||
281 !isa<BranchInst>(Pred2->getTerminator()))
283 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
284 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
286 // Eliminate code duplication by ensuring that Pred1Br is conditional if
288 if (Pred2Br->isConditional()) {
289 // If both branches are conditional, we don't have an "if statement". In
290 // reality, we could transform this case, but since the condition will be
291 // required anyway, we stand no chance of eliminating it, so the xform is
292 // probably not profitable.
293 if (Pred1Br->isConditional())
296 std::swap(Pred1, Pred2);
297 std::swap(Pred1Br, Pred2Br);
300 if (Pred1Br->isConditional()) {
301 // If we found a conditional branch predecessor, make sure that it branches
302 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
303 if (Pred1Br->getSuccessor(0) == BB &&
304 Pred1Br->getSuccessor(1) == Pred2) {
307 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
308 Pred1Br->getSuccessor(1) == BB) {
312 // We know that one arm of the conditional goes to BB, so the other must
313 // go somewhere unrelated, and this must not be an "if statement".
317 // The only thing we have to watch out for here is to make sure that Pred2
318 // doesn't have incoming edges from other blocks. If it does, the condition
319 // doesn't dominate BB.
320 if (++pred_begin(Pred2) != pred_end(Pred2))
323 return Pred1Br->getCondition();
326 // Ok, if we got here, both predecessors end with an unconditional branch to
327 // BB. Don't panic! If both blocks only have a single (identical)
328 // predecessor, and THAT is a conditional branch, then we're all ok!
329 if (pred_begin(Pred1) == pred_end(Pred1) ||
330 ++pred_begin(Pred1) != pred_end(Pred1) ||
331 pred_begin(Pred2) == pred_end(Pred2) ||
332 ++pred_begin(Pred2) != pred_end(Pred2) ||
333 *pred_begin(Pred1) != *pred_begin(Pred2))
336 // Otherwise, if this is a conditional branch, then we can use it!
337 BasicBlock *CommonPred = *pred_begin(Pred1);
338 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
339 assert(BI->isConditional() && "Two successors but not conditional?");
340 if (BI->getSuccessor(0) == Pred1) {
347 return BI->getCondition();
352 /// DominatesMergePoint - If we have a merge point of an "if condition" as
353 /// accepted above, return true if the specified value dominates the block. We
354 /// don't handle the true generality of domination here, just a special case
355 /// which works well enough for us.
357 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
358 /// see if V (which must be an instruction) is cheap to compute and is
359 /// non-trapping. If both are true, the instruction is inserted into the set
360 /// and true is returned.
361 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
362 std::set<Instruction*> *AggressiveInsts) {
363 Instruction *I = dyn_cast<Instruction>(V);
365 // Non-instructions all dominate instructions, but not all constantexprs
366 // can be executed unconditionally.
367 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
372 BasicBlock *PBB = I->getParent();
374 // We don't want to allow weird loops that might have the "if condition" in
375 // the bottom of this block.
376 if (PBB == BB) return false;
378 // If this instruction is defined in a block that contains an unconditional
379 // branch to BB, then it must be in the 'conditional' part of the "if
381 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
382 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
383 if (!AggressiveInsts) return false;
384 // Okay, it looks like the instruction IS in the "condition". Check to
385 // see if its a cheap instruction to unconditionally compute, and if it
386 // only uses stuff defined outside of the condition. If so, hoist it out.
387 switch (I->getOpcode()) {
388 default: return false; // Cannot hoist this out safely.
389 case Instruction::Load: {
390 // We can hoist loads that are non-volatile and obviously cannot trap.
391 if (cast<LoadInst>(I)->isVolatile())
393 // FIXME: A computation of a constant can trap!
394 if (!isa<AllocaInst>(I->getOperand(0)) &&
395 !isa<Constant>(I->getOperand(0)))
397 // External weak globals may have address 0, so we can't load them.
398 Value *V2 = I->getOperand(0)->getUnderlyingObject();
400 GlobalVariable* GV = dyn_cast<GlobalVariable>(V2);
401 if (GV && GV->hasExternalWeakLinkage())
404 // Finally, we have to check to make sure there are no instructions
405 // before the load in its basic block, as we are going to hoist the loop
406 // out to its predecessor.
407 BasicBlock::iterator IP = PBB->begin();
408 while (isa<DbgInfoIntrinsic>(IP))
410 if (IP != BasicBlock::iterator(I))
414 case Instruction::Add:
415 case Instruction::Sub:
416 case Instruction::And:
417 case Instruction::Or:
418 case Instruction::Xor:
419 case Instruction::Shl:
420 case Instruction::LShr:
421 case Instruction::AShr:
422 case Instruction::ICmp:
423 break; // These are all cheap and non-trapping instructions.
426 // Okay, we can only really hoist these out if their operands are not
427 // defined in the conditional region.
428 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
429 if (!DominatesMergePoint(*i, BB, 0))
431 // Okay, it's safe to do this! Remember this instruction.
432 AggressiveInsts->insert(I);
438 /// GatherConstantSetEQs - Given a potentially 'or'd together collection of
439 /// icmp_eq instructions that compare a value against a constant, return the
440 /// value being compared, and stick the constant into the Values vector.
441 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
442 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
443 if (Inst->getOpcode() == Instruction::ICmp &&
444 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
445 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
447 return Inst->getOperand(0);
448 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
450 return Inst->getOperand(1);
452 } else if (Inst->getOpcode() == Instruction::Or) {
453 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
454 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
462 /// GatherConstantSetNEs - Given a potentially 'and'd together collection of
463 /// setne instructions that compare a value against a constant, return the value
464 /// being compared, and stick the constant into the Values vector.
465 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
466 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
467 if (Inst->getOpcode() == Instruction::ICmp &&
468 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
469 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
471 return Inst->getOperand(0);
472 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
474 return Inst->getOperand(1);
476 } else if (Inst->getOpcode() == Instruction::And) {
477 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
478 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
486 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
487 /// bunch of comparisons of one value against constants, return the value and
488 /// the constants being compared.
489 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
490 std::vector<ConstantInt*> &Values) {
491 if (Cond->getOpcode() == Instruction::Or) {
492 CompVal = GatherConstantSetEQs(Cond, Values);
494 // Return true to indicate that the condition is true if the CompVal is
495 // equal to one of the constants.
497 } else if (Cond->getOpcode() == Instruction::And) {
498 CompVal = GatherConstantSetNEs(Cond, Values);
500 // Return false to indicate that the condition is false if the CompVal is
501 // equal to one of the constants.
507 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
508 Instruction* Cond = 0;
509 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
510 Cond = dyn_cast<Instruction>(SI->getCondition());
511 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
512 if (BI->isConditional())
513 Cond = dyn_cast<Instruction>(BI->getCondition());
516 TI->eraseFromParent();
517 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
520 /// isValueEqualityComparison - Return true if the specified terminator checks
521 /// to see if a value is equal to constant integer value.
522 static Value *isValueEqualityComparison(TerminatorInst *TI) {
523 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
524 // Do not permit merging of large switch instructions into their
525 // predecessors unless there is only one predecessor.
526 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
527 pred_end(SI->getParent())) > 128)
530 return SI->getCondition();
532 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
533 if (BI->isConditional() && BI->getCondition()->hasOneUse())
534 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
535 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
536 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
537 isa<ConstantInt>(ICI->getOperand(1)))
538 return ICI->getOperand(0);
542 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
543 /// decode all of the 'cases' that it represents and return the 'default' block.
545 GetValueEqualityComparisonCases(TerminatorInst *TI,
546 std::vector<std::pair<ConstantInt*,
547 BasicBlock*> > &Cases) {
548 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
549 Cases.reserve(SI->getNumCases());
550 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
551 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
552 return SI->getDefaultDest();
555 BranchInst *BI = cast<BranchInst>(TI);
556 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
557 Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
558 BI->getSuccessor(ICI->getPredicate() ==
559 ICmpInst::ICMP_NE)));
560 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
564 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
565 /// in the list that match the specified block.
566 static void EliminateBlockCases(BasicBlock *BB,
567 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
568 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
569 if (Cases[i].second == BB) {
570 Cases.erase(Cases.begin()+i);
575 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
578 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
579 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
580 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
582 // Make V1 be smaller than V2.
583 if (V1->size() > V2->size())
586 if (V1->size() == 0) return false;
587 if (V1->size() == 1) {
589 ConstantInt *TheVal = (*V1)[0].first;
590 for (unsigned i = 0, e = V2->size(); i != e; ++i)
591 if (TheVal == (*V2)[i].first)
595 // Otherwise, just sort both lists and compare element by element.
596 std::sort(V1->begin(), V1->end());
597 std::sort(V2->begin(), V2->end());
598 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
599 while (i1 != e1 && i2 != e2) {
600 if ((*V1)[i1].first == (*V2)[i2].first)
602 if ((*V1)[i1].first < (*V2)[i2].first)
610 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
611 /// terminator instruction and its block is known to only have a single
612 /// predecessor block, check to see if that predecessor is also a value
613 /// comparison with the same value, and if that comparison determines the
614 /// outcome of this comparison. If so, simplify TI. This does a very limited
615 /// form of jump threading.
616 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
618 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
619 if (!PredVal) return false; // Not a value comparison in predecessor.
621 Value *ThisVal = isValueEqualityComparison(TI);
622 assert(ThisVal && "This isn't a value comparison!!");
623 if (ThisVal != PredVal) return false; // Different predicates.
625 // Find out information about when control will move from Pred to TI's block.
626 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
627 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
629 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
631 // Find information about how control leaves this block.
632 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
633 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
634 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
636 // If TI's block is the default block from Pred's comparison, potentially
637 // simplify TI based on this knowledge.
638 if (PredDef == TI->getParent()) {
639 // If we are here, we know that the value is none of those cases listed in
640 // PredCases. If there are any cases in ThisCases that are in PredCases, we
642 if (ValuesOverlap(PredCases, ThisCases)) {
643 if (isa<BranchInst>(TI)) {
644 // Okay, one of the successors of this condbr is dead. Convert it to a
646 assert(ThisCases.size() == 1 && "Branch can only have one case!");
647 // Insert the new branch.
648 Instruction *NI = BranchInst::Create(ThisDef, TI);
650 // Remove PHI node entries for the dead edge.
651 ThisCases[0].second->removePredecessor(TI->getParent());
653 DOUT << "Threading pred instr: " << *Pred->getTerminator()
654 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
656 EraseTerminatorInstAndDCECond(TI);
660 SwitchInst *SI = cast<SwitchInst>(TI);
661 // Okay, TI has cases that are statically dead, prune them away.
662 SmallPtrSet<Constant*, 16> DeadCases;
663 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
664 DeadCases.insert(PredCases[i].first);
666 DOUT << "Threading pred instr: " << *Pred->getTerminator()
667 << "Through successor TI: " << *TI;
669 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
670 if (DeadCases.count(SI->getCaseValue(i))) {
671 SI->getSuccessor(i)->removePredecessor(TI->getParent());
675 DOUT << "Leaving: " << *TI << "\n";
681 // Otherwise, TI's block must correspond to some matched value. Find out
682 // which value (or set of values) this is.
683 ConstantInt *TIV = 0;
684 BasicBlock *TIBB = TI->getParent();
685 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
686 if (PredCases[i].second == TIBB) {
688 TIV = PredCases[i].first;
690 return false; // Cannot handle multiple values coming to this block.
692 assert(TIV && "No edge from pred to succ?");
694 // Okay, we found the one constant that our value can be if we get into TI's
695 // BB. Find out which successor will unconditionally be branched to.
696 BasicBlock *TheRealDest = 0;
697 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
698 if (ThisCases[i].first == TIV) {
699 TheRealDest = ThisCases[i].second;
703 // If not handled by any explicit cases, it is handled by the default case.
704 if (TheRealDest == 0) TheRealDest = ThisDef;
706 // Remove PHI node entries for dead edges.
707 BasicBlock *CheckEdge = TheRealDest;
708 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
709 if (*SI != CheckEdge)
710 (*SI)->removePredecessor(TIBB);
714 // Insert the new branch.
715 Instruction *NI = BranchInst::Create(TheRealDest, TI);
717 DOUT << "Threading pred instr: " << *Pred->getTerminator()
718 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
720 EraseTerminatorInstAndDCECond(TI);
727 /// ConstantIntOrdering - This class implements a stable ordering of constant
728 /// integers that does not depend on their address. This is important for
729 /// applications that sort ConstantInt's to ensure uniqueness.
730 struct ConstantIntOrdering {
731 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
732 return LHS->getValue().ult(RHS->getValue());
737 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
738 /// equality comparison instruction (either a switch or a branch on "X == c").
739 /// See if any of the predecessors of the terminator block are value comparisons
740 /// on the same value. If so, and if safe to do so, fold them together.
741 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
742 BasicBlock *BB = TI->getParent();
743 Value *CV = isValueEqualityComparison(TI); // CondVal
744 assert(CV && "Not a comparison?");
745 bool Changed = false;
747 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
748 while (!Preds.empty()) {
749 BasicBlock *Pred = Preds.pop_back_val();
751 // See if the predecessor is a comparison with the same value.
752 TerminatorInst *PTI = Pred->getTerminator();
753 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
755 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
756 // Figure out which 'cases' to copy from SI to PSI.
757 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
758 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
760 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
761 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
763 // Based on whether the default edge from PTI goes to BB or not, fill in
764 // PredCases and PredDefault with the new switch cases we would like to
766 SmallVector<BasicBlock*, 8> NewSuccessors;
768 if (PredDefault == BB) {
769 // If this is the default destination from PTI, only the edges in TI
770 // that don't occur in PTI, or that branch to BB will be activated.
771 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
772 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
773 if (PredCases[i].second != BB)
774 PTIHandled.insert(PredCases[i].first);
776 // The default destination is BB, we don't need explicit targets.
777 std::swap(PredCases[i], PredCases.back());
778 PredCases.pop_back();
782 // Reconstruct the new switch statement we will be building.
783 if (PredDefault != BBDefault) {
784 PredDefault->removePredecessor(Pred);
785 PredDefault = BBDefault;
786 NewSuccessors.push_back(BBDefault);
788 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
789 if (!PTIHandled.count(BBCases[i].first) &&
790 BBCases[i].second != BBDefault) {
791 PredCases.push_back(BBCases[i]);
792 NewSuccessors.push_back(BBCases[i].second);
796 // If this is not the default destination from PSI, only the edges
797 // in SI that occur in PSI with a destination of BB will be
799 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
800 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
801 if (PredCases[i].second == BB) {
802 PTIHandled.insert(PredCases[i].first);
803 std::swap(PredCases[i], PredCases.back());
804 PredCases.pop_back();
808 // Okay, now we know which constants were sent to BB from the
809 // predecessor. Figure out where they will all go now.
810 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
811 if (PTIHandled.count(BBCases[i].first)) {
812 // If this is one we are capable of getting...
813 PredCases.push_back(BBCases[i]);
814 NewSuccessors.push_back(BBCases[i].second);
815 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
818 // If there are any constants vectored to BB that TI doesn't handle,
819 // they must go to the default destination of TI.
820 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
822 E = PTIHandled.end(); I != E; ++I) {
823 PredCases.push_back(std::make_pair(*I, BBDefault));
824 NewSuccessors.push_back(BBDefault);
828 // Okay, at this point, we know which new successor Pred will get. Make
829 // sure we update the number of entries in the PHI nodes for these
831 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
832 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
834 // Now that the successors are updated, create the new Switch instruction.
835 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
836 PredCases.size(), PTI);
837 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
838 NewSI->addCase(PredCases[i].first, PredCases[i].second);
840 EraseTerminatorInstAndDCECond(PTI);
842 // Okay, last check. If BB is still a successor of PSI, then we must
843 // have an infinite loop case. If so, add an infinitely looping block
844 // to handle the case to preserve the behavior of the code.
845 BasicBlock *InfLoopBlock = 0;
846 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
847 if (NewSI->getSuccessor(i) == BB) {
848 if (InfLoopBlock == 0) {
849 // Insert it at the end of the function, because it's either code,
850 // or it won't matter if it's hot. :)
851 InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
852 BranchInst::Create(InfLoopBlock, InfLoopBlock);
854 NewSI->setSuccessor(i, InfLoopBlock);
863 // isSafeToHoistInvoke - If we would need to insert a select that uses the
864 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
865 // would need to do this), we can't hoist the invoke, as there is nowhere
866 // to put the select in this case.
867 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
868 Instruction *I1, Instruction *I2) {
869 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
871 for (BasicBlock::iterator BBI = SI->begin();
872 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
873 Value *BB1V = PN->getIncomingValueForBlock(BB1);
874 Value *BB2V = PN->getIncomingValueForBlock(BB2);
875 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
883 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
884 /// BB2, hoist any common code in the two blocks up into the branch block. The
885 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
886 static bool HoistThenElseCodeToIf(BranchInst *BI) {
887 // This does very trivial matching, with limited scanning, to find identical
888 // instructions in the two blocks. In particular, we don't want to get into
889 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
890 // such, we currently just scan for obviously identical instructions in an
892 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
893 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
895 BasicBlock::iterator BB1_Itr = BB1->begin();
896 BasicBlock::iterator BB2_Itr = BB2->begin();
898 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
899 while (isa<DbgInfoIntrinsic>(I1))
901 while (isa<DbgInfoIntrinsic>(I2))
903 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
904 !I1->isIdenticalTo(I2) ||
905 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
908 // If we get here, we can hoist at least one instruction.
909 BasicBlock *BIParent = BI->getParent();
912 // If we are hoisting the terminator instruction, don't move one (making a
913 // broken BB), instead clone it, and remove BI.
914 if (isa<TerminatorInst>(I1))
915 goto HoistTerminator;
917 // For a normal instruction, we just move one to right before the branch,
918 // then replace all uses of the other with the first. Finally, we remove
919 // the now redundant second instruction.
920 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
921 if (!I2->use_empty())
922 I2->replaceAllUsesWith(I1);
923 BB2->getInstList().erase(I2);
926 while (isa<DbgInfoIntrinsic>(I1))
929 while (isa<DbgInfoIntrinsic>(I2))
931 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
936 // It may not be possible to hoist an invoke.
937 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
940 // Okay, it is safe to hoist the terminator.
941 Instruction *NT = I1->clone(*BB1->getContext());
942 BIParent->getInstList().insert(BI, NT);
943 if (NT->getType() != Type::VoidTy) {
944 I1->replaceAllUsesWith(NT);
945 I2->replaceAllUsesWith(NT);
949 // Hoisting one of the terminators from our successor is a great thing.
950 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
951 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
952 // nodes, so we insert select instruction to compute the final result.
953 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
954 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
956 for (BasicBlock::iterator BBI = SI->begin();
957 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
958 Value *BB1V = PN->getIncomingValueForBlock(BB1);
959 Value *BB2V = PN->getIncomingValueForBlock(BB2);
961 // These values do not agree. Insert a select instruction before NT
962 // that determines the right value.
963 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
965 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
966 BB1V->getName()+"."+BB2V->getName(), NT);
967 // Make the PHI node use the select for all incoming values for BB1/BB2
968 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
969 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
970 PN->setIncomingValue(i, SI);
975 // Update any PHI nodes in our new successors.
976 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
977 AddPredecessorToBlock(*SI, BIParent, BB1);
979 EraseTerminatorInstAndDCECond(BI);
983 /// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
984 /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
985 /// (for now, restricted to a single instruction that's side effect free) from
986 /// the BB1 into the branch block to speculatively execute it.
987 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
988 // Only speculatively execution a single instruction (not counting the
989 // terminator) for now.
990 Instruction *HInst = NULL;
991 Instruction *Term = BB1->getTerminator();
992 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
994 Instruction *I = BBI;
996 if (isa<DbgInfoIntrinsic>(I)) continue;
997 if (I == Term) break;
1007 // Be conservative for now. FP select instruction can often be expensive.
1008 Value *BrCond = BI->getCondition();
1009 if (isa<Instruction>(BrCond) &&
1010 cast<Instruction>(BrCond)->getOpcode() == Instruction::FCmp)
1013 // If BB1 is actually on the false edge of the conditional branch, remember
1014 // to swap the select operands later.
1015 bool Invert = false;
1016 if (BB1 != BI->getSuccessor(0)) {
1017 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
1024 // br i1 %t1, label %BB1, label %BB2
1033 // %t3 = select i1 %t1, %t2, %t3
1034 switch (HInst->getOpcode()) {
1035 default: return false; // Not safe / profitable to hoist.
1036 case Instruction::Add:
1037 case Instruction::Sub:
1038 // Not worth doing for vector ops.
1039 if (isa<VectorType>(HInst->getType()))
1042 case Instruction::And:
1043 case Instruction::Or:
1044 case Instruction::Xor:
1045 case Instruction::Shl:
1046 case Instruction::LShr:
1047 case Instruction::AShr:
1048 // Don't mess with vector operations.
1049 if (isa<VectorType>(HInst->getType()))
1051 break; // These are all cheap and non-trapping instructions.
1054 // If the instruction is obviously dead, don't try to predicate it.
1055 if (HInst->use_empty()) {
1056 HInst->eraseFromParent();
1060 // Can we speculatively execute the instruction? And what is the value
1061 // if the condition is false? Consider the phi uses, if the incoming value
1062 // from the "if" block are all the same V, then V is the value of the
1063 // select if the condition is false.
1064 BasicBlock *BIParent = BI->getParent();
1065 SmallVector<PHINode*, 4> PHIUses;
1066 Value *FalseV = NULL;
1068 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
1069 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
1071 // Ignore any user that is not a PHI node in BB2. These can only occur in
1072 // unreachable blocks, because they would not be dominated by the instr.
1073 PHINode *PN = dyn_cast<PHINode>(UI);
1074 if (!PN || PN->getParent() != BB2)
1076 PHIUses.push_back(PN);
1078 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
1081 else if (FalseV != PHIV)
1082 return false; // Inconsistent value when condition is false.
1085 assert(FalseV && "Must have at least one user, and it must be a PHI");
1087 // Do not hoist the instruction if any of its operands are defined but not
1088 // used in this BB. The transformation will prevent the operand from
1089 // being sunk into the use block.
1090 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
1092 Instruction *OpI = dyn_cast<Instruction>(*i);
1093 if (OpI && OpI->getParent() == BIParent &&
1094 !OpI->isUsedInBasicBlock(BIParent))
1098 // If we get here, we can hoist the instruction. Try to place it
1099 // before the icmp instruction preceding the conditional branch.
1100 BasicBlock::iterator InsertPos = BI;
1101 if (InsertPos != BIParent->begin())
1103 // Skip debug info between condition and branch.
1104 while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
1106 if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
1107 SmallPtrSet<Instruction *, 4> BB1Insns;
1108 for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
1109 BB1I != BB1E; ++BB1I)
1110 BB1Insns.insert(BB1I);
1111 for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
1113 Instruction *Use = cast<Instruction>(*UI);
1114 if (BB1Insns.count(Use)) {
1115 // If BrCond uses the instruction that place it just before
1116 // branch instruction.
1123 BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
1125 // Create a select whose true value is the speculatively executed value and
1126 // false value is the previously determined FalseV.
1129 SI = SelectInst::Create(BrCond, FalseV, HInst,
1130 FalseV->getName() + "." + HInst->getName(), BI);
1132 SI = SelectInst::Create(BrCond, HInst, FalseV,
1133 HInst->getName() + "." + FalseV->getName(), BI);
1135 // Make the PHI node use the select for all incoming values for "then" and
1137 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1138 PHINode *PN = PHIUses[i];
1139 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
1140 if (PN->getIncomingBlock(j) == BB1 ||
1141 PN->getIncomingBlock(j) == BIParent)
1142 PN->setIncomingValue(j, SI);
1149 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1150 /// across this block.
1151 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1152 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1155 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1156 if (isa<DbgInfoIntrinsic>(BBI))
1158 if (Size > 10) return false; // Don't clone large BB's.
1161 // We can only support instructions that do not define values that are
1162 // live outside of the current basic block.
1163 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1165 Instruction *U = cast<Instruction>(*UI);
1166 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1169 // Looks ok, continue checking.
1175 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1176 /// that is defined in the same block as the branch and if any PHI entries are
1177 /// constants, thread edges corresponding to that entry to be branches to their
1178 /// ultimate destination.
1179 static bool FoldCondBranchOnPHI(BranchInst *BI) {
1180 BasicBlock *BB = BI->getParent();
1181 LLVMContext *Context = BB->getContext();
1182 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1183 // NOTE: we currently cannot transform this case if the PHI node is used
1184 // outside of the block.
1185 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1188 // Degenerate case of a single entry PHI.
1189 if (PN->getNumIncomingValues() == 1) {
1190 FoldSingleEntryPHINodes(PN->getParent());
1194 // Now we know that this block has multiple preds and two succs.
1195 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1197 // Okay, this is a simple enough basic block. See if any phi values are
1199 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1201 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
1202 CB->getType() == Type::Int1Ty) {
1203 // Okay, we now know that all edges from PredBB should be revectored to
1204 // branch to RealDest.
1205 BasicBlock *PredBB = PN->getIncomingBlock(i);
1206 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1208 if (RealDest == BB) continue; // Skip self loops.
1210 // The dest block might have PHI nodes, other predecessors and other
1211 // difficult cases. Instead of being smart about this, just insert a new
1212 // block that jumps to the destination block, effectively splitting
1213 // the edge we are about to create.
1214 BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge",
1215 RealDest->getParent(), RealDest);
1216 BranchInst::Create(RealDest, EdgeBB);
1218 for (BasicBlock::iterator BBI = RealDest->begin();
1219 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1220 Value *V = PN->getIncomingValueForBlock(BB);
1221 PN->addIncoming(V, EdgeBB);
1224 // BB may have instructions that are being threaded over. Clone these
1225 // instructions into EdgeBB. We know that there will be no uses of the
1226 // cloned instructions outside of EdgeBB.
1227 BasicBlock::iterator InsertPt = EdgeBB->begin();
1228 std::map<Value*, Value*> TranslateMap; // Track translated values.
1229 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1230 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1231 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1233 // Clone the instruction.
1234 Instruction *N = BBI->clone(*Context);
1235 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1237 // Update operands due to translation.
1238 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1240 std::map<Value*, Value*>::iterator PI =
1241 TranslateMap.find(*i);
1242 if (PI != TranslateMap.end())
1246 // Check for trivial simplification.
1247 if (Constant *C = ConstantFoldInstruction(N, Context)) {
1248 TranslateMap[BBI] = C;
1249 delete N; // Constant folded away, don't need actual inst
1251 // Insert the new instruction into its new home.
1252 EdgeBB->getInstList().insert(InsertPt, N);
1253 if (!BBI->use_empty())
1254 TranslateMap[BBI] = N;
1259 // Loop over all of the edges from PredBB to BB, changing them to branch
1260 // to EdgeBB instead.
1261 TerminatorInst *PredBBTI = PredBB->getTerminator();
1262 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1263 if (PredBBTI->getSuccessor(i) == BB) {
1264 BB->removePredecessor(PredBB);
1265 PredBBTI->setSuccessor(i, EdgeBB);
1268 // Recurse, simplifying any other constants.
1269 return FoldCondBranchOnPHI(BI) | true;
1276 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1277 /// PHI node, see if we can eliminate it.
1278 static bool FoldTwoEntryPHINode(PHINode *PN) {
1279 LLVMContext *Context = PN->getParent()->getContext();
1281 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1282 // statement", which has a very simple dominance structure. Basically, we
1283 // are trying to find the condition that is being branched on, which
1284 // subsequently causes this merge to happen. We really want control
1285 // dependence information for this check, but simplifycfg can't keep it up
1286 // to date, and this catches most of the cases we care about anyway.
1288 BasicBlock *BB = PN->getParent();
1289 BasicBlock *IfTrue, *IfFalse;
1290 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1291 if (!IfCond) return false;
1293 // Okay, we found that we can merge this two-entry phi node into a select.
1294 // Doing so would require us to fold *all* two entry phi nodes in this block.
1295 // At some point this becomes non-profitable (particularly if the target
1296 // doesn't support cmov's). Only do this transformation if there are two or
1297 // fewer PHI nodes in this block.
1298 unsigned NumPhis = 0;
1299 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1303 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1304 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
1306 // Loop over the PHI's seeing if we can promote them all to select
1307 // instructions. While we are at it, keep track of the instructions
1308 // that need to be moved to the dominating block.
1309 std::set<Instruction*> AggressiveInsts;
1311 BasicBlock::iterator AfterPHIIt = BB->begin();
1312 while (isa<PHINode>(AfterPHIIt)) {
1313 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1314 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1315 if (PN->getIncomingValue(0) != PN)
1316 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1318 PN->replaceAllUsesWith(Context->getUndef(PN->getType()));
1319 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1320 &AggressiveInsts) ||
1321 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1322 &AggressiveInsts)) {
1327 // If we all PHI nodes are promotable, check to make sure that all
1328 // instructions in the predecessor blocks can be promoted as well. If
1329 // not, we won't be able to get rid of the control flow, so it's not
1330 // worth promoting to select instructions.
1331 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1332 PN = cast<PHINode>(BB->begin());
1333 BasicBlock *Pred = PN->getIncomingBlock(0);
1334 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1336 DomBlock = *pred_begin(Pred);
1337 for (BasicBlock::iterator I = Pred->begin();
1338 !isa<TerminatorInst>(I); ++I)
1339 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1340 // This is not an aggressive instruction that we can promote.
1341 // Because of this, we won't be able to get rid of the control
1342 // flow, so the xform is not worth it.
1347 Pred = PN->getIncomingBlock(1);
1348 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1350 DomBlock = *pred_begin(Pred);
1351 for (BasicBlock::iterator I = Pred->begin();
1352 !isa<TerminatorInst>(I); ++I)
1353 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1354 // This is not an aggressive instruction that we can promote.
1355 // Because of this, we won't be able to get rid of the control
1356 // flow, so the xform is not worth it.
1361 // If we can still promote the PHI nodes after this gauntlet of tests,
1362 // do all of the PHI's now.
1364 // Move all 'aggressive' instructions, which are defined in the
1365 // conditional parts of the if's up to the dominating block.
1367 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1368 IfBlock1->getInstList(),
1370 IfBlock1->getTerminator());
1373 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1374 IfBlock2->getInstList(),
1376 IfBlock2->getTerminator());
1379 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1380 // Change the PHI node into a select instruction.
1382 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1384 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1386 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
1387 PN->replaceAllUsesWith(NV);
1390 BB->getInstList().erase(PN);
1395 /// isTerminatorFirstRelevantInsn - Return true if Term is very first
1396 /// instruction ignoring Phi nodes and dbg intrinsics.
1397 static bool isTerminatorFirstRelevantInsn(BasicBlock *BB, Instruction *Term) {
1398 BasicBlock::iterator BBI = Term;
1399 while (BBI != BB->begin()) {
1401 if (!isa<DbgInfoIntrinsic>(BBI))
1405 if (isa<PHINode>(BBI) || &*BBI == Term || isa<DbgInfoIntrinsic>(BBI))
1410 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1411 /// to two returning blocks, try to merge them together into one return,
1412 /// introducing a select if the return values disagree.
1413 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1414 assert(BI->isConditional() && "Must be a conditional branch");
1415 BasicBlock *TrueSucc = BI->getSuccessor(0);
1416 BasicBlock *FalseSucc = BI->getSuccessor(1);
1417 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1418 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1420 // Check to ensure both blocks are empty (just a return) or optionally empty
1421 // with PHI nodes. If there are other instructions, merging would cause extra
1422 // computation on one path or the other.
1423 if (!isTerminatorFirstRelevantInsn(TrueSucc, TrueRet))
1425 if (!isTerminatorFirstRelevantInsn(FalseSucc, FalseRet))
1428 // Okay, we found a branch that is going to two return nodes. If
1429 // there is no return value for this function, just change the
1430 // branch into a return.
1431 if (FalseRet->getNumOperands() == 0) {
1432 TrueSucc->removePredecessor(BI->getParent());
1433 FalseSucc->removePredecessor(BI->getParent());
1434 ReturnInst::Create(0, BI);
1435 EraseTerminatorInstAndDCECond(BI);
1439 // Otherwise, figure out what the true and false return values are
1440 // so we can insert a new select instruction.
1441 Value *TrueValue = TrueRet->getReturnValue();
1442 Value *FalseValue = FalseRet->getReturnValue();
1444 // Unwrap any PHI nodes in the return blocks.
1445 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1446 if (TVPN->getParent() == TrueSucc)
1447 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1448 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1449 if (FVPN->getParent() == FalseSucc)
1450 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1452 // In order for this transformation to be safe, we must be able to
1453 // unconditionally execute both operands to the return. This is
1454 // normally the case, but we could have a potentially-trapping
1455 // constant expression that prevents this transformation from being
1457 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1460 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1464 // Okay, we collected all the mapped values and checked them for sanity, and
1465 // defined to really do this transformation. First, update the CFG.
1466 TrueSucc->removePredecessor(BI->getParent());
1467 FalseSucc->removePredecessor(BI->getParent());
1469 // Insert select instructions where needed.
1470 Value *BrCond = BI->getCondition();
1472 // Insert a select if the results differ.
1473 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1474 } else if (isa<UndefValue>(TrueValue)) {
1475 TrueValue = FalseValue;
1477 TrueValue = SelectInst::Create(BrCond, TrueValue,
1478 FalseValue, "retval", BI);
1482 Value *RI = !TrueValue ?
1483 ReturnInst::Create(BI) :
1484 ReturnInst::Create(TrueValue, BI);
1486 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1487 << "\n " << *BI << "NewRet = " << *RI
1488 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1490 EraseTerminatorInstAndDCECond(BI);
1495 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1496 /// and if a predecessor branches to us and one of our successors, fold the
1497 /// setcc into the predecessor and use logical operations to pick the right
1499 bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
1500 BasicBlock *BB = BI->getParent();
1501 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1502 if (Cond == 0) return false;
1505 // Only allow this if the condition is a simple instruction that can be
1506 // executed unconditionally. It must be in the same block as the branch, and
1507 // must be at the front of the block.
1508 BasicBlock::iterator FrontIt = BB->front();
1509 // Ignore dbg intrinsics.
1510 while(isa<DbgInfoIntrinsic>(FrontIt))
1512 if ((!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1513 Cond->getParent() != BB || &*FrontIt != Cond || !Cond->hasOneUse()) {
1517 // Make sure the instruction after the condition is the cond branch.
1518 BasicBlock::iterator CondIt = Cond; ++CondIt;
1519 // Ingore dbg intrinsics.
1520 while(isa<DbgInfoIntrinsic>(CondIt))
1522 if (&*CondIt != BI) {
1523 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
1527 // Cond is known to be a compare or binary operator. Check to make sure that
1528 // neither operand is a potentially-trapping constant expression.
1529 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1537 // Finally, don't infinitely unroll conditional loops.
1538 BasicBlock *TrueDest = BI->getSuccessor(0);
1539 BasicBlock *FalseDest = BI->getSuccessor(1);
1540 if (TrueDest == BB || FalseDest == BB)
1543 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1544 BasicBlock *PredBlock = *PI;
1545 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
1547 // Check that we have two conditional branches. If there is a PHI node in
1548 // the common successor, verify that the same value flows in from both
1550 if (PBI == 0 || PBI->isUnconditional() ||
1551 !SafeToMergeTerminators(BI, PBI))
1554 Instruction::BinaryOps Opc;
1555 bool InvertPredCond = false;
1557 if (PBI->getSuccessor(0) == TrueDest)
1558 Opc = Instruction::Or;
1559 else if (PBI->getSuccessor(1) == FalseDest)
1560 Opc = Instruction::And;
1561 else if (PBI->getSuccessor(0) == FalseDest)
1562 Opc = Instruction::And, InvertPredCond = true;
1563 else if (PBI->getSuccessor(1) == TrueDest)
1564 Opc = Instruction::Or, InvertPredCond = true;
1568 DOUT << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB;
1570 // If we need to invert the condition in the pred block to match, do so now.
1571 if (InvertPredCond) {
1573 BinaryOperator::CreateNot(PBI->getCondition(),
1574 PBI->getCondition()->getName()+".not", PBI);
1575 PBI->setCondition(NewCond);
1576 BasicBlock *OldTrue = PBI->getSuccessor(0);
1577 BasicBlock *OldFalse = PBI->getSuccessor(1);
1578 PBI->setSuccessor(0, OldFalse);
1579 PBI->setSuccessor(1, OldTrue);
1582 // Clone Cond into the predecessor basic block, and or/and the
1583 // two conditions together.
1584 Instruction *New = Cond->clone(*BB->getContext());
1585 PredBlock->getInstList().insert(PBI, New);
1586 New->takeName(Cond);
1587 Cond->setName(New->getName()+".old");
1589 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1590 New, "or.cond", PBI);
1591 PBI->setCondition(NewCond);
1592 if (PBI->getSuccessor(0) == BB) {
1593 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1594 PBI->setSuccessor(0, TrueDest);
1596 if (PBI->getSuccessor(1) == BB) {
1597 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1598 PBI->setSuccessor(1, FalseDest);
1605 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1606 /// predecessor of another block, this function tries to simplify it. We know
1607 /// that PBI and BI are both conditional branches, and BI is in one of the
1608 /// successor blocks of PBI - PBI branches to BI.
1609 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1610 assert(PBI->isConditional() && BI->isConditional());
1611 BasicBlock *BB = BI->getParent();
1612 LLVMContext *Context = BB->getContext();
1614 // If this block ends with a branch instruction, and if there is a
1615 // predecessor that ends on a branch of the same condition, make
1616 // this conditional branch redundant.
1617 if (PBI->getCondition() == BI->getCondition() &&
1618 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1619 // Okay, the outcome of this conditional branch is statically
1620 // knowable. If this block had a single pred, handle specially.
1621 if (BB->getSinglePredecessor()) {
1622 // Turn this into a branch on constant.
1623 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1624 BI->setCondition(Context->getConstantInt(Type::Int1Ty, CondIsTrue));
1625 return true; // Nuke the branch on constant.
1628 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1629 // in the constant and simplify the block result. Subsequent passes of
1630 // simplifycfg will thread the block.
1631 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1632 PHINode *NewPN = PHINode::Create(Type::Int1Ty,
1633 BI->getCondition()->getName() + ".pr",
1635 // Okay, we're going to insert the PHI node. Since PBI is not the only
1636 // predecessor, compute the PHI'd conditional value for all of the preds.
1637 // Any predecessor where the condition is not computable we keep symbolic.
1638 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1639 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1640 PBI != BI && PBI->isConditional() &&
1641 PBI->getCondition() == BI->getCondition() &&
1642 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1643 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1644 NewPN->addIncoming(Context->getConstantInt(Type::Int1Ty,
1647 NewPN->addIncoming(BI->getCondition(), *PI);
1650 BI->setCondition(NewPN);
1655 // If this is a conditional branch in an empty block, and if any
1656 // predecessors is a conditional branch to one of our destinations,
1657 // fold the conditions into logical ops and one cond br.
1658 BasicBlock::iterator BBI = BB->begin();
1659 // Ignore dbg intrinsics.
1660 while (isa<DbgInfoIntrinsic>(BBI))
1666 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1671 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1673 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1674 PBIOp = 0, BIOp = 1;
1675 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1676 PBIOp = 1, BIOp = 0;
1677 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1682 // Check to make sure that the other destination of this branch
1683 // isn't BB itself. If so, this is an infinite loop that will
1684 // keep getting unwound.
1685 if (PBI->getSuccessor(PBIOp) == BB)
1688 // Do not perform this transformation if it would require
1689 // insertion of a large number of select instructions. For targets
1690 // without predication/cmovs, this is a big pessimization.
1691 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1693 unsigned NumPhis = 0;
1694 for (BasicBlock::iterator II = CommonDest->begin();
1695 isa<PHINode>(II); ++II, ++NumPhis)
1696 if (NumPhis > 2) // Disable this xform.
1699 // Finally, if everything is ok, fold the branches to logical ops.
1700 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1702 DOUT << "FOLDING BRs:" << *PBI->getParent()
1703 << "AND: " << *BI->getParent();
1706 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1707 // branch in it, where one edge (OtherDest) goes back to itself but the other
1708 // exits. We don't *know* that the program avoids the infinite loop
1709 // (even though that seems likely). If we do this xform naively, we'll end up
1710 // recursively unpeeling the loop. Since we know that (after the xform is
1711 // done) that the block *is* infinite if reached, we just make it an obviously
1712 // infinite loop with no cond branch.
1713 if (OtherDest == BB) {
1714 // Insert it at the end of the function, because it's either code,
1715 // or it won't matter if it's hot. :)
1716 BasicBlock *InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
1717 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1718 OtherDest = InfLoopBlock;
1721 DOUT << *PBI->getParent()->getParent();
1723 // BI may have other predecessors. Because of this, we leave
1724 // it alone, but modify PBI.
1726 // Make sure we get to CommonDest on True&True directions.
1727 Value *PBICond = PBI->getCondition();
1729 PBICond = BinaryOperator::CreateNot(PBICond,
1730 PBICond->getName()+".not",
1732 Value *BICond = BI->getCondition();
1734 BICond = BinaryOperator::CreateNot(BICond,
1735 BICond->getName()+".not",
1737 // Merge the conditions.
1738 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1740 // Modify PBI to branch on the new condition to the new dests.
1741 PBI->setCondition(Cond);
1742 PBI->setSuccessor(0, CommonDest);
1743 PBI->setSuccessor(1, OtherDest);
1745 // OtherDest may have phi nodes. If so, add an entry from PBI's
1746 // block that are identical to the entries for BI's block.
1748 for (BasicBlock::iterator II = OtherDest->begin();
1749 (PN = dyn_cast<PHINode>(II)); ++II) {
1750 Value *V = PN->getIncomingValueForBlock(BB);
1751 PN->addIncoming(V, PBI->getParent());
1754 // We know that the CommonDest already had an edge from PBI to
1755 // it. If it has PHIs though, the PHIs may have different
1756 // entries for BB and PBI's BB. If so, insert a select to make
1758 for (BasicBlock::iterator II = CommonDest->begin();
1759 (PN = dyn_cast<PHINode>(II)); ++II) {
1760 Value *BIV = PN->getIncomingValueForBlock(BB);
1761 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1762 Value *PBIV = PN->getIncomingValue(PBBIdx);
1764 // Insert a select in PBI to pick the right value.
1765 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1766 PBIV->getName()+".mux", PBI);
1767 PN->setIncomingValue(PBBIdx, NV);
1771 DOUT << "INTO: " << *PBI->getParent();
1773 DOUT << *PBI->getParent()->getParent();
1775 // This basic block is probably dead. We know it has at least
1776 // one fewer predecessor.
1781 /// SimplifyCFG - This function is used to do simplification of a CFG. For
1782 /// example, it adjusts branches to branches to eliminate the extra hop, it
1783 /// eliminates unreachable basic blocks, and does other "peephole" optimization
1784 /// of the CFG. It returns true if a modification was made.
1786 /// WARNING: The entry node of a function may not be simplified.
1788 bool llvm::SimplifyCFG(BasicBlock *BB) {
1789 bool Changed = false;
1790 Function *M = BB->getParent();
1792 assert(BB && BB->getParent() && "Block not embedded in function!");
1793 assert(BB->getTerminator() && "Degenerate basic block encountered!");
1794 assert(&BB->getParent()->getEntryBlock() != BB &&
1795 "Can't Simplify entry block!");
1797 // Remove basic blocks that have no predecessors... or that just have themself
1798 // as a predecessor. These are unreachable.
1799 if (pred_begin(BB) == pred_end(BB) || BB->getSinglePredecessor() == BB) {
1800 DOUT << "Removing BB: \n" << *BB;
1801 DeleteDeadBlock(BB);
1805 // Check to see if we can constant propagate this terminator instruction
1807 Changed |= ConstantFoldTerminator(BB);
1809 // If there is a trivial two-entry PHI node in this basic block, and we can
1810 // eliminate it, do so now.
1811 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1812 if (PN->getNumIncomingValues() == 2)
1813 Changed |= FoldTwoEntryPHINode(PN);
1815 // If this is a returning block with only PHI nodes in it, fold the return
1816 // instruction into any unconditional branch predecessors.
1818 // If any predecessor is a conditional branch that just selects among
1819 // different return values, fold the replace the branch/return with a select
1821 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1822 if (isTerminatorFirstRelevantInsn(BB, BB->getTerminator())) {
1823 // Find predecessors that end with branches.
1824 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1825 SmallVector<BranchInst*, 8> CondBranchPreds;
1826 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1827 TerminatorInst *PTI = (*PI)->getTerminator();
1828 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
1829 if (BI->isUnconditional())
1830 UncondBranchPreds.push_back(*PI);
1832 CondBranchPreds.push_back(BI);
1836 // If we found some, do the transformation!
1837 if (!UncondBranchPreds.empty()) {
1838 while (!UncondBranchPreds.empty()) {
1839 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
1840 DOUT << "FOLDING: " << *BB
1841 << "INTO UNCOND BRANCH PRED: " << *Pred;
1842 Instruction *UncondBranch = Pred->getTerminator();
1843 // Clone the return and add it to the end of the predecessor.
1844 Instruction *NewRet = RI->clone(*BB->getContext());
1845 Pred->getInstList().push_back(NewRet);
1847 BasicBlock::iterator BBI = RI;
1848 if (BBI != BB->begin()) {
1849 // Move region end info into the predecessor.
1850 if (DbgRegionEndInst *DREI = dyn_cast<DbgRegionEndInst>(--BBI))
1851 DREI->moveBefore(NewRet);
1854 // If the return instruction returns a value, and if the value was a
1855 // PHI node in "BB", propagate the right value into the return.
1856 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
1858 if (PHINode *PN = dyn_cast<PHINode>(*i))
1859 if (PN->getParent() == BB)
1860 *i = PN->getIncomingValueForBlock(Pred);
1862 // Update any PHI nodes in the returning block to realize that we no
1863 // longer branch to them.
1864 BB->removePredecessor(Pred);
1865 Pred->getInstList().erase(UncondBranch);
1868 // If we eliminated all predecessors of the block, delete the block now.
1869 if (pred_begin(BB) == pred_end(BB))
1870 // We know there are no successors, so just nuke the block.
1871 M->getBasicBlockList().erase(BB);
1876 // Check out all of the conditional branches going to this return
1877 // instruction. If any of them just select between returns, change the
1878 // branch itself into a select/return pair.
1879 while (!CondBranchPreds.empty()) {
1880 BranchInst *BI = CondBranchPreds.pop_back_val();
1882 // Check to see if the non-BB successor is also a return block.
1883 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
1884 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
1885 SimplifyCondBranchToTwoReturns(BI))
1889 } else if (isa<UnwindInst>(BB->begin())) {
1890 // Check to see if the first instruction in this block is just an unwind.
1891 // If so, replace any invoke instructions which use this as an exception
1892 // destination with call instructions, and any unconditional branch
1893 // predecessor with an unwind.
1895 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
1896 while (!Preds.empty()) {
1897 BasicBlock *Pred = Preds.back();
1898 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1899 if (BI->isUnconditional()) {
1900 Pred->getInstList().pop_back(); // nuke uncond branch
1901 new UnwindInst(Pred); // Use unwind.
1904 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
1905 if (II->getUnwindDest() == BB) {
1906 // Insert a new branch instruction before the invoke, because this
1907 // is now a fall through...
1908 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
1909 Pred->getInstList().remove(II); // Take out of symbol table
1911 // Insert the call now...
1912 SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
1913 CallInst *CI = CallInst::Create(II->getCalledValue(),
1914 Args.begin(), Args.end(),
1916 CI->setCallingConv(II->getCallingConv());
1917 CI->setAttributes(II->getAttributes());
1918 // If the invoke produced a value, the Call now does instead
1919 II->replaceAllUsesWith(CI);
1927 // If this block is now dead, remove it.
1928 if (pred_begin(BB) == pred_end(BB)) {
1929 // We know there are no successors, so just nuke the block.
1930 M->getBasicBlockList().erase(BB);
1934 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1935 if (isValueEqualityComparison(SI)) {
1936 // If we only have one predecessor, and if it is a branch on this value,
1937 // see if that predecessor totally determines the outcome of this switch.
1938 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1939 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1940 return SimplifyCFG(BB) || 1;
1942 // If the block only contains the switch, see if we can fold the block
1943 // away into any preds.
1944 BasicBlock::iterator BBI = BB->begin();
1945 // Ignore dbg intrinsics.
1946 while (isa<DbgInfoIntrinsic>(BBI))
1949 if (FoldValueComparisonIntoPredecessors(SI))
1950 return SimplifyCFG(BB) || 1;
1952 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1953 if (BI->isUnconditional()) {
1954 BasicBlock::iterator BBI = BB->getFirstNonPHI();
1956 BasicBlock *Succ = BI->getSuccessor(0);
1957 // Ignore dbg intrinsics.
1958 while (isa<DbgInfoIntrinsic>(BBI))
1960 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1961 Succ != BB) // Don't hurt infinite loops!
1962 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1965 } else { // Conditional branch
1966 if (isValueEqualityComparison(BI)) {
1967 // If we only have one predecessor, and if it is a branch on this value,
1968 // see if that predecessor totally determines the outcome of this
1970 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1971 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1972 return SimplifyCFG(BB) || 1;
1974 // This block must be empty, except for the setcond inst, if it exists.
1975 // Ignore dbg intrinsics.
1976 BasicBlock::iterator I = BB->begin();
1977 // Ignore dbg intrinsics.
1978 while (isa<DbgInfoIntrinsic>(I))
1981 if (FoldValueComparisonIntoPredecessors(BI))
1982 return SimplifyCFG(BB) | true;
1983 } else if (&*I == cast<Instruction>(BI->getCondition())){
1985 // Ignore dbg intrinsics.
1986 while (isa<DbgInfoIntrinsic>(I))
1989 if (FoldValueComparisonIntoPredecessors(BI))
1990 return SimplifyCFG(BB) | true;
1995 // If this is a branch on a phi node in the current block, thread control
1996 // through this block if any PHI node entries are constants.
1997 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1998 if (PN->getParent() == BI->getParent())
1999 if (FoldCondBranchOnPHI(BI))
2000 return SimplifyCFG(BB) | true;
2002 // If this basic block is ONLY a setcc and a branch, and if a predecessor
2003 // branches to us and one of our successors, fold the setcc into the
2004 // predecessor and use logical operations to pick the right destination.
2005 if (FoldBranchToCommonDest(BI))
2006 return SimplifyCFG(BB) | 1;
2009 // Scan predecessor blocks for conditional branches.
2010 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2011 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2012 if (PBI != BI && PBI->isConditional())
2013 if (SimplifyCondBranchToCondBranch(PBI, BI))
2014 return SimplifyCFG(BB) | true;
2016 } else if (isa<UnreachableInst>(BB->getTerminator())) {
2017 // If there are any instructions immediately before the unreachable that can
2018 // be removed, do so.
2019 Instruction *Unreachable = BB->getTerminator();
2020 while (Unreachable != BB->begin()) {
2021 BasicBlock::iterator BBI = Unreachable;
2023 // Do not delete instructions that can have side effects, like calls
2024 // (which may never return) and volatile loads and stores.
2025 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2027 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2028 if (SI->isVolatile())
2031 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2032 if (LI->isVolatile())
2035 // Delete this instruction
2036 BB->getInstList().erase(BBI);
2040 // If the unreachable instruction is the first in the block, take a gander
2041 // at all of the predecessors of this instruction, and simplify them.
2042 if (&BB->front() == Unreachable) {
2043 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2044 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2045 TerminatorInst *TI = Preds[i]->getTerminator();
2047 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2048 if (BI->isUnconditional()) {
2049 if (BI->getSuccessor(0) == BB) {
2050 new UnreachableInst(TI);
2051 TI->eraseFromParent();
2055 if (BI->getSuccessor(0) == BB) {
2056 BranchInst::Create(BI->getSuccessor(1), BI);
2057 EraseTerminatorInstAndDCECond(BI);
2058 } else if (BI->getSuccessor(1) == BB) {
2059 BranchInst::Create(BI->getSuccessor(0), BI);
2060 EraseTerminatorInstAndDCECond(BI);
2064 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2065 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2066 if (SI->getSuccessor(i) == BB) {
2067 BB->removePredecessor(SI->getParent());
2072 // If the default value is unreachable, figure out the most popular
2073 // destination and make it the default.
2074 if (SI->getSuccessor(0) == BB) {
2075 std::map<BasicBlock*, unsigned> Popularity;
2076 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2077 Popularity[SI->getSuccessor(i)]++;
2079 // Find the most popular block.
2080 unsigned MaxPop = 0;
2081 BasicBlock *MaxBlock = 0;
2082 for (std::map<BasicBlock*, unsigned>::iterator
2083 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2084 if (I->second > MaxPop) {
2086 MaxBlock = I->first;
2090 // Make this the new default, allowing us to delete any explicit
2092 SI->setSuccessor(0, MaxBlock);
2095 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2097 if (isa<PHINode>(MaxBlock->begin()))
2098 for (unsigned i = 0; i != MaxPop-1; ++i)
2099 MaxBlock->removePredecessor(SI->getParent());
2101 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2102 if (SI->getSuccessor(i) == MaxBlock) {
2108 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2109 if (II->getUnwindDest() == BB) {
2110 // Convert the invoke to a call instruction. This would be a good
2111 // place to note that the call does not throw though.
2112 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2113 II->removeFromParent(); // Take out of symbol table
2115 // Insert the call now...
2116 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
2117 CallInst *CI = CallInst::Create(II->getCalledValue(),
2118 Args.begin(), Args.end(),
2120 CI->setCallingConv(II->getCallingConv());
2121 CI->setAttributes(II->getAttributes());
2122 // If the invoke produced a value, the Call does now instead.
2123 II->replaceAllUsesWith(CI);
2130 // If this block is now dead, remove it.
2131 if (pred_begin(BB) == pred_end(BB)) {
2132 // We know there are no successors, so just nuke the block.
2133 M->getBasicBlockList().erase(BB);
2139 // Merge basic blocks into their predecessor if there is only one distinct
2140 // pred, and if there is only one distinct successor of the predecessor, and
2141 // if there are no PHI nodes.
2143 if (MergeBlockIntoPredecessor(BB))
2146 // Otherwise, if this block only has a single predecessor, and if that block
2147 // is a conditional branch, see if we can hoist any code from this block up
2148 // into our predecessor.
2149 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
2150 BasicBlock *OnlyPred = *PI++;
2151 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
2152 if (*PI != OnlyPred) {
2153 OnlyPred = 0; // There are multiple different predecessors...
2158 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
2159 if (BI->isConditional()) {
2160 // Get the other block.
2161 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
2162 PI = pred_begin(OtherBB);
2165 if (PI == pred_end(OtherBB)) {
2166 // We have a conditional branch to two blocks that are only reachable
2167 // from the condbr. We know that the condbr dominates the two blocks,
2168 // so see if there is any identical code in the "then" and "else"
2169 // blocks. If so, we can hoist it up to the branching block.
2170 Changed |= HoistThenElseCodeToIf(BI);
2172 BasicBlock* OnlySucc = NULL;
2173 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
2177 else if (*SI != OnlySucc) {
2178 OnlySucc = 0; // There are multiple distinct successors!
2183 if (OnlySucc == OtherBB) {
2184 // If BB's only successor is the other successor of the predecessor,
2185 // i.e. a triangle, see if we can hoist any code from this block up
2186 // to the "if" block.
2187 Changed |= SpeculativelyExecuteBB(BI, BB);
2192 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2193 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2194 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2195 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
2196 Instruction *Cond = cast<Instruction>(BI->getCondition());
2197 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2198 // 'setne's and'ed together, collect them.
2200 std::vector<ConstantInt*> Values;
2201 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
2202 if (CompVal && CompVal->getType()->isInteger()) {
2203 // There might be duplicate constants in the list, which the switch
2204 // instruction can't handle, remove them now.
2205 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
2206 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2208 // Figure out which block is which destination.
2209 BasicBlock *DefaultBB = BI->getSuccessor(1);
2210 BasicBlock *EdgeBB = BI->getSuccessor(0);
2211 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2213 // Create the new switch instruction now.
2214 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,
2217 // Add all of the 'cases' to the switch instruction.
2218 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2219 New->addCase(Values[i], EdgeBB);
2221 // We added edges from PI to the EdgeBB. As such, if there were any
2222 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2223 // the number of edges added.
2224 for (BasicBlock::iterator BBI = EdgeBB->begin();
2225 isa<PHINode>(BBI); ++BBI) {
2226 PHINode *PN = cast<PHINode>(BBI);
2227 Value *InVal = PN->getIncomingValueForBlock(*PI);
2228 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2229 PN->addIncoming(InVal, *PI);
2232 // Erase the old branch instruction.
2233 EraseTerminatorInstAndDCECond(BI);