LLVM API Documentation
00001 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // Peephole optimize the CFG. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #define DEBUG_TYPE "simplifycfg" 00015 #include "llvm/Transforms/Utils/Local.h" 00016 #include "llvm/Constants.h" 00017 #include "llvm/Instructions.h" 00018 #include "llvm/Type.h" 00019 #include "llvm/Support/CFG.h" 00020 #include "llvm/Support/Debug.h" 00021 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00022 #include <algorithm> 00023 #include <functional> 00024 #include <set> 00025 #include <map> 00026 #include <iostream> 00027 using namespace llvm; 00028 00029 /// SafeToMergeTerminators - Return true if it is safe to merge these two 00030 /// terminator instructions together. 00031 /// 00032 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { 00033 if (SI1 == SI2) return false; // Can't merge with self! 00034 00035 // It is not safe to merge these two switch instructions if they have a common 00036 // successor, and if that successor has a PHI node, and if *that* PHI node has 00037 // conflicting incoming values from the two switch blocks. 00038 BasicBlock *SI1BB = SI1->getParent(); 00039 BasicBlock *SI2BB = SI2->getParent(); 00040 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 00041 00042 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) 00043 if (SI1Succs.count(*I)) 00044 for (BasicBlock::iterator BBI = (*I)->begin(); 00045 isa<PHINode>(BBI); ++BBI) { 00046 PHINode *PN = cast<PHINode>(BBI); 00047 if (PN->getIncomingValueForBlock(SI1BB) != 00048 PN->getIncomingValueForBlock(SI2BB)) 00049 return false; 00050 } 00051 00052 return true; 00053 } 00054 00055 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will 00056 /// now be entries in it from the 'NewPred' block. The values that will be 00057 /// flowing into the PHI nodes will be the same as those coming in from 00058 /// ExistPred, an existing predecessor of Succ. 00059 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, 00060 BasicBlock *ExistPred) { 00061 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) != 00062 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!"); 00063 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do 00064 00065 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 00066 PHINode *PN = cast<PHINode>(I); 00067 Value *V = PN->getIncomingValueForBlock(ExistPred); 00068 PN->addIncoming(V, NewPred); 00069 } 00070 } 00071 00072 // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an 00073 // almost-empty BB ending in an unconditional branch to Succ, into succ. 00074 // 00075 // Assumption: Succ is the single successor for BB. 00076 // 00077 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { 00078 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!"); 00079 00080 // Check to see if one of the predecessors of BB is already a predecessor of 00081 // Succ. If so, we cannot do the transformation if there are any PHI nodes 00082 // with incompatible values coming in from the two edges! 00083 // 00084 if (isa<PHINode>(Succ->front())) { 00085 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); 00086 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); 00087 PI != PE; ++PI) 00088 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) { 00089 // Loop over all of the PHI nodes checking to see if there are 00090 // incompatible values coming in. 00091 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 00092 PHINode *PN = cast<PHINode>(I); 00093 // Loop up the entries in the PHI node for BB and for *PI if the 00094 // values coming in are non-equal, we cannot merge these two blocks 00095 // (instead we should insert a conditional move or something, then 00096 // merge the blocks). 00097 if (PN->getIncomingValueForBlock(BB) != 00098 PN->getIncomingValueForBlock(*PI)) 00099 return false; // Values are not equal... 00100 } 00101 } 00102 } 00103 00104 // Finally, if BB has PHI nodes that are used by things other than the PHIs in 00105 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot 00106 // fold these blocks, as we don't know whether BB dominates Succ or not to 00107 // update the PHI nodes correctly. 00108 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true; 00109 00110 // If the predecessors of Succ are only BB and Succ itself, we can handle this. 00111 bool IsSafe = true; 00112 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI) 00113 if (*PI != Succ && *PI != BB) { 00114 IsSafe = false; 00115 break; 00116 } 00117 if (IsSafe) return true; 00118 00119 // If the PHI nodes in BB are only used by instructions in Succ, we are ok if 00120 // BB and Succ have no common predecessors. 00121 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) { 00122 PHINode *PN = cast<PHINode>(I); 00123 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; 00124 ++UI) 00125 if (cast<Instruction>(*UI)->getParent() != Succ) 00126 return false; 00127 } 00128 00129 // Scan the predecessor sets of BB and Succ, making sure there are no common 00130 // predecessors. Common predecessors would cause us to build a phi node with 00131 // differing incoming values, which is not legal. 00132 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); 00133 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI) 00134 if (BBPreds.count(*PI)) 00135 return false; 00136 00137 return true; 00138 } 00139 00140 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional 00141 /// branch to Succ, and contains no instructions other than PHI nodes and the 00142 /// branch. If possible, eliminate BB. 00143 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, 00144 BasicBlock *Succ) { 00145 // If our successor has PHI nodes, then we need to update them to include 00146 // entries for BB's predecessors, not for BB itself. Be careful though, 00147 // if this transformation fails (returns true) then we cannot do this 00148 // transformation! 00149 // 00150 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false; 00151 00152 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB); 00153 00154 if (isa<PHINode>(Succ->begin())) { 00155 // If there is more than one pred of succ, and there are PHI nodes in 00156 // the successor, then we need to add incoming edges for the PHI nodes 00157 // 00158 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); 00159 00160 // Loop over all of the PHI nodes in the successor of BB. 00161 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) { 00162 PHINode *PN = cast<PHINode>(I); 00163 Value *OldVal = PN->removeIncomingValue(BB, false); 00164 assert(OldVal && "No entry in PHI for Pred BB!"); 00165 00166 // If this incoming value is one of the PHI nodes in BB, the new entries 00167 // in the PHI node are the entries from the old PHI. 00168 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) { 00169 PHINode *OldValPN = cast<PHINode>(OldVal); 00170 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) 00171 PN->addIncoming(OldValPN->getIncomingValue(i), 00172 OldValPN->getIncomingBlock(i)); 00173 } else { 00174 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 00175 End = BBPreds.end(); PredI != End; ++PredI) { 00176 // Add an incoming value for each of the new incoming values... 00177 PN->addIncoming(OldVal, *PredI); 00178 } 00179 } 00180 } 00181 } 00182 00183 if (isa<PHINode>(&BB->front())) { 00184 std::vector<BasicBlock*> 00185 OldSuccPreds(pred_begin(Succ), pred_end(Succ)); 00186 00187 // Move all PHI nodes in BB to Succ if they are alive, otherwise 00188 // delete them. 00189 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) 00190 if (PN->use_empty()) { 00191 // Just remove the dead phi. This happens if Succ's PHIs were the only 00192 // users of the PHI nodes. 00193 PN->eraseFromParent(); 00194 } else { 00195 // The instruction is alive, so this means that Succ must have 00196 // *ONLY* had BB as a predecessor, and the PHI node is still valid 00197 // now. Simply move it into Succ, because we know that BB 00198 // strictly dominated Succ. 00199 Succ->getInstList().splice(Succ->begin(), 00200 BB->getInstList(), BB->begin()); 00201 00202 // We need to add new entries for the PHI node to account for 00203 // predecessors of Succ that the PHI node does not take into 00204 // account. At this point, since we know that BB dominated succ, 00205 // this means that we should any newly added incoming edges should 00206 // use the PHI node as the value for these edges, because they are 00207 // loop back edges. 00208 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i) 00209 if (OldSuccPreds[i] != BB) 00210 PN->addIncoming(PN, OldSuccPreds[i]); 00211 } 00212 } 00213 00214 // Everything that jumped to BB now goes to Succ. 00215 std::string OldName = BB->getName(); 00216 BB->replaceAllUsesWith(Succ); 00217 BB->eraseFromParent(); // Delete the old basic block. 00218 00219 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can 00220 Succ->setName(OldName); 00221 return true; 00222 } 00223 00224 /// GetIfCondition - Given a basic block (BB) with two predecessors (and 00225 /// presumably PHI nodes in it), check to see if the merge at this block is due 00226 /// to an "if condition". If so, return the boolean condition that determines 00227 /// which entry into BB will be taken. Also, return by references the block 00228 /// that will be entered from if the condition is true, and the block that will 00229 /// be entered if the condition is false. 00230 /// 00231 /// 00232 static Value *GetIfCondition(BasicBlock *BB, 00233 BasicBlock *&IfTrue, BasicBlock *&IfFalse) { 00234 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 && 00235 "Function can only handle blocks with 2 predecessors!"); 00236 BasicBlock *Pred1 = *pred_begin(BB); 00237 BasicBlock *Pred2 = *++pred_begin(BB); 00238 00239 // We can only handle branches. Other control flow will be lowered to 00240 // branches if possible anyway. 00241 if (!isa<BranchInst>(Pred1->getTerminator()) || 00242 !isa<BranchInst>(Pred2->getTerminator())) 00243 return 0; 00244 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator()); 00245 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator()); 00246 00247 // Eliminate code duplication by ensuring that Pred1Br is conditional if 00248 // either are. 00249 if (Pred2Br->isConditional()) { 00250 // If both branches are conditional, we don't have an "if statement". In 00251 // reality, we could transform this case, but since the condition will be 00252 // required anyway, we stand no chance of eliminating it, so the xform is 00253 // probably not profitable. 00254 if (Pred1Br->isConditional()) 00255 return 0; 00256 00257 std::swap(Pred1, Pred2); 00258 std::swap(Pred1Br, Pred2Br); 00259 } 00260 00261 if (Pred1Br->isConditional()) { 00262 // If we found a conditional branch predecessor, make sure that it branches 00263 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 00264 if (Pred1Br->getSuccessor(0) == BB && 00265 Pred1Br->getSuccessor(1) == Pred2) { 00266 IfTrue = Pred1; 00267 IfFalse = Pred2; 00268 } else if (Pred1Br->getSuccessor(0) == Pred2 && 00269 Pred1Br->getSuccessor(1) == BB) { 00270 IfTrue = Pred2; 00271 IfFalse = Pred1; 00272 } else { 00273 // We know that one arm of the conditional goes to BB, so the other must 00274 // go somewhere unrelated, and this must not be an "if statement". 00275 return 0; 00276 } 00277 00278 // The only thing we have to watch out for here is to make sure that Pred2 00279 // doesn't have incoming edges from other blocks. If it does, the condition 00280 // doesn't dominate BB. 00281 if (++pred_begin(Pred2) != pred_end(Pred2)) 00282 return 0; 00283 00284 return Pred1Br->getCondition(); 00285 } 00286 00287 // Ok, if we got here, both predecessors end with an unconditional branch to 00288 // BB. Don't panic! If both blocks only have a single (identical) 00289 // predecessor, and THAT is a conditional branch, then we're all ok! 00290 if (pred_begin(Pred1) == pred_end(Pred1) || 00291 ++pred_begin(Pred1) != pred_end(Pred1) || 00292 pred_begin(Pred2) == pred_end(Pred2) || 00293 ++pred_begin(Pred2) != pred_end(Pred2) || 00294 *pred_begin(Pred1) != *pred_begin(Pred2)) 00295 return 0; 00296 00297 // Otherwise, if this is a conditional branch, then we can use it! 00298 BasicBlock *CommonPred = *pred_begin(Pred1); 00299 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) { 00300 assert(BI->isConditional() && "Two successors but not conditional?"); 00301 if (BI->getSuccessor(0) == Pred1) { 00302 IfTrue = Pred1; 00303 IfFalse = Pred2; 00304 } else { 00305 IfTrue = Pred2; 00306 IfFalse = Pred1; 00307 } 00308 return BI->getCondition(); 00309 } 00310 return 0; 00311 } 00312 00313 00314 // If we have a merge point of an "if condition" as accepted above, return true 00315 // if the specified value dominates the block. We don't handle the true 00316 // generality of domination here, just a special case which works well enough 00317 // for us. 00318 // 00319 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to 00320 // see if V (which must be an instruction) is cheap to compute and is 00321 // non-trapping. If both are true, the instruction is inserted into the set and 00322 // true is returned. 00323 static bool DominatesMergePoint(Value *V, BasicBlock *BB, 00324 std::set<Instruction*> *AggressiveInsts) { 00325 Instruction *I = dyn_cast<Instruction>(V); 00326 if (!I) return true; // Non-instructions all dominate instructions. 00327 BasicBlock *PBB = I->getParent(); 00328 00329 // We don't want to allow weird loops that might have the "if condition" in 00330 // the bottom of this block. 00331 if (PBB == BB) return false; 00332 00333 // If this instruction is defined in a block that contains an unconditional 00334 // branch to BB, then it must be in the 'conditional' part of the "if 00335 // statement". 00336 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator())) 00337 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) { 00338 if (!AggressiveInsts) return false; 00339 // Okay, it looks like the instruction IS in the "condition". Check to 00340 // see if its a cheap instruction to unconditionally compute, and if it 00341 // only uses stuff defined outside of the condition. If so, hoist it out. 00342 switch (I->getOpcode()) { 00343 default: return false; // Cannot hoist this out safely. 00344 case Instruction::Load: 00345 // We can hoist loads that are non-volatile and obviously cannot trap. 00346 if (cast<LoadInst>(I)->isVolatile()) 00347 return false; 00348 if (!isa<AllocaInst>(I->getOperand(0)) && 00349 !isa<Constant>(I->getOperand(0))) 00350 return false; 00351 00352 // Finally, we have to check to make sure there are no instructions 00353 // before the load in its basic block, as we are going to hoist the loop 00354 // out to its predecessor. 00355 if (PBB->begin() != BasicBlock::iterator(I)) 00356 return false; 00357 break; 00358 case Instruction::Add: 00359 case Instruction::Sub: 00360 case Instruction::And: 00361 case Instruction::Or: 00362 case Instruction::Xor: 00363 case Instruction::Shl: 00364 case Instruction::Shr: 00365 case Instruction::SetEQ: 00366 case Instruction::SetNE: 00367 case Instruction::SetLT: 00368 case Instruction::SetGT: 00369 case Instruction::SetLE: 00370 case Instruction::SetGE: 00371 break; // These are all cheap and non-trapping instructions. 00372 } 00373 00374 // Okay, we can only really hoist these out if their operands are not 00375 // defined in the conditional region. 00376 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 00377 if (!DominatesMergePoint(I->getOperand(i), BB, 0)) 00378 return false; 00379 // Okay, it's safe to do this! Remember this instruction. 00380 AggressiveInsts->insert(I); 00381 } 00382 00383 return true; 00384 } 00385 00386 // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq 00387 // instructions that compare a value against a constant, return the value being 00388 // compared, and stick the constant into the Values vector. 00389 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){ 00390 if (Instruction *Inst = dyn_cast<Instruction>(V)) 00391 if (Inst->getOpcode() == Instruction::SetEQ) { 00392 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) { 00393 Values.push_back(C); 00394 return Inst->getOperand(0); 00395 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) { 00396 Values.push_back(C); 00397 return Inst->getOperand(1); 00398 } 00399 } else if (Inst->getOpcode() == Instruction::Or) { 00400 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values)) 00401 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values)) 00402 if (LHS == RHS) 00403 return LHS; 00404 } 00405 return 0; 00406 } 00407 00408 // GatherConstantSetNEs - Given a potentially 'and'd together collection of 00409 // setne instructions that compare a value against a constant, return the value 00410 // being compared, and stick the constant into the Values vector. 00411 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){ 00412 if (Instruction *Inst = dyn_cast<Instruction>(V)) 00413 if (Inst->getOpcode() == Instruction::SetNE) { 00414 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) { 00415 Values.push_back(C); 00416 return Inst->getOperand(0); 00417 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) { 00418 Values.push_back(C); 00419 return Inst->getOperand(1); 00420 } 00421 } else if (Inst->getOpcode() == Instruction::Cast) { 00422 // Cast of X to bool is really a comparison against zero. 00423 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!"); 00424 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0)); 00425 return Inst->getOperand(0); 00426 } else if (Inst->getOpcode() == Instruction::And) { 00427 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values)) 00428 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values)) 00429 if (LHS == RHS) 00430 return LHS; 00431 } 00432 return 0; 00433 } 00434 00435 00436 00437 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a 00438 /// bunch of comparisons of one value against constants, return the value and 00439 /// the constants being compared. 00440 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal, 00441 std::vector<ConstantInt*> &Values) { 00442 if (Cond->getOpcode() == Instruction::Or) { 00443 CompVal = GatherConstantSetEQs(Cond, Values); 00444 00445 // Return true to indicate that the condition is true if the CompVal is 00446 // equal to one of the constants. 00447 return true; 00448 } else if (Cond->getOpcode() == Instruction::And) { 00449 CompVal = GatherConstantSetNEs(Cond, Values); 00450 00451 // Return false to indicate that the condition is false if the CompVal is 00452 // equal to one of the constants. 00453 return false; 00454 } 00455 return false; 00456 } 00457 00458 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and 00459 /// has no side effects, nuke it. If it uses any instructions that become dead 00460 /// because the instruction is now gone, nuke them too. 00461 static void ErasePossiblyDeadInstructionTree(Instruction *I) { 00462 if (isInstructionTriviallyDead(I)) { 00463 std::vector<Value*> Operands(I->op_begin(), I->op_end()); 00464 I->getParent()->getInstList().erase(I); 00465 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 00466 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i])) 00467 ErasePossiblyDeadInstructionTree(OpI); 00468 } 00469 } 00470 00471 // isValueEqualityComparison - Return true if the specified terminator checks to 00472 // see if a value is equal to constant integer value. 00473 static Value *isValueEqualityComparison(TerminatorInst *TI) { 00474 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 00475 // Do not permit merging of large switch instructions into their 00476 // predecessors unless there is only one predecessor. 00477 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()), 00478 pred_end(SI->getParent())) > 128) 00479 return 0; 00480 00481 return SI->getCondition(); 00482 } 00483 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 00484 if (BI->isConditional() && BI->getCondition()->hasOneUse()) 00485 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition())) 00486 if ((SCI->getOpcode() == Instruction::SetEQ || 00487 SCI->getOpcode() == Instruction::SetNE) && 00488 isa<ConstantInt>(SCI->getOperand(1))) 00489 return SCI->getOperand(0); 00490 return 0; 00491 } 00492 00493 // Given a value comparison instruction, decode all of the 'cases' that it 00494 // represents and return the 'default' block. 00495 static BasicBlock * 00496 GetValueEqualityComparisonCases(TerminatorInst *TI, 00497 std::vector<std::pair<ConstantInt*, 00498 BasicBlock*> > &Cases) { 00499 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 00500 Cases.reserve(SI->getNumCases()); 00501 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) 00502 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i))); 00503 return SI->getDefaultDest(); 00504 } 00505 00506 BranchInst *BI = cast<BranchInst>(TI); 00507 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition()); 00508 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)), 00509 BI->getSuccessor(SCI->getOpcode() == 00510 Instruction::SetNE))); 00511 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ); 00512 } 00513 00514 00515 // EliminateBlockCases - Given an vector of bb/value pairs, remove any entries 00516 // in the list that match the specified block. 00517 static void EliminateBlockCases(BasicBlock *BB, 00518 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) { 00519 for (unsigned i = 0, e = Cases.size(); i != e; ++i) 00520 if (Cases[i].second == BB) { 00521 Cases.erase(Cases.begin()+i); 00522 --i; --e; 00523 } 00524 } 00525 00526 // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as 00527 // well. 00528 static bool 00529 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1, 00530 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) { 00531 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2; 00532 00533 // Make V1 be smaller than V2. 00534 if (V1->size() > V2->size()) 00535 std::swap(V1, V2); 00536 00537 if (V1->size() == 0) return false; 00538 if (V1->size() == 1) { 00539 // Just scan V2. 00540 ConstantInt *TheVal = (*V1)[0].first; 00541 for (unsigned i = 0, e = V2->size(); i != e; ++i) 00542 if (TheVal == (*V2)[i].first) 00543 return true; 00544 } 00545 00546 // Otherwise, just sort both lists and compare element by element. 00547 std::sort(V1->begin(), V1->end()); 00548 std::sort(V2->begin(), V2->end()); 00549 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); 00550 while (i1 != e1 && i2 != e2) { 00551 if ((*V1)[i1].first == (*V2)[i2].first) 00552 return true; 00553 if ((*V1)[i1].first < (*V2)[i2].first) 00554 ++i1; 00555 else 00556 ++i2; 00557 } 00558 return false; 00559 } 00560 00561 // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a 00562 // terminator instruction and its block is known to only have a single 00563 // predecessor block, check to see if that predecessor is also a value 00564 // comparison with the same value, and if that comparison determines the outcome 00565 // of this comparison. If so, simplify TI. This does a very limited form of 00566 // jump threading. 00567 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, 00568 BasicBlock *Pred) { 00569 Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); 00570 if (!PredVal) return false; // Not a value comparison in predecessor. 00571 00572 Value *ThisVal = isValueEqualityComparison(TI); 00573 assert(ThisVal && "This isn't a value comparison!!"); 00574 if (ThisVal != PredVal) return false; // Different predicates. 00575 00576 // Find out information about when control will move from Pred to TI's block. 00577 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases; 00578 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), 00579 PredCases); 00580 EliminateBlockCases(PredDef, PredCases); // Remove default from cases. 00581 00582 // Find information about how control leaves this block. 00583 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases; 00584 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); 00585 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. 00586 00587 // If TI's block is the default block from Pred's comparison, potentially 00588 // simplify TI based on this knowledge. 00589 if (PredDef == TI->getParent()) { 00590 // If we are here, we know that the value is none of those cases listed in 00591 // PredCases. If there are any cases in ThisCases that are in PredCases, we 00592 // can simplify TI. 00593 if (ValuesOverlap(PredCases, ThisCases)) { 00594 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) { 00595 // Okay, one of the successors of this condbr is dead. Convert it to a 00596 // uncond br. 00597 assert(ThisCases.size() == 1 && "Branch can only have one case!"); 00598 Value *Cond = BTI->getCondition(); 00599 // Insert the new branch. 00600 Instruction *NI = new BranchInst(ThisDef, TI); 00601 00602 // Remove PHI node entries for the dead edge. 00603 ThisCases[0].second->removePredecessor(TI->getParent()); 00604 00605 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator() 00606 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); 00607 00608 TI->eraseFromParent(); // Nuke the old one. 00609 // If condition is now dead, nuke it. 00610 if (Instruction *CondI = dyn_cast<Instruction>(Cond)) 00611 ErasePossiblyDeadInstructionTree(CondI); 00612 return true; 00613 00614 } else { 00615 SwitchInst *SI = cast<SwitchInst>(TI); 00616 // Okay, TI has cases that are statically dead, prune them away. 00617 std::set<Constant*> DeadCases; 00618 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00619 DeadCases.insert(PredCases[i].first); 00620 00621 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator() 00622 << "Through successor TI: " << *TI); 00623 00624 for (unsigned i = SI->getNumCases()-1; i != 0; --i) 00625 if (DeadCases.count(SI->getCaseValue(i))) { 00626 SI->getSuccessor(i)->removePredecessor(TI->getParent()); 00627 SI->removeCase(i); 00628 } 00629 00630 DEBUG(std::cerr << "Leaving: " << *TI << "\n"); 00631 return true; 00632 } 00633 } 00634 00635 } else { 00636 // Otherwise, TI's block must correspond to some matched value. Find out 00637 // which value (or set of values) this is. 00638 ConstantInt *TIV = 0; 00639 BasicBlock *TIBB = TI->getParent(); 00640 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00641 if (PredCases[i].second == TIBB) 00642 if (TIV == 0) 00643 TIV = PredCases[i].first; 00644 else 00645 return false; // Cannot handle multiple values coming to this block. 00646 assert(TIV && "No edge from pred to succ?"); 00647 00648 // Okay, we found the one constant that our value can be if we get into TI's 00649 // BB. Find out which successor will unconditionally be branched to. 00650 BasicBlock *TheRealDest = 0; 00651 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) 00652 if (ThisCases[i].first == TIV) { 00653 TheRealDest = ThisCases[i].second; 00654 break; 00655 } 00656 00657 // If not handled by any explicit cases, it is handled by the default case. 00658 if (TheRealDest == 0) TheRealDest = ThisDef; 00659 00660 // Remove PHI node entries for dead edges. 00661 BasicBlock *CheckEdge = TheRealDest; 00662 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) 00663 if (*SI != CheckEdge) 00664 (*SI)->removePredecessor(TIBB); 00665 else 00666 CheckEdge = 0; 00667 00668 // Insert the new branch. 00669 Instruction *NI = new BranchInst(TheRealDest, TI); 00670 00671 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator() 00672 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); 00673 Instruction *Cond = 0; 00674 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 00675 Cond = dyn_cast<Instruction>(BI->getCondition()); 00676 TI->eraseFromParent(); // Nuke the old one. 00677 00678 if (Cond) ErasePossiblyDeadInstructionTree(Cond); 00679 return true; 00680 } 00681 return false; 00682 } 00683 00684 // FoldValueComparisonIntoPredecessors - The specified terminator is a value 00685 // equality comparison instruction (either a switch or a branch on "X == c"). 00686 // See if any of the predecessors of the terminator block are value comparisons 00687 // on the same value. If so, and if safe to do so, fold them together. 00688 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) { 00689 BasicBlock *BB = TI->getParent(); 00690 Value *CV = isValueEqualityComparison(TI); // CondVal 00691 assert(CV && "Not a comparison?"); 00692 bool Changed = false; 00693 00694 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); 00695 while (!Preds.empty()) { 00696 BasicBlock *Pred = Preds.back(); 00697 Preds.pop_back(); 00698 00699 // See if the predecessor is a comparison with the same value. 00700 TerminatorInst *PTI = Pred->getTerminator(); 00701 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal 00702 00703 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { 00704 // Figure out which 'cases' to copy from SI to PSI. 00705 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases; 00706 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); 00707 00708 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases; 00709 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); 00710 00711 // Based on whether the default edge from PTI goes to BB or not, fill in 00712 // PredCases and PredDefault with the new switch cases we would like to 00713 // build. 00714 std::vector<BasicBlock*> NewSuccessors; 00715 00716 if (PredDefault == BB) { 00717 // If this is the default destination from PTI, only the edges in TI 00718 // that don't occur in PTI, or that branch to BB will be activated. 00719 std::set<ConstantInt*> PTIHandled; 00720 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00721 if (PredCases[i].second != BB) 00722 PTIHandled.insert(PredCases[i].first); 00723 else { 00724 // The default destination is BB, we don't need explicit targets. 00725 std::swap(PredCases[i], PredCases.back()); 00726 PredCases.pop_back(); 00727 --i; --e; 00728 } 00729 00730 // Reconstruct the new switch statement we will be building. 00731 if (PredDefault != BBDefault) { 00732 PredDefault->removePredecessor(Pred); 00733 PredDefault = BBDefault; 00734 NewSuccessors.push_back(BBDefault); 00735 } 00736 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 00737 if (!PTIHandled.count(BBCases[i].first) && 00738 BBCases[i].second != BBDefault) { 00739 PredCases.push_back(BBCases[i]); 00740 NewSuccessors.push_back(BBCases[i].second); 00741 } 00742 00743 } else { 00744 // If this is not the default destination from PSI, only the edges 00745 // in SI that occur in PSI with a destination of BB will be 00746 // activated. 00747 std::set<ConstantInt*> PTIHandled; 00748 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00749 if (PredCases[i].second == BB) { 00750 PTIHandled.insert(PredCases[i].first); 00751 std::swap(PredCases[i], PredCases.back()); 00752 PredCases.pop_back(); 00753 --i; --e; 00754 } 00755 00756 // Okay, now we know which constants were sent to BB from the 00757 // predecessor. Figure out where they will all go now. 00758 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 00759 if (PTIHandled.count(BBCases[i].first)) { 00760 // If this is one we are capable of getting... 00761 PredCases.push_back(BBCases[i]); 00762 NewSuccessors.push_back(BBCases[i].second); 00763 PTIHandled.erase(BBCases[i].first);// This constant is taken care of 00764 } 00765 00766 // If there are any constants vectored to BB that TI doesn't handle, 00767 // they must go to the default destination of TI. 00768 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(), 00769 E = PTIHandled.end(); I != E; ++I) { 00770 PredCases.push_back(std::make_pair(*I, BBDefault)); 00771 NewSuccessors.push_back(BBDefault); 00772 } 00773 } 00774 00775 // Okay, at this point, we know which new successor Pred will get. Make 00776 // sure we update the number of entries in the PHI nodes for these 00777 // successors. 00778 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i) 00779 AddPredecessorToBlock(NewSuccessors[i], Pred, BB); 00780 00781 // Now that the successors are updated, create the new Switch instruction. 00782 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI); 00783 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 00784 NewSI->addCase(PredCases[i].first, PredCases[i].second); 00785 00786 Instruction *DeadCond = 0; 00787 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) 00788 // If PTI is a branch, remember the condition. 00789 DeadCond = dyn_cast<Instruction>(BI->getCondition()); 00790 Pred->getInstList().erase(PTI); 00791 00792 // If the condition is dead now, remove the instruction tree. 00793 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond); 00794 00795 // Okay, last check. If BB is still a successor of PSI, then we must 00796 // have an infinite loop case. If so, add an infinitely looping block 00797 // to handle the case to preserve the behavior of the code. 00798 BasicBlock *InfLoopBlock = 0; 00799 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) 00800 if (NewSI->getSuccessor(i) == BB) { 00801 if (InfLoopBlock == 0) { 00802 // Insert it at the end of the loop, because it's either code, 00803 // or it won't matter if it's hot. :) 00804 InfLoopBlock = new BasicBlock("infloop", BB->getParent()); 00805 new BranchInst(InfLoopBlock, InfLoopBlock); 00806 } 00807 NewSI->setSuccessor(i, InfLoopBlock); 00808 } 00809 00810 Changed = true; 00811 } 00812 } 00813 return Changed; 00814 } 00815 00816 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and 00817 /// BB2, hoist any common code in the two blocks up into the branch block. The 00818 /// caller of this function guarantees that BI's block dominates BB1 and BB2. 00819 static bool HoistThenElseCodeToIf(BranchInst *BI) { 00820 // This does very trivial matching, with limited scanning, to find identical 00821 // instructions in the two blocks. In particular, we don't want to get into 00822 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As 00823 // such, we currently just scan for obviously identical instructions in an 00824 // identical order. 00825 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. 00826 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination 00827 00828 Instruction *I1 = BB1->begin(), *I2 = BB2->begin(); 00829 if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2) || 00830 isa<PHINode>(I1)) 00831 return false; 00832 00833 // If we get here, we can hoist at least one instruction. 00834 BasicBlock *BIParent = BI->getParent(); 00835 00836 do { 00837 // If we are hoisting the terminator instruction, don't move one (making a 00838 // broken BB), instead clone it, and remove BI. 00839 if (isa<TerminatorInst>(I1)) 00840 goto HoistTerminator; 00841 00842 // For a normal instruction, we just move one to right before the branch, 00843 // then replace all uses of the other with the first. Finally, we remove 00844 // the now redundant second instruction. 00845 BIParent->getInstList().splice(BI, BB1->getInstList(), I1); 00846 if (!I2->use_empty()) 00847 I2->replaceAllUsesWith(I1); 00848 BB2->getInstList().erase(I2); 00849 00850 I1 = BB1->begin(); 00851 I2 = BB2->begin(); 00852 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2)); 00853 00854 return true; 00855 00856 HoistTerminator: 00857 // Okay, it is safe to hoist the terminator. 00858 Instruction *NT = I1->clone(); 00859 BIParent->getInstList().insert(BI, NT); 00860 if (NT->getType() != Type::VoidTy) { 00861 I1->replaceAllUsesWith(NT); 00862 I2->replaceAllUsesWith(NT); 00863 NT->setName(I1->getName()); 00864 } 00865 00866 // Hoisting one of the terminators from our successor is a great thing. 00867 // Unfortunately, the successors of the if/else blocks may have PHI nodes in 00868 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI 00869 // nodes, so we insert select instruction to compute the final result. 00870 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; 00871 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { 00872 PHINode *PN; 00873 for (BasicBlock::iterator BBI = SI->begin(); 00874 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 00875 Value *BB1V = PN->getIncomingValueForBlock(BB1); 00876 Value *BB2V = PN->getIncomingValueForBlock(BB2); 00877 if (BB1V != BB2V) { 00878 // These values do not agree. Insert a select instruction before NT 00879 // that determines the right value. 00880 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; 00881 if (SI == 0) 00882 SI = new SelectInst(BI->getCondition(), BB1V, BB2V, 00883 BB1V->getName()+"."+BB2V->getName(), NT); 00884 // Make the PHI node use the select for all incoming values for BB1/BB2 00885 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00886 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) 00887 PN->setIncomingValue(i, SI); 00888 } 00889 } 00890 } 00891 00892 // Update any PHI nodes in our new successors. 00893 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) 00894 AddPredecessorToBlock(*SI, BIParent, BB1); 00895 00896 BI->eraseFromParent(); 00897 return true; 00898 } 00899 00900 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch 00901 /// across this block. 00902 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { 00903 BranchInst *BI = cast<BranchInst>(BB->getTerminator()); 00904 unsigned Size = 0; 00905 00906 // If this basic block contains anything other than a PHI (which controls the 00907 // branch) and branch itself, bail out. FIXME: improve this in the future. 00908 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) { 00909 if (Size > 10) return false; // Don't clone large BB's. 00910 00911 // We can only support instructions that are do not define values that are 00912 // live outside of the current basic block. 00913 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end(); 00914 UI != E; ++UI) { 00915 Instruction *U = cast<Instruction>(*UI); 00916 if (U->getParent() != BB || isa<PHINode>(U)) return false; 00917 } 00918 00919 // Looks ok, continue checking. 00920 } 00921 00922 return true; 00923 } 00924 00925 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value 00926 /// that is defined in the same block as the branch and if any PHI entries are 00927 /// constants, thread edges corresponding to that entry to be branches to their 00928 /// ultimate destination. 00929 static bool FoldCondBranchOnPHI(BranchInst *BI) { 00930 BasicBlock *BB = BI->getParent(); 00931 PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); 00932 // NOTE: we currently cannot transform this case if the PHI node is used 00933 // outside of the block. 00934 if (!PN || PN->getParent() != BB || !PN->hasOneUse()) 00935 return false; 00936 00937 // Degenerate case of a single entry PHI. 00938 if (PN->getNumIncomingValues() == 1) { 00939 if (PN->getIncomingValue(0) != PN) 00940 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 00941 else 00942 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 00943 PN->eraseFromParent(); 00944 return true; 00945 } 00946 00947 // Now we know that this block has multiple preds and two succs. 00948 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false; 00949 00950 // Okay, this is a simple enough basic block. See if any phi values are 00951 // constants. 00952 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00953 if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i))) { 00954 // Okay, we now know that all edges from PredBB should be revectored to 00955 // branch to RealDest. 00956 BasicBlock *PredBB = PN->getIncomingBlock(i); 00957 BasicBlock *RealDest = BI->getSuccessor(!CB->getValue()); 00958 00959 if (RealDest == BB) continue; // Skip self loops. 00960 00961 // The dest block might have PHI nodes, other predecessors and other 00962 // difficult cases. Instead of being smart about this, just insert a new 00963 // block that jumps to the destination block, effectively splitting 00964 // the edge we are about to create. 00965 BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge", 00966 RealDest->getParent(), RealDest); 00967 new BranchInst(RealDest, EdgeBB); 00968 PHINode *PN; 00969 for (BasicBlock::iterator BBI = RealDest->begin(); 00970 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 00971 Value *V = PN->getIncomingValueForBlock(BB); 00972 PN->addIncoming(V, EdgeBB); 00973 } 00974 00975 // BB may have instructions that are being threaded over. Clone these 00976 // instructions into EdgeBB. We know that there will be no uses of the 00977 // cloned instructions outside of EdgeBB. 00978 BasicBlock::iterator InsertPt = EdgeBB->begin(); 00979 std::map<Value*, Value*> TranslateMap; // Track translated values. 00980 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 00981 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 00982 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); 00983 } else { 00984 // Clone the instruction. 00985 Instruction *N = BBI->clone(); 00986 if (BBI->hasName()) N->setName(BBI->getName()+".c"); 00987 00988 // Update operands due to translation. 00989 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 00990 std::map<Value*, Value*>::iterator PI = 00991 TranslateMap.find(N->getOperand(i)); 00992 if (PI != TranslateMap.end()) 00993 N->setOperand(i, PI->second); 00994 } 00995 00996 // Check for trivial simplification. 00997 if (Constant *C = ConstantFoldInstruction(N)) { 00998 TranslateMap[BBI] = C; 00999 delete N; // Constant folded away, don't need actual inst 01000 } else { 01001 // Insert the new instruction into its new home. 01002 EdgeBB->getInstList().insert(InsertPt, N); 01003 if (!BBI->use_empty()) 01004 TranslateMap[BBI] = N; 01005 } 01006 } 01007 } 01008 01009 // Loop over all of the edges from PredBB to BB, changing them to branch 01010 // to EdgeBB instead. 01011 TerminatorInst *PredBBTI = PredBB->getTerminator(); 01012 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) 01013 if (PredBBTI->getSuccessor(i) == BB) { 01014 BB->removePredecessor(PredBB); 01015 PredBBTI->setSuccessor(i, EdgeBB); 01016 } 01017 01018 // Recurse, simplifying any other constants. 01019 return FoldCondBranchOnPHI(BI) | true; 01020 } 01021 01022 return false; 01023 } 01024 01025 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry 01026 /// PHI node, see if we can eliminate it. 01027 static bool FoldTwoEntryPHINode(PHINode *PN) { 01028 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 01029 // statement", which has a very simple dominance structure. Basically, we 01030 // are trying to find the condition that is being branched on, which 01031 // subsequently causes this merge to happen. We really want control 01032 // dependence information for this check, but simplifycfg can't keep it up 01033 // to date, and this catches most of the cases we care about anyway. 01034 // 01035 BasicBlock *BB = PN->getParent(); 01036 BasicBlock *IfTrue, *IfFalse; 01037 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); 01038 if (!IfCond) return false; 01039 01040 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: " 01041 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); 01042 01043 // Loop over the PHI's seeing if we can promote them all to select 01044 // instructions. While we are at it, keep track of the instructions 01045 // that need to be moved to the dominating block. 01046 std::set<Instruction*> AggressiveInsts; 01047 01048 BasicBlock::iterator AfterPHIIt = BB->begin(); 01049 while (isa<PHINode>(AfterPHIIt)) { 01050 PHINode *PN = cast<PHINode>(AfterPHIIt++); 01051 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) { 01052 if (PN->getIncomingValue(0) != PN) 01053 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 01054 else 01055 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 01056 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB, 01057 &AggressiveInsts) || 01058 !DominatesMergePoint(PN->getIncomingValue(1), BB, 01059 &AggressiveInsts)) { 01060 return false; 01061 } 01062 } 01063 01064 // If we all PHI nodes are promotable, check to make sure that all 01065 // instructions in the predecessor blocks can be promoted as well. If 01066 // not, we won't be able to get rid of the control flow, so it's not 01067 // worth promoting to select instructions. 01068 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0; 01069 PN = cast<PHINode>(BB->begin()); 01070 BasicBlock *Pred = PN->getIncomingBlock(0); 01071 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) { 01072 IfBlock1 = Pred; 01073 DomBlock = *pred_begin(Pred); 01074 for (BasicBlock::iterator I = Pred->begin(); 01075 !isa<TerminatorInst>(I); ++I) 01076 if (!AggressiveInsts.count(I)) { 01077 // This is not an aggressive instruction that we can promote. 01078 // Because of this, we won't be able to get rid of the control 01079 // flow, so the xform is not worth it. 01080 return false; 01081 } 01082 } 01083 01084 Pred = PN->getIncomingBlock(1); 01085 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) { 01086 IfBlock2 = Pred; 01087 DomBlock = *pred_begin(Pred); 01088 for (BasicBlock::iterator I = Pred->begin(); 01089 !isa<TerminatorInst>(I); ++I) 01090 if (!AggressiveInsts.count(I)) { 01091 // This is not an aggressive instruction that we can promote. 01092 // Because of this, we won't be able to get rid of the control 01093 // flow, so the xform is not worth it. 01094 return false; 01095 } 01096 } 01097 01098 // If we can still promote the PHI nodes after this gauntlet of tests, 01099 // do all of the PHI's now. 01100 01101 // Move all 'aggressive' instructions, which are defined in the 01102 // conditional parts of the if's up to the dominating block. 01103 if (IfBlock1) { 01104 DomBlock->getInstList().splice(DomBlock->getTerminator(), 01105 IfBlock1->getInstList(), 01106 IfBlock1->begin(), 01107 IfBlock1->getTerminator()); 01108 } 01109 if (IfBlock2) { 01110 DomBlock->getInstList().splice(DomBlock->getTerminator(), 01111 IfBlock2->getInstList(), 01112 IfBlock2->begin(), 01113 IfBlock2->getTerminator()); 01114 } 01115 01116 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 01117 // Change the PHI node into a select instruction. 01118 Value *TrueVal = 01119 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); 01120 Value *FalseVal = 01121 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); 01122 01123 std::string Name = PN->getName(); PN->setName(""); 01124 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal, 01125 Name, AfterPHIIt)); 01126 BB->getInstList().erase(PN); 01127 } 01128 return true; 01129 } 01130 01131 namespace { 01132 /// ConstantIntOrdering - This class implements a stable ordering of constant 01133 /// integers that does not depend on their address. This is important for 01134 /// applications that sort ConstantInt's to ensure uniqueness. 01135 struct ConstantIntOrdering { 01136 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { 01137 return LHS->getRawValue() < RHS->getRawValue(); 01138 } 01139 }; 01140 } 01141 01142 // SimplifyCFG - This function is used to do simplification of a CFG. For 01143 // example, it adjusts branches to branches to eliminate the extra hop, it 01144 // eliminates unreachable basic blocks, and does other "peephole" optimization 01145 // of the CFG. It returns true if a modification was made. 01146 // 01147 // WARNING: The entry node of a function may not be simplified. 01148 // 01149 bool llvm::SimplifyCFG(BasicBlock *BB) { 01150 bool Changed = false; 01151 Function *M = BB->getParent(); 01152 01153 assert(BB && BB->getParent() && "Block not embedded in function!"); 01154 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 01155 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!"); 01156 01157 // Remove basic blocks that have no predecessors... which are unreachable. 01158 if (pred_begin(BB) == pred_end(BB) || 01159 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) { 01160 DEBUG(std::cerr << "Removing BB: \n" << *BB); 01161 01162 // Loop through all of our successors and make sure they know that one 01163 // of their predecessors is going away. 01164 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) 01165 SI->removePredecessor(BB); 01166 01167 while (!BB->empty()) { 01168 Instruction &I = BB->back(); 01169 // If this instruction is used, replace uses with an arbitrary 01170 // value. Because control flow can't get here, we don't care 01171 // what we replace the value with. Note that since this block is 01172 // unreachable, and all values contained within it must dominate their 01173 // uses, that all uses will eventually be removed. 01174 if (!I.use_empty()) 01175 // Make all users of this instruction use undef instead 01176 I.replaceAllUsesWith(UndefValue::get(I.getType())); 01177 01178 // Remove the instruction from the basic block 01179 BB->getInstList().pop_back(); 01180 } 01181 M->getBasicBlockList().erase(BB); 01182 return true; 01183 } 01184 01185 // Check to see if we can constant propagate this terminator instruction 01186 // away... 01187 Changed |= ConstantFoldTerminator(BB); 01188 01189 // If this is a returning block with only PHI nodes in it, fold the return 01190 // instruction into any unconditional branch predecessors. 01191 // 01192 // If any predecessor is a conditional branch that just selects among 01193 // different return values, fold the replace the branch/return with a select 01194 // and return. 01195 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 01196 BasicBlock::iterator BBI = BB->getTerminator(); 01197 if (BBI == BB->begin() || isa<PHINode>(--BBI)) { 01198 // Find predecessors that end with branches. 01199 std::vector<BasicBlock*> UncondBranchPreds; 01200 std::vector<BranchInst*> CondBranchPreds; 01201 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 01202 TerminatorInst *PTI = (*PI)->getTerminator(); 01203 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) 01204 if (BI->isUnconditional()) 01205 UncondBranchPreds.push_back(*PI); 01206 else 01207 CondBranchPreds.push_back(BI); 01208 } 01209 01210 // If we found some, do the transformation! 01211 if (!UncondBranchPreds.empty()) { 01212 while (!UncondBranchPreds.empty()) { 01213 BasicBlock *Pred = UncondBranchPreds.back(); 01214 DEBUG(std::cerr << "FOLDING: " << *BB 01215 << "INTO UNCOND BRANCH PRED: " << *Pred); 01216 UncondBranchPreds.pop_back(); 01217 Instruction *UncondBranch = Pred->getTerminator(); 01218 // Clone the return and add it to the end of the predecessor. 01219 Instruction *NewRet = RI->clone(); 01220 Pred->getInstList().push_back(NewRet); 01221 01222 // If the return instruction returns a value, and if the value was a 01223 // PHI node in "BB", propagate the right value into the return. 01224 if (NewRet->getNumOperands() == 1) 01225 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0))) 01226 if (PN->getParent() == BB) 01227 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred)); 01228 // Update any PHI nodes in the returning block to realize that we no 01229 // longer branch to them. 01230 BB->removePredecessor(Pred); 01231 Pred->getInstList().erase(UncondBranch); 01232 } 01233 01234 // If we eliminated all predecessors of the block, delete the block now. 01235 if (pred_begin(BB) == pred_end(BB)) 01236 // We know there are no successors, so just nuke the block. 01237 M->getBasicBlockList().erase(BB); 01238 01239 return true; 01240 } 01241 01242 // Check out all of the conditional branches going to this return 01243 // instruction. If any of them just select between returns, change the 01244 // branch itself into a select/return pair. 01245 while (!CondBranchPreds.empty()) { 01246 BranchInst *BI = CondBranchPreds.back(); 01247 CondBranchPreds.pop_back(); 01248 BasicBlock *TrueSucc = BI->getSuccessor(0); 01249 BasicBlock *FalseSucc = BI->getSuccessor(1); 01250 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc; 01251 01252 // Check to see if the non-BB successor is also a return block. 01253 if (isa<ReturnInst>(OtherSucc->getTerminator())) { 01254 // Check to see if there are only PHI instructions in this block. 01255 BasicBlock::iterator OSI = OtherSucc->getTerminator(); 01256 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) { 01257 // Okay, we found a branch that is going to two return nodes. If 01258 // there is no return value for this function, just change the 01259 // branch into a return. 01260 if (RI->getNumOperands() == 0) { 01261 TrueSucc->removePredecessor(BI->getParent()); 01262 FalseSucc->removePredecessor(BI->getParent()); 01263 new ReturnInst(0, BI); 01264 BI->getParent()->getInstList().erase(BI); 01265 return true; 01266 } 01267 01268 // Otherwise, figure out what the true and false return values are 01269 // so we can insert a new select instruction. 01270 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0); 01271 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0); 01272 01273 // Unwrap any PHI nodes in the return blocks. 01274 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue)) 01275 if (TVPN->getParent() == TrueSucc) 01276 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); 01277 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue)) 01278 if (FVPN->getParent() == FalseSucc) 01279 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); 01280 01281 TrueSucc->removePredecessor(BI->getParent()); 01282 FalseSucc->removePredecessor(BI->getParent()); 01283 01284 // Insert a new select instruction. 01285 Value *NewRetVal; 01286 Value *BrCond = BI->getCondition(); 01287 if (TrueValue != FalseValue) 01288 NewRetVal = new SelectInst(BrCond, TrueValue, 01289 FalseValue, "retval", BI); 01290 else 01291 NewRetVal = TrueValue; 01292 01293 DEBUG(std::cerr << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 01294 << "\n " << *BI << "Select = " << *NewRetVal 01295 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc); 01296 01297 new ReturnInst(NewRetVal, BI); 01298 BI->eraseFromParent(); 01299 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond)) 01300 if (isInstructionTriviallyDead(BrCondI)) 01301 BrCondI->eraseFromParent(); 01302 return true; 01303 } 01304 } 01305 } 01306 } 01307 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) { 01308 // Check to see if the first instruction in this block is just an unwind. 01309 // If so, replace any invoke instructions which use this as an exception 01310 // destination with call instructions, and any unconditional branch 01311 // predecessor with an unwind. 01312 // 01313 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); 01314 while (!Preds.empty()) { 01315 BasicBlock *Pred = Preds.back(); 01316 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) { 01317 if (BI->isUnconditional()) { 01318 Pred->getInstList().pop_back(); // nuke uncond branch 01319 new UnwindInst(Pred); // Use unwind. 01320 Changed = true; 01321 } 01322 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator())) 01323 if (II->getUnwindDest() == BB) { 01324 // Insert a new branch instruction before the invoke, because this 01325 // is now a fall through... 01326 BranchInst *BI = new BranchInst(II->getNormalDest(), II); 01327 Pred->getInstList().remove(II); // Take out of symbol table 01328 01329 // Insert the call now... 01330 std::vector<Value*> Args(II->op_begin()+3, II->op_end()); 01331 CallInst *CI = new CallInst(II->getCalledValue(), Args, 01332 II->getName(), BI); 01333 CI->setCallingConv(II->getCallingConv()); 01334 // If the invoke produced a value, the Call now does instead 01335 II->replaceAllUsesWith(CI); 01336 delete II; 01337 Changed = true; 01338 } 01339 01340 Preds.pop_back(); 01341 } 01342 01343 // If this block is now dead, remove it. 01344 if (pred_begin(BB) == pred_end(BB)) { 01345 // We know there are no successors, so just nuke the block. 01346 M->getBasicBlockList().erase(BB); 01347 return true; 01348 } 01349 01350 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 01351 if (isValueEqualityComparison(SI)) { 01352 // If we only have one predecessor, and if it is a branch on this value, 01353 // see if that predecessor totally determines the outcome of this switch. 01354 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 01355 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred)) 01356 return SimplifyCFG(BB) || 1; 01357 01358 // If the block only contains the switch, see if we can fold the block 01359 // away into any preds. 01360 if (SI == &BB->front()) 01361 if (FoldValueComparisonIntoPredecessors(SI)) 01362 return SimplifyCFG(BB) || 1; 01363 } 01364 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 01365 if (BI->isUnconditional()) { 01366 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes... 01367 while (isa<PHINode>(*BBI)) ++BBI; 01368 01369 BasicBlock *Succ = BI->getSuccessor(0); 01370 if (BBI->isTerminator() && // Terminator is the only non-phi instruction! 01371 Succ != BB) // Don't hurt infinite loops! 01372 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ)) 01373 return 1; 01374 01375 } else { // Conditional branch 01376 if (Value *CompVal = isValueEqualityComparison(BI)) { 01377 // If we only have one predecessor, and if it is a branch on this value, 01378 // see if that predecessor totally determines the outcome of this 01379 // switch. 01380 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 01381 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred)) 01382 return SimplifyCFG(BB) || 1; 01383 01384 // This block must be empty, except for the setcond inst, if it exists. 01385 BasicBlock::iterator I = BB->begin(); 01386 if (&*I == BI || 01387 (&*I == cast<Instruction>(BI->getCondition()) && 01388 &*++I == BI)) 01389 if (FoldValueComparisonIntoPredecessors(BI)) 01390 return SimplifyCFG(BB) | true; 01391 } 01392 01393 // If this is a branch on a phi node in the current block, thread control 01394 // through this block if any PHI node entries are constants. 01395 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 01396 if (PN->getParent() == BI->getParent()) 01397 if (FoldCondBranchOnPHI(BI)) 01398 return SimplifyCFG(BB) | true; 01399 01400 // If this basic block is ONLY a setcc and a branch, and if a predecessor 01401 // branches to us and one of our successors, fold the setcc into the 01402 // predecessor and use logical operations to pick the right destination. 01403 BasicBlock *TrueDest = BI->getSuccessor(0); 01404 BasicBlock *FalseDest = BI->getSuccessor(1); 01405 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition())) 01406 if (Cond->getParent() == BB && &BB->front() == Cond && 01407 Cond->getNext() == BI && Cond->hasOneUse() && 01408 TrueDest != BB && FalseDest != BB) 01409 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI) 01410 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 01411 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) { 01412 BasicBlock *PredBlock = *PI; 01413 if (PBI->getSuccessor(0) == FalseDest || 01414 PBI->getSuccessor(1) == TrueDest) { 01415 // Invert the predecessors condition test (xor it with true), 01416 // which allows us to write this code once. 01417 Value *NewCond = 01418 BinaryOperator::createNot(PBI->getCondition(), 01419 PBI->getCondition()->getName()+".not", PBI); 01420 PBI->setCondition(NewCond); 01421 BasicBlock *OldTrue = PBI->getSuccessor(0); 01422 BasicBlock *OldFalse = PBI->getSuccessor(1); 01423 PBI->setSuccessor(0, OldFalse); 01424 PBI->setSuccessor(1, OldTrue); 01425 } 01426 01427 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) || 01428 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) { 01429 // Clone Cond into the predecessor basic block, and or/and the 01430 // two conditions together. 01431 Instruction *New = Cond->clone(); 01432 New->setName(Cond->getName()); 01433 Cond->setName(Cond->getName()+".old"); 01434 PredBlock->getInstList().insert(PBI, New); 01435 Instruction::BinaryOps Opcode = 01436 PBI->getSuccessor(0) == TrueDest ? 01437 Instruction::Or : Instruction::And; 01438 Value *NewCond = 01439 BinaryOperator::create(Opcode, PBI->getCondition(), 01440 New, "bothcond", PBI); 01441 PBI->setCondition(NewCond); 01442 if (PBI->getSuccessor(0) == BB) { 01443 AddPredecessorToBlock(TrueDest, PredBlock, BB); 01444 PBI->setSuccessor(0, TrueDest); 01445 } 01446 if (PBI->getSuccessor(1) == BB) { 01447 AddPredecessorToBlock(FalseDest, PredBlock, BB); 01448 PBI->setSuccessor(1, FalseDest); 01449 } 01450 return SimplifyCFG(BB) | 1; 01451 } 01452 } 01453 01454 // Scan predessor blocks for conditional branchs. 01455 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 01456 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 01457 if (PBI != BI && PBI->isConditional()) { 01458 01459 // If this block ends with a branch instruction, and if there is a 01460 // predecessor that ends on a branch of the same condition, make this 01461 // conditional branch redundant. 01462 if (PBI->getCondition() == BI->getCondition() && 01463 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 01464 // Okay, the outcome of this conditional branch is statically 01465 // knowable. If this block had a single pred, handle specially. 01466 if (BB->getSinglePredecessor()) { 01467 // Turn this into a branch on constant. 01468 bool CondIsTrue = PBI->getSuccessor(0) == BB; 01469 BI->setCondition(ConstantBool::get(CondIsTrue)); 01470 return SimplifyCFG(BB); // Nuke the branch on constant. 01471 } 01472 01473 // Otherwise, if there are multiple predecessors, insert a PHI that 01474 // merges in the constant and simplify the block result. 01475 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 01476 PHINode *NewPN = new PHINode(Type::BoolTy, 01477 BI->getCondition()->getName()+".pr", 01478 BB->begin()); 01479 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 01480 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) && 01481 PBI != BI && PBI->isConditional() && 01482 PBI->getCondition() == BI->getCondition() && 01483 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 01484 bool CondIsTrue = PBI->getSuccessor(0) == BB; 01485 NewPN->addIncoming(ConstantBool::get(CondIsTrue), *PI); 01486 } else { 01487 NewPN->addIncoming(BI->getCondition(), *PI); 01488 } 01489 01490 BI->setCondition(NewPN); 01491 // This will thread the branch. 01492 return SimplifyCFG(BB) | true; 01493 } 01494 } 01495 01496 // If this is a conditional branch in an empty block, and if any 01497 // predecessors is a conditional branch to one of our destinations, 01498 // fold the conditions into logical ops and one cond br. 01499 if (&BB->front() == BI) { 01500 int PBIOp, BIOp; 01501 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 01502 PBIOp = BIOp = 0; 01503 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 01504 PBIOp = 0; BIOp = 1; 01505 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 01506 PBIOp = 1; BIOp = 0; 01507 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 01508 PBIOp = BIOp = 1; 01509 } else { 01510 PBIOp = BIOp = -1; 01511 } 01512 01513 // Check to make sure that the other destination of this branch 01514 // isn't BB itself. If so, this is an infinite loop that will 01515 // keep getting unwound. 01516 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB) 01517 PBIOp = BIOp = -1; 01518 01519 // Finally, if everything is ok, fold the branches to logical ops. 01520 if (PBIOp != -1) { 01521 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 01522 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 01523 01524 // If OtherDest *is* BB, then this is a basic block with just 01525 // a conditional branch in it, where one edge (OtherDesg) goes 01526 // back to the block. We know that the program doesn't get 01527 // stuck in the infinite loop, so the condition must be such 01528 // that OtherDest isn't branched through. Forward to CommonDest, 01529 // and avoid an infinite loop at optimizer time. 01530 if (OtherDest == BB) 01531 OtherDest = CommonDest; 01532 01533 DEBUG(std::cerr << "FOLDING BRs:" << *PBI->getParent() 01534 << "AND: " << *BI->getParent()); 01535 01536 // BI may have other predecessors. Because of this, we leave 01537 // it alone, but modify PBI. 01538 01539 // Make sure we get to CommonDest on True&True directions. 01540 Value *PBICond = PBI->getCondition(); 01541 if (PBIOp) 01542 PBICond = BinaryOperator::createNot(PBICond, 01543 PBICond->getName()+".not", 01544 PBI); 01545 Value *BICond = BI->getCondition(); 01546 if (BIOp) 01547 BICond = BinaryOperator::createNot(BICond, 01548 BICond->getName()+".not", 01549 PBI); 01550 // Merge the conditions. 01551 Value *Cond = 01552 BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI); 01553 01554 // Modify PBI to branch on the new condition to the new dests. 01555 PBI->setCondition(Cond); 01556 PBI->setSuccessor(0, CommonDest); 01557 PBI->setSuccessor(1, OtherDest); 01558 01559 // OtherDest may have phi nodes. If so, add an entry from PBI's 01560 // block that are identical to the entries for BI's block. 01561 PHINode *PN; 01562 for (BasicBlock::iterator II = OtherDest->begin(); 01563 (PN = dyn_cast<PHINode>(II)); ++II) { 01564 Value *V = PN->getIncomingValueForBlock(BB); 01565 PN->addIncoming(V, PBI->getParent()); 01566 } 01567 01568 // We know that the CommonDest already had an edge from PBI to 01569 // it. If it has PHIs though, the PHIs may have different 01570 // entries for BB and PBI's BB. If so, insert a select to make 01571 // them agree. 01572 for (BasicBlock::iterator II = CommonDest->begin(); 01573 (PN = dyn_cast<PHINode>(II)); ++II) { 01574 Value * BIV = PN->getIncomingValueForBlock(BB); 01575 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 01576 Value *PBIV = PN->getIncomingValue(PBBIdx); 01577 if (BIV != PBIV) { 01578 // Insert a select in PBI to pick the right value. 01579 Value *NV = new SelectInst(PBICond, PBIV, BIV, 01580 PBIV->getName()+".mux", PBI); 01581 PN->setIncomingValue(PBBIdx, NV); 01582 } 01583 } 01584 01585 DEBUG(std::cerr << "INTO: " << *PBI->getParent()); 01586 01587 // This basic block is probably dead. We know it has at least 01588 // one fewer predecessor. 01589 return SimplifyCFG(BB) | true; 01590 } 01591 } 01592 } 01593 } 01594 } else if (isa<UnreachableInst>(BB->getTerminator())) { 01595 // If there are any instructions immediately before the unreachable that can 01596 // be removed, do so. 01597 Instruction *Unreachable = BB->getTerminator(); 01598 while (Unreachable != BB->begin()) { 01599 BasicBlock::iterator BBI = Unreachable; 01600 --BBI; 01601 if (isa<CallInst>(BBI)) break; 01602 // Delete this instruction 01603 BB->getInstList().erase(BBI); 01604 Changed = true; 01605 } 01606 01607 // If the unreachable instruction is the first in the block, take a gander 01608 // at all of the predecessors of this instruction, and simplify them. 01609 if (&BB->front() == Unreachable) { 01610 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); 01611 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 01612 TerminatorInst *TI = Preds[i]->getTerminator(); 01613 01614 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 01615 if (BI->isUnconditional()) { 01616 if (BI->getSuccessor(0) == BB) { 01617 new UnreachableInst(TI); 01618 TI->eraseFromParent(); 01619 Changed = true; 01620 } 01621 } else { 01622 if (BI->getSuccessor(0) == BB) { 01623 new BranchInst(BI->getSuccessor(1), BI); 01624 BI->eraseFromParent(); 01625 } else if (BI->getSuccessor(1) == BB) { 01626 new BranchInst(BI->getSuccessor(0), BI); 01627 BI->eraseFromParent(); 01628 Changed = true; 01629 } 01630 } 01631 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 01632 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) 01633 if (SI->getSuccessor(i) == BB) { 01634 BB->removePredecessor(SI->getParent()); 01635 SI->removeCase(i); 01636 --i; --e; 01637 Changed = true; 01638 } 01639 // If the default value is unreachable, figure out the most popular 01640 // destination and make it the default. 01641 if (SI->getSuccessor(0) == BB) { 01642 std::map<BasicBlock*, unsigned> Popularity; 01643 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) 01644 Popularity[SI->getSuccessor(i)]++; 01645 01646 // Find the most popular block. 01647 unsigned MaxPop = 0; 01648 BasicBlock *MaxBlock = 0; 01649 for (std::map<BasicBlock*, unsigned>::iterator 01650 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) { 01651 if (I->second > MaxPop) { 01652 MaxPop = I->second; 01653 MaxBlock = I->first; 01654 } 01655 } 01656 if (MaxBlock) { 01657 // Make this the new default, allowing us to delete any explicit 01658 // edges to it. 01659 SI->setSuccessor(0, MaxBlock); 01660 Changed = true; 01661 01662 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from 01663 // it. 01664 if (isa<PHINode>(MaxBlock->begin())) 01665 for (unsigned i = 0; i != MaxPop-1; ++i) 01666 MaxBlock->removePredecessor(SI->getParent()); 01667 01668 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) 01669 if (SI->getSuccessor(i) == MaxBlock) { 01670 SI->removeCase(i); 01671 --i; --e; 01672 } 01673 } 01674 } 01675 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { 01676 if (II->getUnwindDest() == BB) { 01677 // Convert the invoke to a call instruction. This would be a good 01678 // place to note that the call does not throw though. 01679 BranchInst *BI = new BranchInst(II->getNormalDest(), II); 01680 II->removeFromParent(); // Take out of symbol table 01681 01682 // Insert the call now... 01683 std::vector<Value*> Args(II->op_begin()+3, II->op_end()); 01684 CallInst *CI = new CallInst(II->getCalledValue(), Args, 01685 II->getName(), BI); 01686 CI->setCallingConv(II->getCallingConv()); 01687 // If the invoke produced a value, the Call does now instead. 01688 II->replaceAllUsesWith(CI); 01689 delete II; 01690 Changed = true; 01691 } 01692 } 01693 } 01694 01695 // If this block is now dead, remove it. 01696 if (pred_begin(BB) == pred_end(BB)) { 01697 // We know there are no successors, so just nuke the block. 01698 M->getBasicBlockList().erase(BB); 01699 return true; 01700 } 01701 } 01702 } 01703 01704 // Merge basic blocks into their predecessor if there is only one distinct 01705 // pred, and if there is only one distinct successor of the predecessor, and 01706 // if there are no PHI nodes. 01707 // 01708 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB)); 01709 BasicBlock *OnlyPred = *PI++; 01710 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same 01711 if (*PI != OnlyPred) { 01712 OnlyPred = 0; // There are multiple different predecessors... 01713 break; 01714 } 01715 01716 BasicBlock *OnlySucc = 0; 01717 if (OnlyPred && OnlyPred != BB && // Don't break self loops 01718 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) { 01719 // Check to see if there is only one distinct successor... 01720 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred)); 01721 OnlySucc = BB; 01722 for (; SI != SE; ++SI) 01723 if (*SI != OnlySucc) { 01724 OnlySucc = 0; // There are multiple distinct successors! 01725 break; 01726 } 01727 } 01728 01729 if (OnlySucc) { 01730 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred); 01731 TerminatorInst *Term = OnlyPred->getTerminator(); 01732 01733 // Resolve any PHI nodes at the start of the block. They are all 01734 // guaranteed to have exactly one entry if they exist, unless there are 01735 // multiple duplicate (but guaranteed to be equal) entries for the 01736 // incoming edges. This occurs when there are multiple edges from 01737 // OnlyPred to OnlySucc. 01738 // 01739 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) { 01740 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 01741 BB->getInstList().pop_front(); // Delete the phi node... 01742 } 01743 01744 // Delete the unconditional branch from the predecessor... 01745 OnlyPred->getInstList().pop_back(); 01746 01747 // Move all definitions in the successor to the predecessor... 01748 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList()); 01749 01750 // Make all PHI nodes that referred to BB now refer to Pred as their 01751 // source... 01752 BB->replaceAllUsesWith(OnlyPred); 01753 01754 std::string OldName = BB->getName(); 01755 01756 // Erase basic block from the function... 01757 M->getBasicBlockList().erase(BB); 01758 01759 // Inherit predecessors name if it exists... 01760 if (!OldName.empty() && !OnlyPred->hasName()) 01761 OnlyPred->setName(OldName); 01762 01763 return true; 01764 } 01765 01766 // Otherwise, if this block only has a single predecessor, and if that block 01767 // is a conditional branch, see if we can hoist any code from this block up 01768 // into our predecessor. 01769 if (OnlyPred) 01770 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator())) 01771 if (BI->isConditional()) { 01772 // Get the other block. 01773 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB); 01774 PI = pred_begin(OtherBB); 01775 ++PI; 01776 if (PI == pred_end(OtherBB)) { 01777 // We have a conditional branch to two blocks that are only reachable 01778 // from the condbr. We know that the condbr dominates the two blocks, 01779 // so see if there is any identical code in the "then" and "else" 01780 // blocks. If so, we can hoist it up to the branching block. 01781 Changed |= HoistThenElseCodeToIf(BI); 01782 } 01783 } 01784 01785 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 01786 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator())) 01787 // Change br (X == 0 | X == 1), T, F into a switch instruction. 01788 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) { 01789 Instruction *Cond = cast<Instruction>(BI->getCondition()); 01790 // If this is a bunch of seteq's or'd together, or if it's a bunch of 01791 // 'setne's and'ed together, collect them. 01792 Value *CompVal = 0; 01793 std::vector<ConstantInt*> Values; 01794 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values); 01795 if (CompVal && CompVal->getType()->isInteger()) { 01796 // There might be duplicate constants in the list, which the switch 01797 // instruction can't handle, remove them now. 01798 std::sort(Values.begin(), Values.end(), ConstantIntOrdering()); 01799 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 01800 01801 // Figure out which block is which destination. 01802 BasicBlock *DefaultBB = BI->getSuccessor(1); 01803 BasicBlock *EdgeBB = BI->getSuccessor(0); 01804 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); 01805 01806 // Create the new switch instruction now. 01807 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI); 01808 01809 // Add all of the 'cases' to the switch instruction. 01810 for (unsigned i = 0, e = Values.size(); i != e; ++i) 01811 New->addCase(Values[i], EdgeBB); 01812 01813 // We added edges from PI to the EdgeBB. As such, if there were any 01814 // PHI nodes in EdgeBB, they need entries to be added corresponding to 01815 // the number of edges added. 01816 for (BasicBlock::iterator BBI = EdgeBB->begin(); 01817 isa<PHINode>(BBI); ++BBI) { 01818 PHINode *PN = cast<PHINode>(BBI); 01819 Value *InVal = PN->getIncomingValueForBlock(*PI); 01820 for (unsigned i = 0, e = Values.size()-1; i != e; ++i) 01821 PN->addIncoming(InVal, *PI); 01822 } 01823 01824 // Erase the old branch instruction. 01825 (*PI)->getInstList().erase(BI); 01826 01827 // Erase the potentially condition tree that was used to computed the 01828 // branch condition. 01829 ErasePossiblyDeadInstructionTree(Cond); 01830 return true; 01831 } 01832 } 01833 01834 // If there is a trivial two-entry PHI node in this basic block, and we can 01835 // eliminate it, do so now. 01836 if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) 01837 if (PN->getNumIncomingValues() == 2) 01838 Changed |= FoldTwoEntryPHINode(PN); 01839 01840 return Changed; 01841 }