1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Type.h"
19 #include "llvm/Support/CFG.h"
20 #include "llvm/Support/Debug.h"
27 // PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
28 // predecessors from "BB". This is a little tricky because "Succ" has PHI
29 // nodes, which need to have extra slots added to them to hold the merge edges
30 // from BB's predecessors, and BB itself might have had PHI nodes in it. This
31 // function returns true (failure) if the Succ BB already has a predecessor that
32 // is a predecessor of BB and incoming PHI arguments would not be discernible.
34 // Assumption: Succ is the single successor for BB.
36 static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
37 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
39 if (!isa<PHINode>(Succ->front()))
40 return false; // We can make the transformation, no problem.
42 // If there is more than one predecessor, and there are PHI nodes in
43 // the successor, then we need to add incoming edges for the PHI nodes
45 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
47 // Check to see if one of the predecessors of BB is already a predecessor of
48 // Succ. If so, we cannot do the transformation if there are any PHI nodes
49 // with incompatible values coming in from the two edges!
51 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
52 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
53 // Loop over all of the PHI nodes checking to see if there are
54 // incompatible values coming in.
55 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
56 PHINode *PN = cast<PHINode>(I);
57 // Loop up the entries in the PHI node for BB and for *PI if the values
58 // coming in are non-equal, we cannot merge these two blocks (instead we
59 // should insert a conditional move or something, then merge the
61 int Idx1 = PN->getBasicBlockIndex(BB);
62 int Idx2 = PN->getBasicBlockIndex(*PI);
63 assert(Idx1 != -1 && Idx2 != -1 &&
64 "Didn't have entries for my predecessors??");
65 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
66 return true; // Values are not equal...
70 // Loop over all of the PHI nodes in the successor BB.
71 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
72 PHINode *PN = cast<PHINode>(I);
73 Value *OldVal = PN->removeIncomingValue(BB, false);
74 assert(OldVal && "No entry in PHI for Pred BB!");
76 // If this incoming value is one of the PHI nodes in BB, the new entries in
77 // the PHI node are the entries from the old PHI.
78 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
79 PHINode *OldValPN = cast<PHINode>(OldVal);
80 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
81 PN->addIncoming(OldValPN->getIncomingValue(i),
82 OldValPN->getIncomingBlock(i));
84 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
85 End = BBPreds.end(); PredI != End; ++PredI) {
86 // Add an incoming value for each of the new incoming values...
87 PN->addIncoming(OldVal, *PredI);
94 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
95 /// presumably PHI nodes in it), check to see if the merge at this block is due
96 /// to an "if condition". If so, return the boolean condition that determines
97 /// which entry into BB will be taken. Also, return by references the block
98 /// that will be entered from if the condition is true, and the block that will
99 /// be entered if the condition is false.
102 static Value *GetIfCondition(BasicBlock *BB,
103 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
104 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
105 "Function can only handle blocks with 2 predecessors!");
106 BasicBlock *Pred1 = *pred_begin(BB);
107 BasicBlock *Pred2 = *++pred_begin(BB);
109 // We can only handle branches. Other control flow will be lowered to
110 // branches if possible anyway.
111 if (!isa<BranchInst>(Pred1->getTerminator()) ||
112 !isa<BranchInst>(Pred2->getTerminator()))
114 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
115 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
117 // Eliminate code duplication by ensuring that Pred1Br is conditional if
119 if (Pred2Br->isConditional()) {
120 // If both branches are conditional, we don't have an "if statement". In
121 // reality, we could transform this case, but since the condition will be
122 // required anyway, we stand no chance of eliminating it, so the xform is
123 // probably not profitable.
124 if (Pred1Br->isConditional())
127 std::swap(Pred1, Pred2);
128 std::swap(Pred1Br, Pred2Br);
131 if (Pred1Br->isConditional()) {
132 // If we found a conditional branch predecessor, make sure that it branches
133 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
134 if (Pred1Br->getSuccessor(0) == BB &&
135 Pred1Br->getSuccessor(1) == Pred2) {
138 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
139 Pred1Br->getSuccessor(1) == BB) {
143 // We know that one arm of the conditional goes to BB, so the other must
144 // go somewhere unrelated, and this must not be an "if statement".
148 // The only thing we have to watch out for here is to make sure that Pred2
149 // doesn't have incoming edges from other blocks. If it does, the condition
150 // doesn't dominate BB.
151 if (++pred_begin(Pred2) != pred_end(Pred2))
154 return Pred1Br->getCondition();
157 // Ok, if we got here, both predecessors end with an unconditional branch to
158 // BB. Don't panic! If both blocks only have a single (identical)
159 // predecessor, and THAT is a conditional branch, then we're all ok!
160 if (pred_begin(Pred1) == pred_end(Pred1) ||
161 ++pred_begin(Pred1) != pred_end(Pred1) ||
162 pred_begin(Pred2) == pred_end(Pred2) ||
163 ++pred_begin(Pred2) != pred_end(Pred2) ||
164 *pred_begin(Pred1) != *pred_begin(Pred2))
167 // Otherwise, if this is a conditional branch, then we can use it!
168 BasicBlock *CommonPred = *pred_begin(Pred1);
169 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
170 assert(BI->isConditional() && "Two successors but not conditional?");
171 if (BI->getSuccessor(0) == Pred1) {
178 return BI->getCondition();
184 // If we have a merge point of an "if condition" as accepted above, return true
185 // if the specified value dominates the block. We don't handle the true
186 // generality of domination here, just a special case which works well enough
189 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to
190 // see if V (which must be an instruction) is cheap to compute and is
191 // non-trapping. If both are true, the instruction is inserted into the set and
193 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
194 std::set<Instruction*> *AggressiveInsts) {
195 Instruction *I = dyn_cast<Instruction>(V);
196 if (!I) return true; // Non-instructions all dominate instructions.
197 BasicBlock *PBB = I->getParent();
199 // We don't want to allow wierd loops that might have the "if condition" in
200 // the bottom of this block.
201 if (PBB == BB) return false;
203 // If this instruction is defined in a block that contains an unconditional
204 // branch to BB, then it must be in the 'conditional' part of the "if
206 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
207 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
208 if (!AggressiveInsts) return false;
209 // Okay, it looks like the instruction IS in the "condition". Check to
210 // see if its a cheap instruction to unconditionally compute, and if it
211 // only uses stuff defined outside of the condition. If so, hoist it out.
212 switch (I->getOpcode()) {
213 default: return false; // Cannot hoist this out safely.
214 case Instruction::Load:
215 // We can hoist loads that are non-volatile and obviously cannot trap.
216 if (cast<LoadInst>(I)->isVolatile())
218 if (!isa<AllocaInst>(I->getOperand(0)) &&
219 !isa<Constant>(I->getOperand(0)))
222 // Finally, we have to check to make sure there are no instructions
223 // before the load in its basic block, as we are going to hoist the loop
224 // out to its predecessor.
225 if (PBB->begin() != BasicBlock::iterator(I))
228 case Instruction::Add:
229 case Instruction::Sub:
230 case Instruction::And:
231 case Instruction::Or:
232 case Instruction::Xor:
233 case Instruction::Shl:
234 case Instruction::Shr:
235 break; // These are all cheap and non-trapping instructions.
238 // Okay, we can only really hoist these out if their operands are not
239 // defined in the conditional region.
240 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
241 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
243 // Okay, it's safe to do this! Remember this instruction.
244 AggressiveInsts->insert(I);
250 // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
251 // instructions that compare a value against a constant, return the value being
252 // compared, and stick the constant into the Values vector.
253 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
254 if (Instruction *Inst = dyn_cast<Instruction>(V))
255 if (Inst->getOpcode() == Instruction::SetEQ) {
256 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
258 return Inst->getOperand(0);
259 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
261 return Inst->getOperand(1);
263 } else if (Inst->getOpcode() == Instruction::Or) {
264 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
265 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
272 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
273 // setne instructions that compare a value against a constant, return the value
274 // being compared, and stick the constant into the Values vector.
275 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
276 if (Instruction *Inst = dyn_cast<Instruction>(V))
277 if (Inst->getOpcode() == Instruction::SetNE) {
278 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
280 return Inst->getOperand(0);
281 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
283 return Inst->getOperand(1);
285 } else if (Inst->getOpcode() == Instruction::Cast) {
286 // Cast of X to bool is really a comparison against zero.
287 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
288 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
289 return Inst->getOperand(0);
290 } else if (Inst->getOpcode() == Instruction::And) {
291 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
292 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
301 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
302 /// bunch of comparisons of one value against constants, return the value and
303 /// the constants being compared.
304 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
305 std::vector<ConstantInt*> &Values) {
306 if (Cond->getOpcode() == Instruction::Or) {
307 CompVal = GatherConstantSetEQs(Cond, Values);
309 // Return true to indicate that the condition is true if the CompVal is
310 // equal to one of the constants.
312 } else if (Cond->getOpcode() == Instruction::And) {
313 CompVal = GatherConstantSetNEs(Cond, Values);
315 // Return false to indicate that the condition is false if the CompVal is
316 // equal to one of the constants.
322 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
323 /// has no side effects, nuke it. If it uses any instructions that become dead
324 /// because the instruction is now gone, nuke them too.
325 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
326 if (isInstructionTriviallyDead(I)) {
327 std::vector<Value*> Operands(I->op_begin(), I->op_end());
328 I->getParent()->getInstList().erase(I);
329 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
330 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
331 ErasePossiblyDeadInstructionTree(OpI);
335 /// SafeToMergeTerminators - Return true if it is safe to merge these two
336 /// terminator instructions together.
338 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
339 if (SI1 == SI2) return false; // Can't merge with self!
341 // It is not safe to merge these two switch instructions if they have a common
342 // successor, and if that successor has a PHI node, and if *that* PHI node has
343 // conflicting incoming values from the two switch blocks.
344 BasicBlock *SI1BB = SI1->getParent();
345 BasicBlock *SI2BB = SI2->getParent();
346 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
348 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
349 if (SI1Succs.count(*I))
350 for (BasicBlock::iterator BBI = (*I)->begin();
351 isa<PHINode>(BBI); ++BBI) {
352 PHINode *PN = cast<PHINode>(BBI);
353 if (PN->getIncomingValueForBlock(SI1BB) !=
354 PN->getIncomingValueForBlock(SI2BB))
361 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
362 /// now be entries in it from the 'NewPred' block. The values that will be
363 /// flowing into the PHI nodes will be the same as those coming in from
364 /// ExistPred, an existing predecessor of Succ.
365 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
366 BasicBlock *ExistPred) {
367 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
368 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
369 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
371 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
372 PHINode *PN = cast<PHINode>(I);
373 Value *V = PN->getIncomingValueForBlock(ExistPred);
374 PN->addIncoming(V, NewPred);
378 // isValueEqualityComparison - Return true if the specified terminator checks to
379 // see if a value is equal to constant integer value.
380 static Value *isValueEqualityComparison(TerminatorInst *TI) {
381 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
382 // Do not permit merging of large switch instructions into their
383 // predecessors unless there is only one predecessor.
384 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
385 pred_end(SI->getParent())) > 128)
388 return SI->getCondition();
390 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
391 if (BI->isConditional() && BI->getCondition()->hasOneUse())
392 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
393 if ((SCI->getOpcode() == Instruction::SetEQ ||
394 SCI->getOpcode() == Instruction::SetNE) &&
395 isa<ConstantInt>(SCI->getOperand(1)))
396 return SCI->getOperand(0);
400 // Given a value comparison instruction, decode all of the 'cases' that it
401 // represents and return the 'default' block.
403 GetValueEqualityComparisonCases(TerminatorInst *TI,
404 std::vector<std::pair<ConstantInt*,
405 BasicBlock*> > &Cases) {
406 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
407 Cases.reserve(SI->getNumCases());
408 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
409 Cases.push_back(std::make_pair(cast<ConstantInt>(SI->getCaseValue(i)),
410 SI->getSuccessor(i)));
411 return SI->getDefaultDest();
414 BranchInst *BI = cast<BranchInst>(TI);
415 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
416 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
417 BI->getSuccessor(SCI->getOpcode() ==
418 Instruction::SetNE)));
419 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
423 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
424 // equality comparison instruction (either a switch or a branch on "X == c").
425 // See if any of the predecessors of the terminator block are value comparisons
426 // on the same value. If so, and if safe to do so, fold them together.
427 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
428 BasicBlock *BB = TI->getParent();
429 Value *CV = isValueEqualityComparison(TI); // CondVal
430 assert(CV && "Not a comparison?");
431 bool Changed = false;
433 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
434 while (!Preds.empty()) {
435 BasicBlock *Pred = Preds.back();
438 // See if the predecessor is a comparison with the same value.
439 TerminatorInst *PTI = Pred->getTerminator();
440 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
442 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
443 // Figure out which 'cases' to copy from SI to PSI.
444 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
445 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
447 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
448 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
450 // Based on whether the default edge from PTI goes to BB or not, fill in
451 // PredCases and PredDefault with the new switch cases we would like to
453 std::vector<BasicBlock*> NewSuccessors;
455 if (PredDefault == BB) {
456 // If this is the default destination from PTI, only the edges in TI
457 // that don't occur in PTI, or that branch to BB will be activated.
458 std::set<ConstantInt*> PTIHandled;
459 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
460 if (PredCases[i].second != BB)
461 PTIHandled.insert(PredCases[i].first);
463 // The default destination is BB, we don't need explicit targets.
464 std::swap(PredCases[i], PredCases.back());
465 PredCases.pop_back();
469 // Reconstruct the new switch statement we will be building.
470 if (PredDefault != BBDefault) {
471 PredDefault->removePredecessor(Pred);
472 PredDefault = BBDefault;
473 NewSuccessors.push_back(BBDefault);
475 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
476 if (!PTIHandled.count(BBCases[i].first) &&
477 BBCases[i].second != BBDefault) {
478 PredCases.push_back(BBCases[i]);
479 NewSuccessors.push_back(BBCases[i].second);
483 // If this is not the default destination from PSI, only the edges
484 // in SI that occur in PSI with a destination of BB will be
486 std::set<ConstantInt*> PTIHandled;
487 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
488 if (PredCases[i].second == BB) {
489 PTIHandled.insert(PredCases[i].first);
490 std::swap(PredCases[i], PredCases.back());
491 PredCases.pop_back();
495 // Okay, now we know which constants were sent to BB from the
496 // predecessor. Figure out where they will all go now.
497 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
498 if (PTIHandled.count(BBCases[i].first)) {
499 // If this is one we are capable of getting...
500 PredCases.push_back(BBCases[i]);
501 NewSuccessors.push_back(BBCases[i].second);
502 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
505 // If there are any constants vectored to BB that TI doesn't handle,
506 // they must go to the default destination of TI.
507 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
508 E = PTIHandled.end(); I != E; ++I) {
509 PredCases.push_back(std::make_pair(*I, BBDefault));
510 NewSuccessors.push_back(BBDefault);
514 // Okay, at this point, we know which new successor Pred will get. Make
515 // sure we update the number of entries in the PHI nodes for these
517 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
518 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
520 // Now that the successors are updated, create the new Switch instruction.
521 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PTI);
522 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
523 NewSI->addCase(PredCases[i].first, PredCases[i].second);
524 Pred->getInstList().erase(PTI);
526 // Okay, last check. If BB is still a successor of PSI, then we must
527 // have an infinite loop case. If so, add an infinitely looping block
528 // to handle the case to preserve the behavior of the code.
529 BasicBlock *InfLoopBlock = 0;
530 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
531 if (NewSI->getSuccessor(i) == BB) {
532 if (InfLoopBlock == 0) {
533 // Insert it at the end of the loop, because it's either code,
534 // or it won't matter if it's hot. :)
535 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
536 new BranchInst(InfLoopBlock, InfLoopBlock);
538 NewSI->setSuccessor(i, InfLoopBlock);
547 /// HoistThenElseCodeToIf - Given a conditional branch that codes to BB1 and
548 /// BB2, hoist any common code in the two blocks up into the branch block. The
549 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
550 static bool HoistThenElseCodeToIf(BranchInst *BI) {
551 // This does very trivial matching, with limited scanning, to find identical
552 // instructions in the two blocks. In particular, we don't want to get into
553 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
554 // such, we currently just scan for obviously identical instructions in an
556 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
557 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
559 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
560 if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2))
563 // If we get here, we can hoist at least one instruction.
564 BasicBlock *BIParent = BI->getParent();
567 // If we are hoisting the terminator instruction, don't move one (making a
568 // broken BB), instead clone it, and remove BI.
569 if (isa<TerminatorInst>(I1))
570 goto HoistTerminator;
572 // For a normal instruction, we just move one to right before the branch,
573 // then replace all uses of the other with the first. Finally, we remove
574 // the now redundant second instruction.
575 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
576 if (!I2->use_empty())
577 I2->replaceAllUsesWith(I1);
578 BB2->getInstList().erase(I2);
582 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
587 // Okay, it is safe to hoist the terminator.
588 Instruction *NT = I1->clone();
589 BIParent->getInstList().insert(BI, NT);
590 if (NT->getType() != Type::VoidTy) {
591 I1->replaceAllUsesWith(NT);
592 I2->replaceAllUsesWith(NT);
593 NT->setName(I1->getName());
596 // Hoisting one of the terminators from our successor is a great thing.
597 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
598 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
599 // nodes, so we insert select instruction to compute the final result.
600 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
601 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
603 for (BasicBlock::iterator BBI = SI->begin();
604 PN = dyn_cast<PHINode>(BBI); ++BBI) {
605 Value *BB1V = PN->getIncomingValueForBlock(BB1);
606 Value *BB2V = PN->getIncomingValueForBlock(BB2);
608 // These values do not agree. Insert a select instruction before NT
609 // that determines the right value.
610 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
612 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
613 BB1V->getName()+"."+BB2V->getName(), NT);
614 // Make the PHI node use the select for all incoming values for BB1/BB2
615 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
616 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
617 PN->setIncomingValue(i, SI);
622 // Update any PHI nodes in our new successors.
623 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
624 AddPredecessorToBlock(*SI, BIParent, BB1);
626 BI->eraseFromParent();
631 /// ConstantIntOrdering - This class implements a stable ordering of constant
632 /// integers that does not depend on their address. This is important for
633 /// applications that sort ConstantInt's to ensure uniqueness.
634 struct ConstantIntOrdering {
635 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
636 return LHS->getRawValue() < RHS->getRawValue();
642 // SimplifyCFG - This function is used to do simplification of a CFG. For
643 // example, it adjusts branches to branches to eliminate the extra hop, it
644 // eliminates unreachable basic blocks, and does other "peephole" optimization
645 // of the CFG. It returns true if a modification was made.
647 // WARNING: The entry node of a function may not be simplified.
649 bool llvm::SimplifyCFG(BasicBlock *BB) {
650 bool Changed = false;
651 Function *M = BB->getParent();
653 assert(BB && BB->getParent() && "Block not embedded in function!");
654 assert(BB->getTerminator() && "Degenerate basic block encountered!");
655 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
657 // Remove basic blocks that have no predecessors... which are unreachable.
658 if (pred_begin(BB) == pred_end(BB) ||
659 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
660 DEBUG(std::cerr << "Removing BB: \n" << *BB);
662 // Loop through all of our successors and make sure they know that one
663 // of their predecessors is going away.
664 for_each(succ_begin(BB), succ_end(BB),
665 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
667 while (!BB->empty()) {
668 Instruction &I = BB->back();
669 // If this instruction is used, replace uses with an arbitrary
670 // constant value. Because control flow can't get here, we don't care
671 // what we replace the value with. Note that since this block is
672 // unreachable, and all values contained within it must dominate their
673 // uses, that all uses will eventually be removed.
675 // Make all users of this instruction reference the constant instead
676 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
678 // Remove the instruction from the basic block
679 BB->getInstList().pop_back();
681 M->getBasicBlockList().erase(BB);
685 // Check to see if we can constant propagate this terminator instruction
687 Changed |= ConstantFoldTerminator(BB);
689 // Check to see if this block has no non-phi instructions and only a single
690 // successor. If so, replace references to this basic block with references
692 succ_iterator SI(succ_begin(BB));
693 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
694 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
695 while (isa<PHINode>(*BBI)) ++BBI;
697 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor.
698 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
699 Succ != BB) { // Don't hurt infinite loops!
700 // If our successor has PHI nodes, then we need to update them to include
701 // entries for BB's predecessors, not for BB itself. Be careful though,
702 // if this transformation fails (returns true) then we cannot do this
705 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
706 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
708 if (isa<PHINode>(&BB->front())) {
709 std::vector<BasicBlock*>
710 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
712 // Move all PHI nodes in BB to Succ if they are alive, otherwise
714 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
716 BB->getInstList().erase(BB->begin()); // Nuke instruction.
718 // The instruction is alive, so this means that Succ must have
719 // *ONLY* had BB as a predecessor, and the PHI node is still valid
720 // now. Simply move it into Succ, because we know that BB
721 // strictly dominated Succ.
722 BB->getInstList().remove(BB->begin());
723 Succ->getInstList().push_front(PN);
725 // We need to add new entries for the PHI node to account for
726 // predecessors of Succ that the PHI node does not take into
727 // account. At this point, since we know that BB dominated succ,
728 // this means that we should any newly added incoming edges should
729 // use the PHI node as the value for these edges, because they are
731 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
732 if (OldSuccPreds[i] != BB)
733 PN->addIncoming(PN, OldSuccPreds[i]);
737 // Everything that jumped to BB now goes to Succ.
738 std::string OldName = BB->getName();
739 BB->replaceAllUsesWith(Succ);
740 BB->eraseFromParent(); // Delete the old basic block.
742 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
743 Succ->setName(OldName);
749 // If this is a returning block with only PHI nodes in it, fold the return
750 // instruction into any unconditional branch predecessors.
752 // If any predecessor is a conditional branch that just selects among
753 // different return values, fold the replace the branch/return with a select
755 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
756 BasicBlock::iterator BBI = BB->getTerminator();
757 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
758 // Find predecessors that end with branches.
759 std::vector<BasicBlock*> UncondBranchPreds;
760 std::vector<BranchInst*> CondBranchPreds;
761 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
762 TerminatorInst *PTI = (*PI)->getTerminator();
763 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
764 if (BI->isUnconditional())
765 UncondBranchPreds.push_back(*PI);
767 CondBranchPreds.push_back(BI);
770 // If we found some, do the transformation!
771 if (!UncondBranchPreds.empty()) {
772 while (!UncondBranchPreds.empty()) {
773 BasicBlock *Pred = UncondBranchPreds.back();
774 UncondBranchPreds.pop_back();
775 Instruction *UncondBranch = Pred->getTerminator();
776 // Clone the return and add it to the end of the predecessor.
777 Instruction *NewRet = RI->clone();
778 Pred->getInstList().push_back(NewRet);
780 // If the return instruction returns a value, and if the value was a
781 // PHI node in "BB", propagate the right value into the return.
782 if (NewRet->getNumOperands() == 1)
783 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
784 if (PN->getParent() == BB)
785 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
786 // Update any PHI nodes in the returning block to realize that we no
787 // longer branch to them.
788 BB->removePredecessor(Pred);
789 Pred->getInstList().erase(UncondBranch);
792 // If we eliminated all predecessors of the block, delete the block now.
793 if (pred_begin(BB) == pred_end(BB))
794 // We know there are no successors, so just nuke the block.
795 M->getBasicBlockList().erase(BB);
800 // Check out all of the conditional branches going to this return
801 // instruction. If any of them just select between returns, change the
802 // branch itself into a select/return pair.
803 while (!CondBranchPreds.empty()) {
804 BranchInst *BI = CondBranchPreds.back();
805 CondBranchPreds.pop_back();
806 BasicBlock *TrueSucc = BI->getSuccessor(0);
807 BasicBlock *FalseSucc = BI->getSuccessor(1);
808 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
810 // Check to see if the non-BB successor is also a return block.
811 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
812 // Check to see if there are only PHI instructions in this block.
813 BasicBlock::iterator OSI = OtherSucc->getTerminator();
814 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
815 // Okay, we found a branch that is going to two return nodes. If
816 // there is no return value for this function, just change the
817 // branch into a return.
818 if (RI->getNumOperands() == 0) {
819 TrueSucc->removePredecessor(BI->getParent());
820 FalseSucc->removePredecessor(BI->getParent());
821 new ReturnInst(0, BI);
822 BI->getParent()->getInstList().erase(BI);
826 // Otherwise, figure out what the true and false return values are
827 // so we can insert a new select instruction.
828 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
829 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
831 // Unwrap any PHI nodes in the return blocks.
832 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
833 if (TVPN->getParent() == TrueSucc)
834 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
835 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
836 if (FVPN->getParent() == FalseSucc)
837 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
839 TrueSucc->removePredecessor(BI->getParent());
840 FalseSucc->removePredecessor(BI->getParent());
842 // Insert a new select instruction.
844 Value *BrCond = BI->getCondition();
845 if (TrueValue != FalseValue)
846 NewRetVal = new SelectInst(BrCond, TrueValue,
847 FalseValue, "retval", BI);
849 NewRetVal = TrueValue;
851 new ReturnInst(NewRetVal, BI);
852 BI->getParent()->getInstList().erase(BI);
853 if (BrCond->use_empty())
854 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
855 BrCondI->getParent()->getInstList().erase(BrCondI);
861 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
862 // Check to see if the first instruction in this block is just an unwind.
863 // If so, replace any invoke instructions which use this as an exception
864 // destination with call instructions, and any unconditional branch
865 // predecessor with an unwind.
867 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
868 while (!Preds.empty()) {
869 BasicBlock *Pred = Preds.back();
870 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
871 if (BI->isUnconditional()) {
872 Pred->getInstList().pop_back(); // nuke uncond branch
873 new UnwindInst(Pred); // Use unwind.
876 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
877 if (II->getUnwindDest() == BB) {
878 // Insert a new branch instruction before the invoke, because this
879 // is now a fall through...
880 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
881 Pred->getInstList().remove(II); // Take out of symbol table
883 // Insert the call now...
884 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
885 CallInst *CI = new CallInst(II->getCalledValue(), Args,
887 // If the invoke produced a value, the Call now does instead
888 II->replaceAllUsesWith(CI);
896 // If this block is now dead, remove it.
897 if (pred_begin(BB) == pred_end(BB)) {
898 // We know there are no successors, so just nuke the block.
899 M->getBasicBlockList().erase(BB);
903 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->begin())) {
904 if (isValueEqualityComparison(SI))
905 if (FoldValueComparisonIntoPredecessors(SI))
906 return SimplifyCFG(BB) || 1;
907 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
908 if (BI->isConditional()) {
909 if (Value *CompVal = isValueEqualityComparison(BI)) {
910 // This block must be empty, except for the setcond inst, if it exists.
911 BasicBlock::iterator I = BB->begin();
913 (&*I == cast<Instruction>(BI->getCondition()) &&
915 if (FoldValueComparisonIntoPredecessors(BI))
916 return SimplifyCFG(BB) | true;
919 // If this basic block is ONLY a setcc and a branch, and if a predecessor
920 // branches to us and one of our successors, fold the setcc into the
921 // predecessor and use logical operations to pick the right destination.
922 BasicBlock *TrueDest = BI->getSuccessor(0);
923 BasicBlock *FalseDest = BI->getSuccessor(1);
924 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
925 if (Cond->getParent() == BB && &BB->front() == Cond &&
926 Cond->getNext() == BI && Cond->hasOneUse() &&
927 TrueDest != BB && FalseDest != BB)
928 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
929 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
930 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
931 BasicBlock *PredBlock = *PI;
932 if (PBI->getSuccessor(0) == FalseDest ||
933 PBI->getSuccessor(1) == TrueDest) {
934 // Invert the predecessors condition test (xor it with true),
935 // which allows us to write this code once.
937 BinaryOperator::createNot(PBI->getCondition(),
938 PBI->getCondition()->getName()+".not", PBI);
939 PBI->setCondition(NewCond);
940 BasicBlock *OldTrue = PBI->getSuccessor(0);
941 BasicBlock *OldFalse = PBI->getSuccessor(1);
942 PBI->setSuccessor(0, OldFalse);
943 PBI->setSuccessor(1, OldTrue);
946 if (PBI->getSuccessor(0) == TrueDest ||
947 PBI->getSuccessor(1) == FalseDest) {
948 // Clone Cond into the predecessor basic block, and or/and the
949 // two conditions together.
950 Instruction *New = Cond->clone();
951 New->setName(Cond->getName());
952 Cond->setName(Cond->getName()+".old");
953 PredBlock->getInstList().insert(PBI, New);
954 Instruction::BinaryOps Opcode =
955 PBI->getSuccessor(0) == TrueDest ?
956 Instruction::Or : Instruction::And;
958 BinaryOperator::create(Opcode, PBI->getCondition(),
959 New, "bothcond", PBI);
960 PBI->setCondition(NewCond);
961 if (PBI->getSuccessor(0) == BB) {
962 AddPredecessorToBlock(TrueDest, PredBlock, BB);
963 PBI->setSuccessor(0, TrueDest);
965 if (PBI->getSuccessor(1) == BB) {
966 AddPredecessorToBlock(FalseDest, PredBlock, BB);
967 PBI->setSuccessor(1, FalseDest);
969 return SimplifyCFG(BB) | 1;
973 // If this block ends with a branch instruction, and if there is one
974 // predecessor, see if the previous block ended with a branch on the same
975 // condition, which makes this conditional branch redundant.
976 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
977 BasicBlock *OnlyPred = *PI++;
978 for (; PI != PE; ++PI)// Search all predecessors, see if they are all same
979 if (*PI != OnlyPred) {
980 OnlyPred = 0; // There are multiple different predecessors...
985 if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
986 if (PBI->isConditional() &&
987 PBI->getCondition() == BI->getCondition() &&
988 (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
989 // Okay, the outcome of this conditional branch is statically
990 // knowable. Delete the outgoing CFG edge that is impossible to
992 bool CondIsTrue = PBI->getSuccessor(0) == BB;
993 BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
994 new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
995 BB->getInstList().erase(BI);
996 return SimplifyCFG(BB) | true;
999 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1000 // If there are any instructions immediately before the unreachable that can
1001 // be removed, do so.
1002 Instruction *Unreachable = BB->getTerminator();
1003 while (Unreachable != BB->begin()) {
1004 BasicBlock::iterator BBI = Unreachable;
1006 if (isa<CallInst>(BBI)) break;
1007 // Delete this instruction
1008 BB->getInstList().erase(BBI);
1012 // If the unreachable instruction is the first in the block, take a gander
1013 // at all of the predecessors of this instruction, and simplify them.
1014 if (&BB->front() == Unreachable) {
1015 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1016 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1017 TerminatorInst *TI = Preds[i]->getTerminator();
1019 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1020 if (BI->isUnconditional()) {
1021 if (BI->getSuccessor(0) == BB) {
1022 new UnreachableInst(TI);
1023 TI->eraseFromParent();
1027 if (BI->getSuccessor(0) == BB) {
1028 new BranchInst(BI->getSuccessor(1), BI);
1029 BI->eraseFromParent();
1030 } else if (BI->getSuccessor(1) == BB) {
1031 new BranchInst(BI->getSuccessor(0), BI);
1032 BI->eraseFromParent();
1036 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1037 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1038 if (SI->getSuccessor(i) == BB) {
1043 // If the default value is unreachable, figure out the most popular
1044 // destination and make it the default.
1045 if (SI->getSuccessor(0) == BB) {
1046 std::map<BasicBlock*, unsigned> Popularity;
1047 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1048 Popularity[SI->getSuccessor(i)]++;
1050 // Find the most popular block.
1051 unsigned MaxPop = 0;
1052 BasicBlock *MaxBlock = 0;
1053 for (std::map<BasicBlock*, unsigned>::iterator
1054 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1055 if (I->second > MaxPop) {
1057 MaxBlock = I->first;
1061 // Make this the new default, allowing us to delete any explicit
1063 SI->setSuccessor(0, MaxBlock);
1066 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1067 if (SI->getSuccessor(i) == MaxBlock) {
1073 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1074 if (II->getUnwindDest() == BB) {
1075 // Convert the invoke to a call instruction. This would be a good
1076 // place to note that the call does not throw though.
1077 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1078 II->removeFromParent(); // Take out of symbol table
1080 // Insert the call now...
1081 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1082 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1084 // If the invoke produced a value, the Call does now instead.
1085 II->replaceAllUsesWith(CI);
1092 // If this block is now dead, remove it.
1093 if (pred_begin(BB) == pred_end(BB)) {
1094 // We know there are no successors, so just nuke the block.
1095 M->getBasicBlockList().erase(BB);
1101 // Merge basic blocks into their predecessor if there is only one distinct
1102 // pred, and if there is only one distinct successor of the predecessor, and
1103 // if there are no PHI nodes.
1105 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1106 BasicBlock *OnlyPred = *PI++;
1107 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1108 if (*PI != OnlyPred) {
1109 OnlyPred = 0; // There are multiple different predecessors...
1113 BasicBlock *OnlySucc = 0;
1114 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1115 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1116 // Check to see if there is only one distinct successor...
1117 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1119 for (; SI != SE; ++SI)
1120 if (*SI != OnlySucc) {
1121 OnlySucc = 0; // There are multiple distinct successors!
1127 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
1128 TerminatorInst *Term = OnlyPred->getTerminator();
1130 // Resolve any PHI nodes at the start of the block. They are all
1131 // guaranteed to have exactly one entry if they exist, unless there are
1132 // multiple duplicate (but guaranteed to be equal) entries for the
1133 // incoming edges. This occurs when there are multiple edges from
1134 // OnlyPred to OnlySucc.
1136 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1137 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1138 BB->getInstList().pop_front(); // Delete the phi node...
1141 // Delete the unconditional branch from the predecessor...
1142 OnlyPred->getInstList().pop_back();
1144 // Move all definitions in the successor to the predecessor...
1145 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
1147 // Make all PHI nodes that referred to BB now refer to Pred as their
1149 BB->replaceAllUsesWith(OnlyPred);
1151 std::string OldName = BB->getName();
1153 // Erase basic block from the function...
1154 M->getBasicBlockList().erase(BB);
1156 // Inherit predecessors name if it exists...
1157 if (!OldName.empty() && !OnlyPred->hasName())
1158 OnlyPred->setName(OldName);
1163 // Otherwise, if this block only has a single predecessor, and if that block
1164 // is a conditional branch, see if we can hoist any code from this block up
1165 // into our predecessor.
1167 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator())) {
1168 // This is guaranteed to be a condbr at this point.
1169 assert(BI->isConditional() && "Should have folded bb into pred!");
1170 // Get the other block.
1171 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1172 PI = pred_begin(OtherBB);
1174 if (PI == pred_end(OtherBB)) {
1175 // We have a conditional branch to two blocks that are only reachable
1176 // from the condbr. We know that the condbr dominates the two blocks,
1177 // so see if there is any identical code in the "then" and "else"
1178 // blocks. If so, we can hoist it up to the branching block.
1179 Changed |= HoistThenElseCodeToIf(BI);
1183 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1184 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1185 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1186 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1187 Instruction *Cond = cast<Instruction>(BI->getCondition());
1188 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1189 // 'setne's and'ed together, collect them.
1191 std::vector<ConstantInt*> Values;
1192 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1193 if (CompVal && CompVal->getType()->isInteger()) {
1194 // There might be duplicate constants in the list, which the switch
1195 // instruction can't handle, remove them now.
1196 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
1197 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1199 // Figure out which block is which destination.
1200 BasicBlock *DefaultBB = BI->getSuccessor(1);
1201 BasicBlock *EdgeBB = BI->getSuccessor(0);
1202 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1204 // Create the new switch instruction now.
1205 SwitchInst *New = new SwitchInst(CompVal, DefaultBB, BI);
1207 // Add all of the 'cases' to the switch instruction.
1208 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1209 New->addCase(Values[i], EdgeBB);
1211 // We added edges from PI to the EdgeBB. As such, if there were any
1212 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1213 // the number of edges added.
1214 for (BasicBlock::iterator BBI = EdgeBB->begin();
1215 isa<PHINode>(BBI); ++BBI) {
1216 PHINode *PN = cast<PHINode>(BBI);
1217 Value *InVal = PN->getIncomingValueForBlock(*PI);
1218 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1219 PN->addIncoming(InVal, *PI);
1222 // Erase the old branch instruction.
1223 (*PI)->getInstList().erase(BI);
1225 // Erase the potentially condition tree that was used to computed the
1226 // branch condition.
1227 ErasePossiblyDeadInstructionTree(Cond);
1232 // If there is a trivial two-entry PHI node in this basic block, and we can
1233 // eliminate it, do so now.
1234 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1235 if (PN->getNumIncomingValues() == 2) {
1236 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1237 // statement", which has a very simple dominance structure. Basically, we
1238 // are trying to find the condition that is being branched on, which
1239 // subsequently causes this merge to happen. We really want control
1240 // dependence information for this check, but simplifycfg can't keep it up
1241 // to date, and this catches most of the cases we care about anyway.
1243 BasicBlock *IfTrue, *IfFalse;
1244 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
1245 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1246 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1248 // Loop over the PHI's seeing if we can promote them all to select
1249 // instructions. While we are at it, keep track of the instructions
1250 // that need to be moved to the dominating block.
1251 std::set<Instruction*> AggressiveInsts;
1252 bool CanPromote = true;
1254 BasicBlock::iterator AfterPHIIt = BB->begin();
1255 while (isa<PHINode>(AfterPHIIt)) {
1256 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1257 if (PN->getIncomingValue(0) == PN->getIncomingValue(1))
1258 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1259 else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1260 &AggressiveInsts) ||
1261 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1262 &AggressiveInsts)) {
1268 // Did we eliminate all PHI's?
1269 CanPromote |= AfterPHIIt == BB->begin();
1271 // If we all PHI nodes are promotable, check to make sure that all
1272 // instructions in the predecessor blocks can be promoted as well. If
1273 // not, we won't be able to get rid of the control flow, so it's not
1274 // worth promoting to select instructions.
1275 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1277 PN = cast<PHINode>(BB->begin());
1278 BasicBlock *Pred = PN->getIncomingBlock(0);
1279 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1281 DomBlock = *pred_begin(Pred);
1282 for (BasicBlock::iterator I = Pred->begin();
1283 !isa<TerminatorInst>(I); ++I)
1284 if (!AggressiveInsts.count(I)) {
1285 // This is not an aggressive instruction that we can promote.
1286 // Because of this, we won't be able to get rid of the control
1287 // flow, so the xform is not worth it.
1293 Pred = PN->getIncomingBlock(1);
1295 cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1297 DomBlock = *pred_begin(Pred);
1298 for (BasicBlock::iterator I = Pred->begin();
1299 !isa<TerminatorInst>(I); ++I)
1300 if (!AggressiveInsts.count(I)) {
1301 // This is not an aggressive instruction that we can promote.
1302 // Because of this, we won't be able to get rid of the control
1303 // flow, so the xform is not worth it.
1310 // If we can still promote the PHI nodes after this gauntlet of tests,
1311 // do all of the PHI's now.
1313 // Move all 'aggressive' instructions, which are defined in the
1314 // conditional parts of the if's up to the dominating block.
1316 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1317 IfBlock1->getInstList(),
1319 IfBlock1->getTerminator());
1322 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1323 IfBlock2->getInstList(),
1325 IfBlock2->getTerminator());
1328 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1329 // Change the PHI node into a select instruction.
1331 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1333 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1335 std::string Name = PN->getName(); PN->setName("");
1336 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1338 BB->getInstList().erase(PN);