LLVM API Documentation
00001 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements sparse conditional constant propagation and merging: 00011 // 00012 // Specifically, this: 00013 // * Assumes values are constant unless proven otherwise 00014 // * Assumes BasicBlocks are dead unless proven otherwise 00015 // * Proves values to be constant, and replaces them with constants 00016 // * Proves conditional branches to be unconditional 00017 // 00018 // Notice that: 00019 // * This pass has a habit of making definitions be dead. It is a good idea 00020 // to to run a DCE pass sometime after running this pass. 00021 // 00022 //===----------------------------------------------------------------------===// 00023 00024 #define DEBUG_TYPE "sccp" 00025 #include "llvm/Transforms/Scalar.h" 00026 #include "llvm/Transforms/IPO.h" 00027 #include "llvm/Constants.h" 00028 #include "llvm/DerivedTypes.h" 00029 #include "llvm/Instructions.h" 00030 #include "llvm/Pass.h" 00031 #include "llvm/Analysis/ConstantFolding.h" 00032 #include "llvm/Analysis/ValueTracking.h" 00033 #include "llvm/Transforms/Utils/Local.h" 00034 #include "llvm/Support/CallSite.h" 00035 #include "llvm/Support/Compiler.h" 00036 #include "llvm/Support/Debug.h" 00037 #include "llvm/Support/InstVisitor.h" 00038 #include "llvm/ADT/DenseMap.h" 00039 #include "llvm/ADT/DenseSet.h" 00040 #include "llvm/ADT/SmallSet.h" 00041 #include "llvm/ADT/SmallVector.h" 00042 #include "llvm/ADT/Statistic.h" 00043 #include "llvm/ADT/STLExtras.h" 00044 #include <algorithm> 00045 #include <map> 00046 using namespace llvm; 00047 00048 STATISTIC(NumInstRemoved, "Number of instructions removed"); 00049 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable"); 00050 00051 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP"); 00052 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP"); 00053 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP"); 00054 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP"); 00055 00056 namespace { 00057 /// LatticeVal class - This class represents the different lattice values that 00058 /// an LLVM value may occupy. It is a simple class with value semantics. 00059 /// 00060 class VISIBILITY_HIDDEN LatticeVal { 00061 enum { 00062 /// undefined - This LLVM Value has no known value yet. 00063 undefined, 00064 00065 /// constant - This LLVM Value has a specific constant value. 00066 constant, 00067 00068 /// forcedconstant - This LLVM Value was thought to be undef until 00069 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged 00070 /// with another (different) constant, it goes to overdefined, instead of 00071 /// asserting. 00072 forcedconstant, 00073 00074 /// overdefined - This instruction is not known to be constant, and we know 00075 /// it has a value. 00076 overdefined 00077 } LatticeValue; // The current lattice position 00078 00079 Constant *ConstantVal; // If Constant value, the current value 00080 public: 00081 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {} 00082 00083 // markOverdefined - Return true if this is a new status to be in... 00084 inline bool markOverdefined() { 00085 if (LatticeValue != overdefined) { 00086 LatticeValue = overdefined; 00087 return true; 00088 } 00089 return false; 00090 } 00091 00092 // markConstant - Return true if this is a new status for us. 00093 inline bool markConstant(Constant *V) { 00094 if (LatticeValue != constant) { 00095 if (LatticeValue == undefined) { 00096 LatticeValue = constant; 00097 assert(V && "Marking constant with NULL"); 00098 ConstantVal = V; 00099 } else { 00100 assert(LatticeValue == forcedconstant && 00101 "Cannot move from overdefined to constant!"); 00102 // Stay at forcedconstant if the constant is the same. 00103 if (V == ConstantVal) return false; 00104 00105 // Otherwise, we go to overdefined. Assumptions made based on the 00106 // forced value are possibly wrong. Assuming this is another constant 00107 // could expose a contradiction. 00108 LatticeValue = overdefined; 00109 } 00110 return true; 00111 } else { 00112 assert(ConstantVal == V && "Marking constant with different value"); 00113 } 00114 return false; 00115 } 00116 00117 inline void markForcedConstant(Constant *V) { 00118 assert(LatticeValue == undefined && "Can't force a defined value!"); 00119 LatticeValue = forcedconstant; 00120 ConstantVal = V; 00121 } 00122 00123 inline bool isUndefined() const { return LatticeValue == undefined; } 00124 inline bool isConstant() const { 00125 return LatticeValue == constant || LatticeValue == forcedconstant; 00126 } 00127 inline bool isOverdefined() const { return LatticeValue == overdefined; } 00128 00129 inline Constant *getConstant() const { 00130 assert(isConstant() && "Cannot get the constant of a non-constant!"); 00131 return ConstantVal; 00132 } 00133 }; 00134 00135 //===----------------------------------------------------------------------===// 00136 // 00137 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional 00138 /// Constant Propagation. 00139 /// 00140 class SCCPSolver : public InstVisitor<SCCPSolver> { 00141 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable 00142 std::map<Value*, LatticeVal> ValueState; // The state each value is in. 00143 00144 /// GlobalValue - If we are tracking any values for the contents of a global 00145 /// variable, we keep a mapping from the constant accessor to the element of 00146 /// the global, to the currently known value. If the value becomes 00147 /// overdefined, it's entry is simply removed from this map. 00148 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals; 00149 00150 /// TrackedRetVals - If we are tracking arguments into and the return 00151 /// value out of a function, it will have an entry in this map, indicating 00152 /// what the known return value for the function is. 00153 DenseMap<Function*, LatticeVal> TrackedRetVals; 00154 00155 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions 00156 /// that return multiple values. 00157 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals; 00158 00159 // The reason for two worklists is that overdefined is the lowest state 00160 // on the lattice, and moving things to overdefined as fast as possible 00161 // makes SCCP converge much faster. 00162 // By having a separate worklist, we accomplish this because everything 00163 // possibly overdefined will become overdefined at the soonest possible 00164 // point. 00165 SmallVector<Value*, 64> OverdefinedInstWorkList; 00166 SmallVector<Value*, 64> InstWorkList; 00167 00168 00169 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list 00170 00171 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not 00172 /// overdefined, despite the fact that the PHI node is overdefined. 00173 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs; 00174 00175 /// KnownFeasibleEdges - Entries in this set are edges which have already had 00176 /// PHI nodes retriggered. 00177 typedef std::pair<BasicBlock*, BasicBlock*> Edge; 00178 DenseSet<Edge> KnownFeasibleEdges; 00179 public: 00180 00181 /// MarkBlockExecutable - This method can be used by clients to mark all of 00182 /// the blocks that are known to be intrinsically live in the processed unit. 00183 void MarkBlockExecutable(BasicBlock *BB) { 00184 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n"; 00185 BBExecutable.insert(BB); // Basic block is executable! 00186 BBWorkList.push_back(BB); // Add the block to the work list! 00187 } 00188 00189 /// TrackValueOfGlobalVariable - Clients can use this method to 00190 /// inform the SCCPSolver that it should track loads and stores to the 00191 /// specified global variable if it can. This is only legal to call if 00192 /// performing Interprocedural SCCP. 00193 void TrackValueOfGlobalVariable(GlobalVariable *GV) { 00194 const Type *ElTy = GV->getType()->getElementType(); 00195 if (ElTy->isFirstClassType()) { 00196 LatticeVal &IV = TrackedGlobals[GV]; 00197 if (!isa<UndefValue>(GV->getInitializer())) 00198 IV.markConstant(GV->getInitializer()); 00199 } 00200 } 00201 00202 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into 00203 /// and out of the specified function (which cannot have its address taken), 00204 /// this method must be called. 00205 void AddTrackedFunction(Function *F) { 00206 assert(F->hasLocalLinkage() && "Can only track internal functions!"); 00207 // Add an entry, F -> undef. 00208 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) { 00209 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 00210 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i), 00211 LatticeVal())); 00212 } else 00213 TrackedRetVals.insert(std::make_pair(F, LatticeVal())); 00214 } 00215 00216 /// Solve - Solve for constants and executable blocks. 00217 /// 00218 void Solve(); 00219 00220 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 00221 /// that branches on undef values cannot reach any of their successors. 00222 /// However, this is not a safe assumption. After we solve dataflow, this 00223 /// method should be use to handle this. If this returns true, the solver 00224 /// should be rerun. 00225 bool ResolvedUndefsIn(Function &F); 00226 00227 bool isBlockExecutable(BasicBlock *BB) const { 00228 return BBExecutable.count(BB); 00229 } 00230 00231 /// getValueMapping - Once we have solved for constants, return the mapping of 00232 /// LLVM values to LatticeVals. 00233 std::map<Value*, LatticeVal> &getValueMapping() { 00234 return ValueState; 00235 } 00236 00237 /// getTrackedRetVals - Get the inferred return value map. 00238 /// 00239 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() { 00240 return TrackedRetVals; 00241 } 00242 00243 /// getTrackedGlobals - Get and return the set of inferred initializers for 00244 /// global variables. 00245 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() { 00246 return TrackedGlobals; 00247 } 00248 00249 inline void markOverdefined(Value *V) { 00250 markOverdefined(ValueState[V], V); 00251 } 00252 00253 private: 00254 // markConstant - Make a value be marked as "constant". If the value 00255 // is not already a constant, add it to the instruction work list so that 00256 // the users of the instruction are updated later. 00257 // 00258 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) { 00259 if (IV.markConstant(C)) { 00260 DOUT << "markConstant: " << *C << ": " << *V; 00261 InstWorkList.push_back(V); 00262 } 00263 } 00264 00265 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) { 00266 IV.markForcedConstant(C); 00267 DOUT << "markForcedConstant: " << *C << ": " << *V; 00268 InstWorkList.push_back(V); 00269 } 00270 00271 inline void markConstant(Value *V, Constant *C) { 00272 markConstant(ValueState[V], V, C); 00273 } 00274 00275 // markOverdefined - Make a value be marked as "overdefined". If the 00276 // value is not already overdefined, add it to the overdefined instruction 00277 // work list so that the users of the instruction are updated later. 00278 inline void markOverdefined(LatticeVal &IV, Value *V) { 00279 if (IV.markOverdefined()) { 00280 DEBUG(DOUT << "markOverdefined: "; 00281 if (Function *F = dyn_cast<Function>(V)) 00282 DOUT << "Function '" << F->getName() << "'\n"; 00283 else 00284 DOUT << *V); 00285 // Only instructions go on the work list 00286 OverdefinedInstWorkList.push_back(V); 00287 } 00288 } 00289 00290 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) { 00291 if (IV.isOverdefined() || MergeWithV.isUndefined()) 00292 return; // Noop. 00293 if (MergeWithV.isOverdefined()) 00294 markOverdefined(IV, V); 00295 else if (IV.isUndefined()) 00296 markConstant(IV, V, MergeWithV.getConstant()); 00297 else if (IV.getConstant() != MergeWithV.getConstant()) 00298 markOverdefined(IV, V); 00299 } 00300 00301 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) { 00302 return mergeInValue(ValueState[V], V, MergeWithV); 00303 } 00304 00305 00306 // getValueState - Return the LatticeVal object that corresponds to the value. 00307 // This function is necessary because not all values should start out in the 00308 // underdefined state... Argument's should be overdefined, and 00309 // constants should be marked as constants. If a value is not known to be an 00310 // Instruction object, then use this accessor to get its value from the map. 00311 // 00312 inline LatticeVal &getValueState(Value *V) { 00313 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V); 00314 if (I != ValueState.end()) return I->second; // Common case, in the map 00315 00316 if (Constant *C = dyn_cast<Constant>(V)) { 00317 if (isa<UndefValue>(V)) { 00318 // Nothing to do, remain undefined. 00319 } else { 00320 LatticeVal &LV = ValueState[C]; 00321 LV.markConstant(C); // Constants are constant 00322 return LV; 00323 } 00324 } 00325 // All others are underdefined by default... 00326 return ValueState[V]; 00327 } 00328 00329 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB 00330 // work list if it is not already executable... 00331 // 00332 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { 00333 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) 00334 return; // This edge is already known to be executable! 00335 00336 if (BBExecutable.count(Dest)) { 00337 DOUT << "Marking Edge Executable: " << Source->getNameStart() 00338 << " -> " << Dest->getNameStart() << "\n"; 00339 00340 // The destination is already executable, but we just made an edge 00341 // feasible that wasn't before. Revisit the PHI nodes in the block 00342 // because they have potentially new operands. 00343 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) 00344 visitPHINode(*cast<PHINode>(I)); 00345 00346 } else { 00347 MarkBlockExecutable(Dest); 00348 } 00349 } 00350 00351 // getFeasibleSuccessors - Return a vector of booleans to indicate which 00352 // successors are reachable from a given terminator instruction. 00353 // 00354 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs); 00355 00356 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 00357 // block to the 'To' basic block is currently feasible... 00358 // 00359 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To); 00360 00361 // OperandChangedState - This method is invoked on all of the users of an 00362 // instruction that was just changed state somehow.... Based on this 00363 // information, we need to update the specified user of this instruction. 00364 // 00365 void OperandChangedState(User *U) { 00366 // Only instructions use other variable values! 00367 Instruction &I = cast<Instruction>(*U); 00368 if (BBExecutable.count(I.getParent())) // Inst is executable? 00369 visit(I); 00370 } 00371 00372 private: 00373 friend class InstVisitor<SCCPSolver>; 00374 00375 // visit implementations - Something changed in this instruction... Either an 00376 // operand made a transition, or the instruction is newly executable. Change 00377 // the value type of I to reflect these changes if appropriate. 00378 // 00379 void visitPHINode(PHINode &I); 00380 00381 // Terminators 00382 void visitReturnInst(ReturnInst &I); 00383 void visitTerminatorInst(TerminatorInst &TI); 00384 00385 void visitCastInst(CastInst &I); 00386 void visitSelectInst(SelectInst &I); 00387 void visitBinaryOperator(Instruction &I); 00388 void visitCmpInst(CmpInst &I); 00389 void visitExtractElementInst(ExtractElementInst &I); 00390 void visitInsertElementInst(InsertElementInst &I); 00391 void visitShuffleVectorInst(ShuffleVectorInst &I); 00392 void visitExtractValueInst(ExtractValueInst &EVI); 00393 void visitInsertValueInst(InsertValueInst &IVI); 00394 00395 // Instructions that cannot be folded away... 00396 void visitStoreInst (Instruction &I); 00397 void visitLoadInst (LoadInst &I); 00398 void visitGetElementPtrInst(GetElementPtrInst &I); 00399 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); } 00400 void visitInvokeInst (InvokeInst &II) { 00401 visitCallSite(CallSite::get(&II)); 00402 visitTerminatorInst(II); 00403 } 00404 void visitCallSite (CallSite CS); 00405 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ } 00406 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ } 00407 void visitAllocationInst(Instruction &I) { markOverdefined(&I); } 00408 void visitVANextInst (Instruction &I) { markOverdefined(&I); } 00409 void visitVAArgInst (Instruction &I) { markOverdefined(&I); } 00410 void visitFreeInst (Instruction &I) { /*returns void*/ } 00411 00412 void visitInstruction(Instruction &I) { 00413 // If a new instruction is added to LLVM that we don't handle... 00414 cerr << "SCCP: Don't know how to handle: " << I; 00415 markOverdefined(&I); // Just in case 00416 } 00417 }; 00418 00419 } // end anonymous namespace 00420 00421 00422 // getFeasibleSuccessors - Return a vector of booleans to indicate which 00423 // successors are reachable from a given terminator instruction. 00424 // 00425 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI, 00426 SmallVector<bool, 16> &Succs) { 00427 Succs.resize(TI.getNumSuccessors()); 00428 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) { 00429 if (BI->isUnconditional()) { 00430 Succs[0] = true; 00431 } else { 00432 LatticeVal &BCValue = getValueState(BI->getCondition()); 00433 if (BCValue.isOverdefined() || 00434 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) { 00435 // Overdefined condition variables, and branches on unfoldable constant 00436 // conditions, mean the branch could go either way. 00437 Succs[0] = Succs[1] = true; 00438 } else if (BCValue.isConstant()) { 00439 // Constant condition variables mean the branch can only go a single way 00440 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true; 00441 } 00442 } 00443 } else if (isa<InvokeInst>(&TI)) { 00444 // Invoke instructions successors are always executable. 00445 Succs[0] = Succs[1] = true; 00446 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) { 00447 LatticeVal &SCValue = getValueState(SI->getCondition()); 00448 if (SCValue.isOverdefined() || // Overdefined condition? 00449 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) { 00450 // All destinations are executable! 00451 Succs.assign(TI.getNumSuccessors(), true); 00452 } else if (SCValue.isConstant()) 00453 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true; 00454 } else { 00455 assert(0 && "SCCP: Don't know how to handle this terminator!"); 00456 } 00457 } 00458 00459 00460 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 00461 // block to the 'To' basic block is currently feasible... 00462 // 00463 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) { 00464 assert(BBExecutable.count(To) && "Dest should always be alive!"); 00465 00466 // Make sure the source basic block is executable!! 00467 if (!BBExecutable.count(From)) return false; 00468 00469 // Check to make sure this edge itself is actually feasible now... 00470 TerminatorInst *TI = From->getTerminator(); 00471 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 00472 if (BI->isUnconditional()) 00473 return true; 00474 else { 00475 LatticeVal &BCValue = getValueState(BI->getCondition()); 00476 if (BCValue.isOverdefined()) { 00477 // Overdefined condition variables mean the branch could go either way. 00478 return true; 00479 } else if (BCValue.isConstant()) { 00480 // Not branching on an evaluatable constant? 00481 if (!isa<ConstantInt>(BCValue.getConstant())) return true; 00482 00483 // Constant condition variables mean the branch can only go a single way 00484 return BI->getSuccessor(BCValue.getConstant() == 00485 ConstantInt::getFalse()) == To; 00486 } 00487 return false; 00488 } 00489 } else if (isa<InvokeInst>(TI)) { 00490 // Invoke instructions successors are always executable. 00491 return true; 00492 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 00493 LatticeVal &SCValue = getValueState(SI->getCondition()); 00494 if (SCValue.isOverdefined()) { // Overdefined condition? 00495 // All destinations are executable! 00496 return true; 00497 } else if (SCValue.isConstant()) { 00498 Constant *CPV = SCValue.getConstant(); 00499 if (!isa<ConstantInt>(CPV)) 00500 return true; // not a foldable constant? 00501 00502 // Make sure to skip the "default value" which isn't a value 00503 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) 00504 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch... 00505 return SI->getSuccessor(i) == To; 00506 00507 // Constant value not equal to any of the branches... must execute 00508 // default branch then... 00509 return SI->getDefaultDest() == To; 00510 } 00511 return false; 00512 } else { 00513 cerr << "Unknown terminator instruction: " << *TI; 00514 abort(); 00515 } 00516 } 00517 00518 // visit Implementations - Something changed in this instruction... Either an 00519 // operand made a transition, or the instruction is newly executable. Change 00520 // the value type of I to reflect these changes if appropriate. This method 00521 // makes sure to do the following actions: 00522 // 00523 // 1. If a phi node merges two constants in, and has conflicting value coming 00524 // from different branches, or if the PHI node merges in an overdefined 00525 // value, then the PHI node becomes overdefined. 00526 // 2. If a phi node merges only constants in, and they all agree on value, the 00527 // PHI node becomes a constant value equal to that. 00528 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 00529 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 00530 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 00531 // 6. If a conditional branch has a value that is constant, make the selected 00532 // destination executable 00533 // 7. If a conditional branch has a value that is overdefined, make all 00534 // successors executable. 00535 // 00536 void SCCPSolver::visitPHINode(PHINode &PN) { 00537 LatticeVal &PNIV = getValueState(&PN); 00538 if (PNIV.isOverdefined()) { 00539 // There may be instructions using this PHI node that are not overdefined 00540 // themselves. If so, make sure that they know that the PHI node operand 00541 // changed. 00542 std::multimap<PHINode*, Instruction*>::iterator I, E; 00543 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN); 00544 if (I != E) { 00545 SmallVector<Instruction*, 16> Users; 00546 for (; I != E; ++I) Users.push_back(I->second); 00547 while (!Users.empty()) { 00548 visit(Users.back()); 00549 Users.pop_back(); 00550 } 00551 } 00552 return; // Quick exit 00553 } 00554 00555 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, 00556 // and slow us down a lot. Just mark them overdefined. 00557 if (PN.getNumIncomingValues() > 64) { 00558 markOverdefined(PNIV, &PN); 00559 return; 00560 } 00561 00562 // Look at all of the executable operands of the PHI node. If any of them 00563 // are overdefined, the PHI becomes overdefined as well. If they are all 00564 // constant, and they agree with each other, the PHI becomes the identical 00565 // constant. If they are constant and don't agree, the PHI is overdefined. 00566 // If there are no executable operands, the PHI remains undefined. 00567 // 00568 Constant *OperandVal = 0; 00569 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 00570 LatticeVal &IV = getValueState(PN.getIncomingValue(i)); 00571 if (IV.isUndefined()) continue; // Doesn't influence PHI node. 00572 00573 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) { 00574 if (IV.isOverdefined()) { // PHI node becomes overdefined! 00575 markOverdefined(&PN); 00576 return; 00577 } 00578 00579 if (OperandVal == 0) { // Grab the first value... 00580 OperandVal = IV.getConstant(); 00581 } else { // Another value is being merged in! 00582 // There is already a reachable operand. If we conflict with it, 00583 // then the PHI node becomes overdefined. If we agree with it, we 00584 // can continue on. 00585 00586 // Check to see if there are two different constants merging... 00587 if (IV.getConstant() != OperandVal) { 00588 // Yes there is. This means the PHI node is not constant. 00589 // You must be overdefined poor PHI. 00590 // 00591 markOverdefined(&PN); // The PHI node now becomes overdefined 00592 return; // I'm done analyzing you 00593 } 00594 } 00595 } 00596 } 00597 00598 // If we exited the loop, this means that the PHI node only has constant 00599 // arguments that agree with each other(and OperandVal is the constant) or 00600 // OperandVal is null because there are no defined incoming arguments. If 00601 // this is the case, the PHI remains undefined. 00602 // 00603 if (OperandVal) 00604 markConstant(&PN, OperandVal); // Acquire operand value 00605 } 00606 00607 void SCCPSolver::visitReturnInst(ReturnInst &I) { 00608 if (I.getNumOperands() == 0) return; // Ret void 00609 00610 Function *F = I.getParent()->getParent(); 00611 // If we are tracking the return value of this function, merge it in. 00612 if (!F->hasLocalLinkage()) 00613 return; 00614 00615 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) { 00616 DenseMap<Function*, LatticeVal>::iterator TFRVI = 00617 TrackedRetVals.find(F); 00618 if (TFRVI != TrackedRetVals.end() && 00619 !TFRVI->second.isOverdefined()) { 00620 LatticeVal &IV = getValueState(I.getOperand(0)); 00621 mergeInValue(TFRVI->second, F, IV); 00622 return; 00623 } 00624 } 00625 00626 // Handle functions that return multiple values. 00627 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) { 00628 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 00629 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 00630 It = TrackedMultipleRetVals.find(std::make_pair(F, i)); 00631 if (It == TrackedMultipleRetVals.end()) break; 00632 mergeInValue(It->second, F, getValueState(I.getOperand(i))); 00633 } 00634 } else if (!TrackedMultipleRetVals.empty() && 00635 I.getNumOperands() == 1 && 00636 isa<StructType>(I.getOperand(0)->getType())) { 00637 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes(); 00638 i != e; ++i) { 00639 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 00640 It = TrackedMultipleRetVals.find(std::make_pair(F, i)); 00641 if (It == TrackedMultipleRetVals.end()) break; 00642 Value *Val = FindInsertedValue(I.getOperand(0), i); 00643 mergeInValue(It->second, F, getValueState(Val)); 00644 } 00645 } 00646 } 00647 00648 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) { 00649 SmallVector<bool, 16> SuccFeasible; 00650 getFeasibleSuccessors(TI, SuccFeasible); 00651 00652 BasicBlock *BB = TI.getParent(); 00653 00654 // Mark all feasible successors executable... 00655 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) 00656 if (SuccFeasible[i]) 00657 markEdgeExecutable(BB, TI.getSuccessor(i)); 00658 } 00659 00660 void SCCPSolver::visitCastInst(CastInst &I) { 00661 Value *V = I.getOperand(0); 00662 LatticeVal &VState = getValueState(V); 00663 if (VState.isOverdefined()) // Inherit overdefinedness of operand 00664 markOverdefined(&I); 00665 else if (VState.isConstant()) // Propagate constant value 00666 markConstant(&I, ConstantExpr::getCast(I.getOpcode(), 00667 VState.getConstant(), I.getType())); 00668 } 00669 00670 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) { 00671 Value *Aggr = EVI.getAggregateOperand(); 00672 00673 // If the operand to the extractvalue is an undef, the result is undef. 00674 if (isa<UndefValue>(Aggr)) 00675 return; 00676 00677 // Currently only handle single-index extractvalues. 00678 if (EVI.getNumIndices() != 1) { 00679 markOverdefined(&EVI); 00680 return; 00681 } 00682 00683 Function *F = 0; 00684 if (CallInst *CI = dyn_cast<CallInst>(Aggr)) 00685 F = CI->getCalledFunction(); 00686 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr)) 00687 F = II->getCalledFunction(); 00688 00689 // TODO: If IPSCCP resolves the callee of this function, we could propagate a 00690 // result back! 00691 if (F == 0 || TrackedMultipleRetVals.empty()) { 00692 markOverdefined(&EVI); 00693 return; 00694 } 00695 00696 // See if we are tracking the result of the callee. If not tracking this 00697 // function (for example, it is a declaration) just move to overdefined. 00698 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) { 00699 markOverdefined(&EVI); 00700 return; 00701 } 00702 00703 // Otherwise, the value will be merged in here as a result of CallSite 00704 // handling. 00705 } 00706 00707 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) { 00708 Value *Aggr = IVI.getAggregateOperand(); 00709 Value *Val = IVI.getInsertedValueOperand(); 00710 00711 // If the operands to the insertvalue are undef, the result is undef. 00712 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val)) 00713 return; 00714 00715 // Currently only handle single-index insertvalues. 00716 if (IVI.getNumIndices() != 1) { 00717 markOverdefined(&IVI); 00718 return; 00719 } 00720 00721 // Currently only handle insertvalue instructions that are in a single-use 00722 // chain that builds up a return value. 00723 for (const InsertValueInst *TmpIVI = &IVI; ; ) { 00724 if (!TmpIVI->hasOneUse()) { 00725 markOverdefined(&IVI); 00726 return; 00727 } 00728 const Value *V = *TmpIVI->use_begin(); 00729 if (isa<ReturnInst>(V)) 00730 break; 00731 TmpIVI = dyn_cast<InsertValueInst>(V); 00732 if (!TmpIVI) { 00733 markOverdefined(&IVI); 00734 return; 00735 } 00736 } 00737 00738 // See if we are tracking the result of the callee. 00739 Function *F = IVI.getParent()->getParent(); 00740 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 00741 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin())); 00742 00743 // Merge in the inserted member value. 00744 if (It != TrackedMultipleRetVals.end()) 00745 mergeInValue(It->second, F, getValueState(Val)); 00746 00747 // Mark the aggregate result of the IVI overdefined; any tracking that we do 00748 // will be done on the individual member values. 00749 markOverdefined(&IVI); 00750 } 00751 00752 void SCCPSolver::visitSelectInst(SelectInst &I) { 00753 LatticeVal &CondValue = getValueState(I.getCondition()); 00754 if (CondValue.isUndefined()) 00755 return; 00756 if (CondValue.isConstant()) { 00757 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){ 00758 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue() 00759 : I.getFalseValue())); 00760 return; 00761 } 00762 } 00763 00764 // Otherwise, the condition is overdefined or a constant we can't evaluate. 00765 // See if we can produce something better than overdefined based on the T/F 00766 // value. 00767 LatticeVal &TVal = getValueState(I.getTrueValue()); 00768 LatticeVal &FVal = getValueState(I.getFalseValue()); 00769 00770 // select ?, C, C -> C. 00771 if (TVal.isConstant() && FVal.isConstant() && 00772 TVal.getConstant() == FVal.getConstant()) { 00773 markConstant(&I, FVal.getConstant()); 00774 return; 00775 } 00776 00777 if (TVal.isUndefined()) { // select ?, undef, X -> X. 00778 mergeInValue(&I, FVal); 00779 } else if (FVal.isUndefined()) { // select ?, X, undef -> X. 00780 mergeInValue(&I, TVal); 00781 } else { 00782 markOverdefined(&I); 00783 } 00784 } 00785 00786 // Handle BinaryOperators and Shift Instructions... 00787 void SCCPSolver::visitBinaryOperator(Instruction &I) { 00788 LatticeVal &IV = ValueState[&I]; 00789 if (IV.isOverdefined()) return; 00790 00791 LatticeVal &V1State = getValueState(I.getOperand(0)); 00792 LatticeVal &V2State = getValueState(I.getOperand(1)); 00793 00794 if (V1State.isOverdefined() || V2State.isOverdefined()) { 00795 // If this is an AND or OR with 0 or -1, it doesn't matter that the other 00796 // operand is overdefined. 00797 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) { 00798 LatticeVal *NonOverdefVal = 0; 00799 if (!V1State.isOverdefined()) { 00800 NonOverdefVal = &V1State; 00801 } else if (!V2State.isOverdefined()) { 00802 NonOverdefVal = &V2State; 00803 } 00804 00805 if (NonOverdefVal) { 00806 if (NonOverdefVal->isUndefined()) { 00807 // Could annihilate value. 00808 if (I.getOpcode() == Instruction::And) 00809 markConstant(IV, &I, Constant::getNullValue(I.getType())); 00810 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType())) 00811 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT)); 00812 else 00813 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType())); 00814 return; 00815 } else { 00816 if (I.getOpcode() == Instruction::And) { 00817 if (NonOverdefVal->getConstant()->isNullValue()) { 00818 markConstant(IV, &I, NonOverdefVal->getConstant()); 00819 return; // X and 0 = 0 00820 } 00821 } else { 00822 if (ConstantInt *CI = 00823 dyn_cast<ConstantInt>(NonOverdefVal->getConstant())) 00824 if (CI->isAllOnesValue()) { 00825 markConstant(IV, &I, NonOverdefVal->getConstant()); 00826 return; // X or -1 = -1 00827 } 00828 } 00829 } 00830 } 00831 } 00832 00833 00834 // If both operands are PHI nodes, it is possible that this instruction has 00835 // a constant value, despite the fact that the PHI node doesn't. Check for 00836 // this condition now. 00837 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0))) 00838 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1))) 00839 if (PN1->getParent() == PN2->getParent()) { 00840 // Since the two PHI nodes are in the same basic block, they must have 00841 // entries for the same predecessors. Walk the predecessor list, and 00842 // if all of the incoming values are constants, and the result of 00843 // evaluating this expression with all incoming value pairs is the 00844 // same, then this expression is a constant even though the PHI node 00845 // is not a constant! 00846 LatticeVal Result; 00847 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) { 00848 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i)); 00849 BasicBlock *InBlock = PN1->getIncomingBlock(i); 00850 LatticeVal &In2 = 00851 getValueState(PN2->getIncomingValueForBlock(InBlock)); 00852 00853 if (In1.isOverdefined() || In2.isOverdefined()) { 00854 Result.markOverdefined(); 00855 break; // Cannot fold this operation over the PHI nodes! 00856 } else if (In1.isConstant() && In2.isConstant()) { 00857 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(), 00858 In2.getConstant()); 00859 if (Result.isUndefined()) 00860 Result.markConstant(V); 00861 else if (Result.isConstant() && Result.getConstant() != V) { 00862 Result.markOverdefined(); 00863 break; 00864 } 00865 } 00866 } 00867 00868 // If we found a constant value here, then we know the instruction is 00869 // constant despite the fact that the PHI nodes are overdefined. 00870 if (Result.isConstant()) { 00871 markConstant(IV, &I, Result.getConstant()); 00872 // Remember that this instruction is virtually using the PHI node 00873 // operands. 00874 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I)); 00875 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I)); 00876 return; 00877 } else if (Result.isUndefined()) { 00878 return; 00879 } 00880 00881 // Okay, this really is overdefined now. Since we might have 00882 // speculatively thought that this was not overdefined before, and 00883 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs, 00884 // make sure to clean out any entries that we put there, for 00885 // efficiency. 00886 std::multimap<PHINode*, Instruction*>::iterator It, E; 00887 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1); 00888 while (It != E) { 00889 if (It->second == &I) { 00890 UsersOfOverdefinedPHIs.erase(It++); 00891 } else 00892 ++It; 00893 } 00894 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2); 00895 while (It != E) { 00896 if (It->second == &I) { 00897 UsersOfOverdefinedPHIs.erase(It++); 00898 } else 00899 ++It; 00900 } 00901 } 00902 00903 markOverdefined(IV, &I); 00904 } else if (V1State.isConstant() && V2State.isConstant()) { 00905 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(), 00906 V2State.getConstant())); 00907 } 00908 } 00909 00910 // Handle ICmpInst instruction... 00911 void SCCPSolver::visitCmpInst(CmpInst &I) { 00912 LatticeVal &IV = ValueState[&I]; 00913 if (IV.isOverdefined()) return; 00914 00915 LatticeVal &V1State = getValueState(I.getOperand(0)); 00916 LatticeVal &V2State = getValueState(I.getOperand(1)); 00917 00918 if (V1State.isOverdefined() || V2State.isOverdefined()) { 00919 // If both operands are PHI nodes, it is possible that this instruction has 00920 // a constant value, despite the fact that the PHI node doesn't. Check for 00921 // this condition now. 00922 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0))) 00923 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1))) 00924 if (PN1->getParent() == PN2->getParent()) { 00925 // Since the two PHI nodes are in the same basic block, they must have 00926 // entries for the same predecessors. Walk the predecessor list, and 00927 // if all of the incoming values are constants, and the result of 00928 // evaluating this expression with all incoming value pairs is the 00929 // same, then this expression is a constant even though the PHI node 00930 // is not a constant! 00931 LatticeVal Result; 00932 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) { 00933 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i)); 00934 BasicBlock *InBlock = PN1->getIncomingBlock(i); 00935 LatticeVal &In2 = 00936 getValueState(PN2->getIncomingValueForBlock(InBlock)); 00937 00938 if (In1.isOverdefined() || In2.isOverdefined()) { 00939 Result.markOverdefined(); 00940 break; // Cannot fold this operation over the PHI nodes! 00941 } else if (In1.isConstant() && In2.isConstant()) { 00942 Constant *V = ConstantExpr::getCompare(I.getPredicate(), 00943 In1.getConstant(), 00944 In2.getConstant()); 00945 if (Result.isUndefined()) 00946 Result.markConstant(V); 00947 else if (Result.isConstant() && Result.getConstant() != V) { 00948 Result.markOverdefined(); 00949 break; 00950 } 00951 } 00952 } 00953 00954 // If we found a constant value here, then we know the instruction is 00955 // constant despite the fact that the PHI nodes are overdefined. 00956 if (Result.isConstant()) { 00957 markConstant(IV, &I, Result.getConstant()); 00958 // Remember that this instruction is virtually using the PHI node 00959 // operands. 00960 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I)); 00961 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I)); 00962 return; 00963 } else if (Result.isUndefined()) { 00964 return; 00965 } 00966 00967 // Okay, this really is overdefined now. Since we might have 00968 // speculatively thought that this was not overdefined before, and 00969 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs, 00970 // make sure to clean out any entries that we put there, for 00971 // efficiency. 00972 std::multimap<PHINode*, Instruction*>::iterator It, E; 00973 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1); 00974 while (It != E) { 00975 if (It->second == &I) { 00976 UsersOfOverdefinedPHIs.erase(It++); 00977 } else 00978 ++It; 00979 } 00980 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2); 00981 while (It != E) { 00982 if (It->second == &I) { 00983 UsersOfOverdefinedPHIs.erase(It++); 00984 } else 00985 ++It; 00986 } 00987 } 00988 00989 markOverdefined(IV, &I); 00990 } else if (V1State.isConstant() && V2State.isConstant()) { 00991 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(), 00992 V1State.getConstant(), 00993 V2State.getConstant())); 00994 } 00995 } 00996 00997 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) { 00998 // FIXME : SCCP does not handle vectors properly. 00999 markOverdefined(&I); 01000 return; 01001 01002 #if 0 01003 LatticeVal &ValState = getValueState(I.getOperand(0)); 01004 LatticeVal &IdxState = getValueState(I.getOperand(1)); 01005 01006 if (ValState.isOverdefined() || IdxState.isOverdefined()) 01007 markOverdefined(&I); 01008 else if(ValState.isConstant() && IdxState.isConstant()) 01009 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(), 01010 IdxState.getConstant())); 01011 #endif 01012 } 01013 01014 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) { 01015 // FIXME : SCCP does not handle vectors properly. 01016 markOverdefined(&I); 01017 return; 01018 #if 0 01019 LatticeVal &ValState = getValueState(I.getOperand(0)); 01020 LatticeVal &EltState = getValueState(I.getOperand(1)); 01021 LatticeVal &IdxState = getValueState(I.getOperand(2)); 01022 01023 if (ValState.isOverdefined() || EltState.isOverdefined() || 01024 IdxState.isOverdefined()) 01025 markOverdefined(&I); 01026 else if(ValState.isConstant() && EltState.isConstant() && 01027 IdxState.isConstant()) 01028 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(), 01029 EltState.getConstant(), 01030 IdxState.getConstant())); 01031 else if (ValState.isUndefined() && EltState.isConstant() && 01032 IdxState.isConstant()) 01033 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()), 01034 EltState.getConstant(), 01035 IdxState.getConstant())); 01036 #endif 01037 } 01038 01039 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) { 01040 // FIXME : SCCP does not handle vectors properly. 01041 markOverdefined(&I); 01042 return; 01043 #if 0 01044 LatticeVal &V1State = getValueState(I.getOperand(0)); 01045 LatticeVal &V2State = getValueState(I.getOperand(1)); 01046 LatticeVal &MaskState = getValueState(I.getOperand(2)); 01047 01048 if (MaskState.isUndefined() || 01049 (V1State.isUndefined() && V2State.isUndefined())) 01050 return; // Undefined output if mask or both inputs undefined. 01051 01052 if (V1State.isOverdefined() || V2State.isOverdefined() || 01053 MaskState.isOverdefined()) { 01054 markOverdefined(&I); 01055 } else { 01056 // A mix of constant/undef inputs. 01057 Constant *V1 = V1State.isConstant() ? 01058 V1State.getConstant() : UndefValue::get(I.getType()); 01059 Constant *V2 = V2State.isConstant() ? 01060 V2State.getConstant() : UndefValue::get(I.getType()); 01061 Constant *Mask = MaskState.isConstant() ? 01062 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType()); 01063 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask)); 01064 } 01065 #endif 01066 } 01067 01068 // Handle getelementptr instructions... if all operands are constants then we 01069 // can turn this into a getelementptr ConstantExpr. 01070 // 01071 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) { 01072 LatticeVal &IV = ValueState[&I]; 01073 if (IV.isOverdefined()) return; 01074 01075 SmallVector<Constant*, 8> Operands; 01076 Operands.reserve(I.getNumOperands()); 01077 01078 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 01079 LatticeVal &State = getValueState(I.getOperand(i)); 01080 if (State.isUndefined()) 01081 return; // Operands are not resolved yet... 01082 else if (State.isOverdefined()) { 01083 markOverdefined(IV, &I); 01084 return; 01085 } 01086 assert(State.isConstant() && "Unknown state!"); 01087 Operands.push_back(State.getConstant()); 01088 } 01089 01090 Constant *Ptr = Operands[0]; 01091 Operands.erase(Operands.begin()); // Erase the pointer from idx list... 01092 01093 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0], 01094 Operands.size())); 01095 } 01096 01097 void SCCPSolver::visitStoreInst(Instruction &SI) { 01098 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1))) 01099 return; 01100 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1)); 01101 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV); 01102 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return; 01103 01104 // Get the value we are storing into the global. 01105 LatticeVal &PtrVal = getValueState(SI.getOperand(0)); 01106 01107 mergeInValue(I->second, GV, PtrVal); 01108 if (I->second.isOverdefined()) 01109 TrackedGlobals.erase(I); // No need to keep tracking this! 01110 } 01111 01112 01113 // Handle load instructions. If the operand is a constant pointer to a constant 01114 // global, we can replace the load with the loaded constant value! 01115 void SCCPSolver::visitLoadInst(LoadInst &I) { 01116 LatticeVal &IV = ValueState[&I]; 01117 if (IV.isOverdefined()) return; 01118 01119 LatticeVal &PtrVal = getValueState(I.getOperand(0)); 01120 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet! 01121 if (PtrVal.isConstant() && !I.isVolatile()) { 01122 Value *Ptr = PtrVal.getConstant(); 01123 // TODO: Consider a target hook for valid address spaces for this xform. 01124 if (isa<ConstantPointerNull>(Ptr) && 01125 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) { 01126 // load null -> null 01127 markConstant(IV, &I, Constant::getNullValue(I.getType())); 01128 return; 01129 } 01130 01131 // Transform load (constant global) into the value loaded. 01132 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) { 01133 if (GV->isConstant()) { 01134 if (!GV->isDeclaration()) { 01135 markConstant(IV, &I, GV->getInitializer()); 01136 return; 01137 } 01138 } else if (!TrackedGlobals.empty()) { 01139 // If we are tracking this global, merge in the known value for it. 01140 DenseMap<GlobalVariable*, LatticeVal>::iterator It = 01141 TrackedGlobals.find(GV); 01142 if (It != TrackedGlobals.end()) { 01143 mergeInValue(IV, &I, It->second); 01144 return; 01145 } 01146 } 01147 } 01148 01149 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded. 01150 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) 01151 if (CE->getOpcode() == Instruction::GetElementPtr) 01152 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) 01153 if (GV->isConstant() && !GV->isDeclaration()) 01154 if (Constant *V = 01155 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) { 01156 markConstant(IV, &I, V); 01157 return; 01158 } 01159 } 01160 01161 // Otherwise we cannot say for certain what value this load will produce. 01162 // Bail out. 01163 markOverdefined(IV, &I); 01164 } 01165 01166 void SCCPSolver::visitCallSite(CallSite CS) { 01167 Function *F = CS.getCalledFunction(); 01168 Instruction *I = CS.getInstruction(); 01169 01170 // The common case is that we aren't tracking the callee, either because we 01171 // are not doing interprocedural analysis or the callee is indirect, or is 01172 // external. Handle these cases first. 01173 if (F == 0 || !F->hasLocalLinkage()) { 01174 CallOverdefined: 01175 // Void return and not tracking callee, just bail. 01176 if (I->getType() == Type::VoidTy) return; 01177 01178 // Otherwise, if we have a single return value case, and if the function is 01179 // a declaration, maybe we can constant fold it. 01180 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() && 01181 canConstantFoldCallTo(F)) { 01182 01183 SmallVector<Constant*, 8> Operands; 01184 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); 01185 AI != E; ++AI) { 01186 LatticeVal &State = getValueState(*AI); 01187 if (State.isUndefined()) 01188 return; // Operands are not resolved yet. 01189 else if (State.isOverdefined()) { 01190 markOverdefined(I); 01191 return; 01192 } 01193 assert(State.isConstant() && "Unknown state!"); 01194 Operands.push_back(State.getConstant()); 01195 } 01196 01197 // If we can constant fold this, mark the result of the call as a 01198 // constant. 01199 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) { 01200 markConstant(I, C); 01201 return; 01202 } 01203 } 01204 01205 // Otherwise, we don't know anything about this call, mark it overdefined. 01206 markOverdefined(I); 01207 return; 01208 } 01209 01210 // If this is a single/zero retval case, see if we're tracking the function. 01211 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F); 01212 if (TFRVI != TrackedRetVals.end()) { 01213 // If so, propagate the return value of the callee into this call result. 01214 mergeInValue(I, TFRVI->second); 01215 } else if (isa<StructType>(I->getType())) { 01216 // Check to see if we're tracking this callee, if not, handle it in the 01217 // common path above. 01218 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 01219 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0)); 01220 if (TMRVI == TrackedMultipleRetVals.end()) 01221 goto CallOverdefined; 01222 01223 // If we are tracking this callee, propagate the return values of the call 01224 // into this call site. We do this by walking all the uses. Single-index 01225 // ExtractValueInst uses can be tracked; anything more complicated is 01226 // currently handled conservatively. 01227 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 01228 UI != E; ++UI) { 01229 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) { 01230 if (EVI->getNumIndices() == 1) { 01231 mergeInValue(EVI, 01232 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]); 01233 continue; 01234 } 01235 } 01236 // The aggregate value is used in a way not handled here. Assume nothing. 01237 markOverdefined(*UI); 01238 } 01239 } else { 01240 // Otherwise we're not tracking this callee, so handle it in the 01241 // common path above. 01242 goto CallOverdefined; 01243 } 01244 01245 // Finally, if this is the first call to the function hit, mark its entry 01246 // block executable. 01247 if (!BBExecutable.count(F->begin())) 01248 MarkBlockExecutable(F->begin()); 01249 01250 // Propagate information from this call site into the callee. 01251 CallSite::arg_iterator CAI = CS.arg_begin(); 01252 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 01253 AI != E; ++AI, ++CAI) { 01254 LatticeVal &IV = ValueState[AI]; 01255 if (!IV.isOverdefined()) 01256 mergeInValue(IV, AI, getValueState(*CAI)); 01257 } 01258 } 01259 01260 01261 void SCCPSolver::Solve() { 01262 // Process the work lists until they are empty! 01263 while (!BBWorkList.empty() || !InstWorkList.empty() || 01264 !OverdefinedInstWorkList.empty()) { 01265 // Process the instruction work list... 01266 while (!OverdefinedInstWorkList.empty()) { 01267 Value *I = OverdefinedInstWorkList.back(); 01268 OverdefinedInstWorkList.pop_back(); 01269 01270 DOUT << "\nPopped off OI-WL: " << *I; 01271 01272 // "I" got into the work list because it either made the transition from 01273 // bottom to constant 01274 // 01275 // Anything on this worklist that is overdefined need not be visited 01276 // since all of its users will have already been marked as overdefined 01277 // Update all of the users of this instruction's value... 01278 // 01279 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 01280 UI != E; ++UI) 01281 OperandChangedState(*UI); 01282 } 01283 // Process the instruction work list... 01284 while (!InstWorkList.empty()) { 01285 Value *I = InstWorkList.back(); 01286 InstWorkList.pop_back(); 01287 01288 DOUT << "\nPopped off I-WL: " << *I; 01289 01290 // "I" got into the work list because it either made the transition from 01291 // bottom to constant 01292 // 01293 // Anything on this worklist that is overdefined need not be visited 01294 // since all of its users will have already been marked as overdefined. 01295 // Update all of the users of this instruction's value... 01296 // 01297 if (!getValueState(I).isOverdefined()) 01298 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 01299 UI != E; ++UI) 01300 OperandChangedState(*UI); 01301 } 01302 01303 // Process the basic block work list... 01304 while (!BBWorkList.empty()) { 01305 BasicBlock *BB = BBWorkList.back(); 01306 BBWorkList.pop_back(); 01307 01308 DOUT << "\nPopped off BBWL: " << *BB; 01309 01310 // Notify all instructions in this basic block that they are newly 01311 // executable. 01312 visit(BB); 01313 } 01314 } 01315 } 01316 01317 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 01318 /// that branches on undef values cannot reach any of their successors. 01319 /// However, this is not a safe assumption. After we solve dataflow, this 01320 /// method should be use to handle this. If this returns true, the solver 01321 /// should be rerun. 01322 /// 01323 /// This method handles this by finding an unresolved branch and marking it one 01324 /// of the edges from the block as being feasible, even though the condition 01325 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the 01326 /// CFG and only slightly pessimizes the analysis results (by marking one, 01327 /// potentially infeasible, edge feasible). This cannot usefully modify the 01328 /// constraints on the condition of the branch, as that would impact other users 01329 /// of the value. 01330 /// 01331 /// This scan also checks for values that use undefs, whose results are actually 01332 /// defined. For example, 'zext i8 undef to i32' should produce all zeros 01333 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero, 01334 /// even if X isn't defined. 01335 bool SCCPSolver::ResolvedUndefsIn(Function &F) { 01336 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 01337 if (!BBExecutable.count(BB)) 01338 continue; 01339 01340 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 01341 // Look for instructions which produce undef values. 01342 if (I->getType() == Type::VoidTy) continue; 01343 01344 LatticeVal &LV = getValueState(I); 01345 if (!LV.isUndefined()) continue; 01346 01347 // Get the lattice values of the first two operands for use below. 01348 LatticeVal &Op0LV = getValueState(I->getOperand(0)); 01349 LatticeVal Op1LV; 01350 if (I->getNumOperands() == 2) { 01351 // If this is a two-operand instruction, and if both operands are 01352 // undefs, the result stays undef. 01353 Op1LV = getValueState(I->getOperand(1)); 01354 if (Op0LV.isUndefined() && Op1LV.isUndefined()) 01355 continue; 01356 } 01357 01358 // If this is an instructions whose result is defined even if the input is 01359 // not fully defined, propagate the information. 01360 const Type *ITy = I->getType(); 01361 switch (I->getOpcode()) { 01362 default: break; // Leave the instruction as an undef. 01363 case Instruction::ZExt: 01364 // After a zero extend, we know the top part is zero. SExt doesn't have 01365 // to be handled here, because we don't know whether the top part is 1's 01366 // or 0's. 01367 assert(Op0LV.isUndefined()); 01368 markForcedConstant(LV, I, Constant::getNullValue(ITy)); 01369 return true; 01370 case Instruction::Mul: 01371 case Instruction::And: 01372 // undef * X -> 0. X could be zero. 01373 // undef & X -> 0. X could be zero. 01374 markForcedConstant(LV, I, Constant::getNullValue(ITy)); 01375 return true; 01376 01377 case Instruction::Or: 01378 // undef | X -> -1. X could be -1. 01379 if (const VectorType *PTy = dyn_cast<VectorType>(ITy)) 01380 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy)); 01381 else 01382 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy)); 01383 return true; 01384 01385 case Instruction::SDiv: 01386 case Instruction::UDiv: 01387 case Instruction::SRem: 01388 case Instruction::URem: 01389 // X / undef -> undef. No change. 01390 // X % undef -> undef. No change. 01391 if (Op1LV.isUndefined()) break; 01392 01393 // undef / X -> 0. X could be maxint. 01394 // undef % X -> 0. X could be 1. 01395 markForcedConstant(LV, I, Constant::getNullValue(ITy)); 01396 return true; 01397 01398 case Instruction::AShr: 01399 // undef >>s X -> undef. No change. 01400 if (Op0LV.isUndefined()) break; 01401 01402 // X >>s undef -> X. X could be 0, X could have the high-bit known set. 01403 if (Op0LV.isConstant()) 01404 markForcedConstant(LV, I, Op0LV.getConstant()); 01405 else 01406 markOverdefined(LV, I); 01407 return true; 01408 case Instruction::LShr: 01409 case Instruction::Shl: 01410 // undef >> X -> undef. No change. 01411 // undef << X -> undef. No change. 01412 if (Op0LV.isUndefined()) break; 01413 01414 // X >> undef -> 0. X could be 0. 01415 // X << undef -> 0. X could be 0. 01416 markForcedConstant(LV, I, Constant::getNullValue(ITy)); 01417 return true; 01418 case Instruction::Select: 01419 // undef ? X : Y -> X or Y. There could be commonality between X/Y. 01420 if (Op0LV.isUndefined()) { 01421 if (!Op1LV.isConstant()) // Pick the constant one if there is any. 01422 Op1LV = getValueState(I->getOperand(2)); 01423 } else if (Op1LV.isUndefined()) { 01424 // c ? undef : undef -> undef. No change. 01425 Op1LV = getValueState(I->getOperand(2)); 01426 if (Op1LV.isUndefined()) 01427 break; 01428 // Otherwise, c ? undef : x -> x. 01429 } else { 01430 // Leave Op1LV as Operand(1)'s LatticeValue. 01431 } 01432 01433 if (Op1LV.isConstant()) 01434 markForcedConstant(LV, I, Op1LV.getConstant()); 01435 else 01436 markOverdefined(LV, I); 01437 return true; 01438 case Instruction::Call: 01439 // If a call has an undef result, it is because it is constant foldable 01440 // but one of the inputs was undef. Just force the result to 01441 // overdefined. 01442 markOverdefined(LV, I); 01443 return true; 01444 } 01445 } 01446 01447 TerminatorInst *TI = BB->getTerminator(); 01448 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 01449 if (!BI->isConditional()) continue; 01450 if (!getValueState(BI->getCondition()).isUndefined()) 01451 continue; 01452 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 01453 if (SI->getNumSuccessors()<2) // no cases 01454 continue; 01455 if (!getValueState(SI->getCondition()).isUndefined()) 01456 continue; 01457 } else { 01458 continue; 01459 } 01460 01461 // If the edge to the second successor isn't thought to be feasible yet, 01462 // mark it so now. We pick the second one so that this goes to some 01463 // enumerated value in a switch instead of going to the default destination. 01464 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1)))) 01465 continue; 01466 01467 // Otherwise, it isn't already thought to be feasible. Mark it as such now 01468 // and return. This will make other blocks reachable, which will allow new 01469 // values to be discovered and existing ones to be moved in the lattice. 01470 markEdgeExecutable(BB, TI->getSuccessor(1)); 01471 01472 // This must be a conditional branch of switch on undef. At this point, 01473 // force the old terminator to branch to the first successor. This is 01474 // required because we are now influencing the dataflow of the function with 01475 // the assumption that this edge is taken. If we leave the branch condition 01476 // as undef, then further analysis could think the undef went another way 01477 // leading to an inconsistent set of conclusions. 01478 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 01479 BI->setCondition(ConstantInt::getFalse()); 01480 } else { 01481 SwitchInst *SI = cast<SwitchInst>(TI); 01482 SI->setCondition(SI->getCaseValue(1)); 01483 } 01484 01485 return true; 01486 } 01487 01488 return false; 01489 } 01490 01491 01492 namespace { 01493 //===--------------------------------------------------------------------===// 01494 // 01495 /// SCCP Class - This class uses the SCCPSolver to implement a per-function 01496 /// Sparse Conditional Constant Propagator. 01497 /// 01498 struct VISIBILITY_HIDDEN SCCP : public FunctionPass { 01499 static char ID; // Pass identification, replacement for typeid 01500 SCCP() : FunctionPass(&ID) {} 01501 01502 // runOnFunction - Run the Sparse Conditional Constant Propagation 01503 // algorithm, and return true if the function was modified. 01504 // 01505 bool runOnFunction(Function &F); 01506 01507 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 01508 AU.setPreservesCFG(); 01509 } 01510 }; 01511 } // end anonymous namespace 01512 01513 char SCCP::ID = 0; 01514 static RegisterPass<SCCP> 01515 X("sccp", "Sparse Conditional Constant Propagation"); 01516 01517 // createSCCPPass - This is the public interface to this file... 01518 FunctionPass *llvm::createSCCPPass() { 01519 return new SCCP(); 01520 } 01521 01522 01523 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm, 01524 // and return true if the function was modified. 01525 // 01526 bool SCCP::runOnFunction(Function &F) { 01527 DOUT << "SCCP on function '" << F.getNameStart() << "'\n"; 01528 SCCPSolver Solver; 01529 01530 // Mark the first block of the function as being executable. 01531 Solver.MarkBlockExecutable(F.begin()); 01532 01533 // Mark all arguments to the function as being overdefined. 01534 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI) 01535 Solver.markOverdefined(AI); 01536 01537 // Solve for constants. 01538 bool ResolvedUndefs = true; 01539 while (ResolvedUndefs) { 01540 Solver.Solve(); 01541 DOUT << "RESOLVING UNDEFs\n"; 01542 ResolvedUndefs = Solver.ResolvedUndefsIn(F); 01543 } 01544 01545 bool MadeChanges = false; 01546 01547 // If we decided that there are basic blocks that are dead in this function, 01548 // delete their contents now. Note that we cannot actually delete the blocks, 01549 // as we cannot modify the CFG of the function. 01550 // 01551 SmallVector<Instruction*, 512> Insts; 01552 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping(); 01553 01554 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 01555 if (!Solver.isBlockExecutable(BB)) { 01556 DOUT << " BasicBlock Dead:" << *BB; 01557 ++NumDeadBlocks; 01558 01559 // Delete the instructions backwards, as it has a reduced likelihood of 01560 // having to update as many def-use and use-def chains. 01561 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator(); 01562 I != E; ++I) 01563 Insts.push_back(I); 01564 while (!Insts.empty()) { 01565 Instruction *I = Insts.back(); 01566 Insts.pop_back(); 01567 if (!I->use_empty()) 01568 I->replaceAllUsesWith(UndefValue::get(I->getType())); 01569 BB->getInstList().erase(I); 01570 MadeChanges = true; 01571 ++NumInstRemoved; 01572 } 01573 } else { 01574 // Iterate over all of the instructions in a function, replacing them with 01575 // constants if we have found them to be of constant values. 01576 // 01577 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 01578 Instruction *Inst = BI++; 01579 if (Inst->getType() == Type::VoidTy || 01580 isa<TerminatorInst>(Inst)) 01581 continue; 01582 01583 LatticeVal &IV = Values[Inst]; 01584 if (!IV.isConstant() && !IV.isUndefined()) 01585 continue; 01586 01587 Constant *Const = IV.isConstant() 01588 ? IV.getConstant() : UndefValue::get(Inst->getType()); 01589 DOUT << " Constant: " << *Const << " = " << *Inst; 01590 01591 // Replaces all of the uses of a variable with uses of the constant. 01592 Inst->replaceAllUsesWith(Const); 01593 01594 // Delete the instruction. 01595 Inst->eraseFromParent(); 01596 01597 // Hey, we just changed something! 01598 MadeChanges = true; 01599 ++NumInstRemoved; 01600 } 01601 } 01602 01603 return MadeChanges; 01604 } 01605 01606 namespace { 01607 //===--------------------------------------------------------------------===// 01608 // 01609 /// IPSCCP Class - This class implements interprocedural Sparse Conditional 01610 /// Constant Propagation. 01611 /// 01612 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass { 01613 static char ID; 01614 IPSCCP() : ModulePass(&ID) {} 01615 bool runOnModule(Module &M); 01616 }; 01617 } // end anonymous namespace 01618 01619 char IPSCCP::ID = 0; 01620 static RegisterPass<IPSCCP> 01621 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation"); 01622 01623 // createIPSCCPPass - This is the public interface to this file... 01624 ModulePass *llvm::createIPSCCPPass() { 01625 return new IPSCCP(); 01626 } 01627 01628 01629 static bool AddressIsTaken(GlobalValue *GV) { 01630 // Delete any dead constantexpr klingons. 01631 GV->removeDeadConstantUsers(); 01632 01633 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); 01634 UI != E; ++UI) 01635 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { 01636 if (SI->getOperand(0) == GV || SI->isVolatile()) 01637 return true; // Storing addr of GV. 01638 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) { 01639 // Make sure we are calling the function, not passing the address. 01640 CallSite CS = CallSite::get(cast<Instruction>(*UI)); 01641 if (CS.hasArgument(GV)) 01642 return true; 01643 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 01644 if (LI->isVolatile()) 01645 return true; 01646 } else { 01647 return true; 01648 } 01649 return false; 01650 } 01651 01652 bool IPSCCP::runOnModule(Module &M) { 01653 SCCPSolver Solver; 01654 01655 // Loop over all functions, marking arguments to those with their addresses 01656 // taken or that are external as overdefined. 01657 // 01658 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 01659 if (!F->hasLocalLinkage() || AddressIsTaken(F)) { 01660 if (!F->isDeclaration()) 01661 Solver.MarkBlockExecutable(F->begin()); 01662 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 01663 AI != E; ++AI) 01664 Solver.markOverdefined(AI); 01665 } else { 01666 Solver.AddTrackedFunction(F); 01667 } 01668 01669 // Loop over global variables. We inform the solver about any internal global 01670 // variables that do not have their 'addresses taken'. If they don't have 01671 // their addresses taken, we can propagate constants through them. 01672 for (Module::global_iterator G = M.global_begin(), E = M.global_end(); 01673 G != E; ++G) 01674 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G)) 01675 Solver.TrackValueOfGlobalVariable(G); 01676 01677 // Solve for constants. 01678 bool ResolvedUndefs = true; 01679 while (ResolvedUndefs) { 01680 Solver.Solve(); 01681 01682 DOUT << "RESOLVING UNDEFS\n"; 01683 ResolvedUndefs = false; 01684 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 01685 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F); 01686 } 01687 01688 bool MadeChanges = false; 01689 01690 // Iterate over all of the instructions in the module, replacing them with 01691 // constants if we have found them to be of constant values. 01692 // 01693 SmallVector<Instruction*, 512> Insts; 01694 SmallVector<BasicBlock*, 512> BlocksToErase; 01695 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping(); 01696 01697 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 01698 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 01699 AI != E; ++AI) 01700 if (!AI->use_empty()) { 01701 LatticeVal &IV = Values[AI]; 01702 if (IV.isConstant() || IV.isUndefined()) { 01703 Constant *CST = IV.isConstant() ? 01704 IV.getConstant() : UndefValue::get(AI->getType()); 01705 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n"; 01706 01707 // Replaces all of the uses of a variable with uses of the 01708 // constant. 01709 AI->replaceAllUsesWith(CST); 01710 ++IPNumArgsElimed; 01711 } 01712 } 01713 01714 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 01715 if (!Solver.isBlockExecutable(BB)) { 01716 DOUT << " BasicBlock Dead:" << *BB; 01717 ++IPNumDeadBlocks; 01718 01719 // Delete the instructions backwards, as it has a reduced likelihood of 01720 // having to update as many def-use and use-def chains. 01721 TerminatorInst *TI = BB->getTerminator(); 01722 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I) 01723 Insts.push_back(I); 01724 01725 while (!Insts.empty()) { 01726 Instruction *I = Insts.back(); 01727 Insts.pop_back(); 01728 if (!I->use_empty()) 01729 I->replaceAllUsesWith(UndefValue::get(I->getType())); 01730 BB->getInstList().erase(I); 01731 MadeChanges = true; 01732 ++IPNumInstRemoved; 01733 } 01734 01735 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 01736 BasicBlock *Succ = TI->getSuccessor(i); 01737 if (!Succ->empty() && isa<PHINode>(Succ->begin())) 01738 TI->getSuccessor(i)->removePredecessor(BB); 01739 } 01740 if (!TI->use_empty()) 01741 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 01742 BB->getInstList().erase(TI); 01743 01744 if (&*BB != &F->front()) 01745 BlocksToErase.push_back(BB); 01746 else 01747 new UnreachableInst(BB); 01748 01749 } else { 01750 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 01751 Instruction *Inst = BI++; 01752 if (Inst->getType() == Type::VoidTy) 01753 continue; 01754 01755 LatticeVal &IV = Values[Inst]; 01756 if (!IV.isConstant() && !IV.isUndefined()) 01757 continue; 01758 01759 Constant *Const = IV.isConstant() 01760 ? IV.getConstant() : UndefValue::get(Inst->getType()); 01761 DOUT << " Constant: " << *Const << " = " << *Inst; 01762 01763 // Replaces all of the uses of a variable with uses of the 01764 // constant. 01765 Inst->replaceAllUsesWith(Const); 01766 01767 // Delete the instruction. 01768 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst)) 01769 Inst->eraseFromParent(); 01770 01771 // Hey, we just changed something! 01772 MadeChanges = true; 01773 ++IPNumInstRemoved; 01774 } 01775 } 01776 01777 // Now that all instructions in the function are constant folded, erase dead 01778 // blocks, because we can now use ConstantFoldTerminator to get rid of 01779 // in-edges. 01780 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) { 01781 // If there are any PHI nodes in this successor, drop entries for BB now. 01782 BasicBlock *DeadBB = BlocksToErase[i]; 01783 while (!DeadBB->use_empty()) { 01784 Instruction *I = cast<Instruction>(DeadBB->use_back()); 01785 bool Folded = ConstantFoldTerminator(I->getParent()); 01786 if (!Folded) { 01787 // The constant folder may not have been able to fold the terminator 01788 // if this is a branch or switch on undef. Fold it manually as a 01789 // branch to the first successor. 01790 #ifndef NDEBUG 01791 if (BranchInst *BI = dyn_cast<BranchInst>(I)) { 01792 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) && 01793 "Branch should be foldable!"); 01794 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 01795 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold"); 01796 } else { 01797 assert(0 && "Didn't fold away reference to block!"); 01798 } 01799 #endif 01800 01801 // Make this an uncond branch to the first successor. 01802 TerminatorInst *TI = I->getParent()->getTerminator(); 01803 BranchInst::Create(TI->getSuccessor(0), TI); 01804 01805 // Remove entries in successor phi nodes to remove edges. 01806 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i) 01807 TI->getSuccessor(i)->removePredecessor(TI->getParent()); 01808 01809 // Remove the old terminator. 01810 TI->eraseFromParent(); 01811 } 01812 } 01813 01814 // Finally, delete the basic block. 01815 F->getBasicBlockList().erase(DeadBB); 01816 } 01817 BlocksToErase.clear(); 01818 } 01819 01820 // If we inferred constant or undef return values for a function, we replaced 01821 // all call uses with the inferred value. This means we don't need to bother 01822 // actually returning anything from the function. Replace all return 01823 // instructions with return undef. 01824 // TODO: Process multiple value ret instructions also. 01825 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals(); 01826 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(), 01827 E = RV.end(); I != E; ++I) 01828 if (!I->second.isOverdefined() && 01829 I->first->getReturnType() != Type::VoidTy) { 01830 Function *F = I->first; 01831 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 01832 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) 01833 if (!isa<UndefValue>(RI->getOperand(0))) 01834 RI->setOperand(0, UndefValue::get(F->getReturnType())); 01835 } 01836 01837 // If we infered constant or undef values for globals variables, we can delete 01838 // the global and any stores that remain to it. 01839 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals(); 01840 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(), 01841 E = TG.end(); I != E; ++I) { 01842 GlobalVariable *GV = I->first; 01843 assert(!I->second.isOverdefined() && 01844 "Overdefined values should have been taken out of the map!"); 01845 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n"; 01846 while (!GV->use_empty()) { 01847 StoreInst *SI = cast<StoreInst>(GV->use_back()); 01848 SI->eraseFromParent(); 01849 } 01850 M.getGlobalList().erase(GV); 01851 ++IPNumGlobalConst; 01852 } 01853 01854 return MadeChanges; 01855 }