SCCP.cpp revision c25e7581b9b8088910da31702d4ca21c4734c6d7
1//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements sparse conditional constant propagation and merging: 11// 12// Specifically, this: 13// * Assumes values are constant unless proven otherwise 14// * Assumes BasicBlocks are dead unless proven otherwise 15// * Proves values to be constant, and replaces them with constants 16// * Proves conditional branches to be unconditional 17// 18// Notice that: 19// * This pass has a habit of making definitions be dead. It is a good idea 20// to to run a DCE pass sometime after running this pass. 21// 22//===----------------------------------------------------------------------===// 23 24#define DEBUG_TYPE "sccp" 25#include "llvm/Transforms/Scalar.h" 26#include "llvm/Transforms/IPO.h" 27#include "llvm/Constants.h" 28#include "llvm/DerivedTypes.h" 29#include "llvm/Instructions.h" 30#include "llvm/LLVMContext.h" 31#include "llvm/Pass.h" 32#include "llvm/Analysis/ConstantFolding.h" 33#include "llvm/Analysis/ValueTracking.h" 34#include "llvm/Transforms/Utils/Local.h" 35#include "llvm/Support/CallSite.h" 36#include "llvm/Support/Compiler.h" 37#include "llvm/Support/Debug.h" 38#include "llvm/Support/ErrorHandling.h" 39#include "llvm/Support/InstVisitor.h" 40#include "llvm/ADT/DenseMap.h" 41#include "llvm/ADT/DenseSet.h" 42#include "llvm/ADT/SmallSet.h" 43#include "llvm/ADT/SmallVector.h" 44#include "llvm/ADT/Statistic.h" 45#include "llvm/ADT/STLExtras.h" 46#include <algorithm> 47#include <map> 48using namespace llvm; 49 50STATISTIC(NumInstRemoved, "Number of instructions removed"); 51STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable"); 52 53STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP"); 54STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP"); 55STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP"); 56STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP"); 57 58namespace { 59/// LatticeVal class - This class represents the different lattice values that 60/// an LLVM value may occupy. It is a simple class with value semantics. 61/// 62class VISIBILITY_HIDDEN LatticeVal { 63 enum { 64 /// undefined - This LLVM Value has no known value yet. 65 undefined, 66 67 /// constant - This LLVM Value has a specific constant value. 68 constant, 69 70 /// forcedconstant - This LLVM Value was thought to be undef until 71 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged 72 /// with another (different) constant, it goes to overdefined, instead of 73 /// asserting. 74 forcedconstant, 75 76 /// overdefined - This instruction is not known to be constant, and we know 77 /// it has a value. 78 overdefined 79 } LatticeValue; // The current lattice position 80 81 Constant *ConstantVal; // If Constant value, the current value 82public: 83 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {} 84 85 // markOverdefined - Return true if this is a new status to be in... 86 inline bool markOverdefined() { 87 if (LatticeValue != overdefined) { 88 LatticeValue = overdefined; 89 return true; 90 } 91 return false; 92 } 93 94 // markConstant - Return true if this is a new status for us. 95 inline bool markConstant(Constant *V) { 96 if (LatticeValue != constant) { 97 if (LatticeValue == undefined) { 98 LatticeValue = constant; 99 assert(V && "Marking constant with NULL"); 100 ConstantVal = V; 101 } else { 102 assert(LatticeValue == forcedconstant && 103 "Cannot move from overdefined to constant!"); 104 // Stay at forcedconstant if the constant is the same. 105 if (V == ConstantVal) return false; 106 107 // Otherwise, we go to overdefined. Assumptions made based on the 108 // forced value are possibly wrong. Assuming this is another constant 109 // could expose a contradiction. 110 LatticeValue = overdefined; 111 } 112 return true; 113 } else { 114 assert(ConstantVal == V && "Marking constant with different value"); 115 } 116 return false; 117 } 118 119 inline void markForcedConstant(Constant *V) { 120 assert(LatticeValue == undefined && "Can't force a defined value!"); 121 LatticeValue = forcedconstant; 122 ConstantVal = V; 123 } 124 125 inline bool isUndefined() const { return LatticeValue == undefined; } 126 inline bool isConstant() const { 127 return LatticeValue == constant || LatticeValue == forcedconstant; 128 } 129 inline bool isOverdefined() const { return LatticeValue == overdefined; } 130 131 inline Constant *getConstant() const { 132 assert(isConstant() && "Cannot get the constant of a non-constant!"); 133 return ConstantVal; 134 } 135}; 136 137//===----------------------------------------------------------------------===// 138// 139/// SCCPSolver - This class is a general purpose solver for Sparse Conditional 140/// Constant Propagation. 141/// 142class SCCPSolver : public InstVisitor<SCCPSolver> { 143 LLVMContext *Context; 144 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable 145 std::map<Value*, LatticeVal> ValueState; // The state each value is in. 146 147 /// GlobalValue - If we are tracking any values for the contents of a global 148 /// variable, we keep a mapping from the constant accessor to the element of 149 /// the global, to the currently known value. If the value becomes 150 /// overdefined, it's entry is simply removed from this map. 151 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals; 152 153 /// TrackedRetVals - If we are tracking arguments into and the return 154 /// value out of a function, it will have an entry in this map, indicating 155 /// what the known return value for the function is. 156 DenseMap<Function*, LatticeVal> TrackedRetVals; 157 158 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions 159 /// that return multiple values. 160 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals; 161 162 // The reason for two worklists is that overdefined is the lowest state 163 // on the lattice, and moving things to overdefined as fast as possible 164 // makes SCCP converge much faster. 165 // By having a separate worklist, we accomplish this because everything 166 // possibly overdefined will become overdefined at the soonest possible 167 // point. 168 SmallVector<Value*, 64> OverdefinedInstWorkList; 169 SmallVector<Value*, 64> InstWorkList; 170 171 172 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list 173 174 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not 175 /// overdefined, despite the fact that the PHI node is overdefined. 176 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs; 177 178 /// KnownFeasibleEdges - Entries in this set are edges which have already had 179 /// PHI nodes retriggered. 180 typedef std::pair<BasicBlock*, BasicBlock*> Edge; 181 DenseSet<Edge> KnownFeasibleEdges; 182public: 183 void setContext(LLVMContext *C) { Context = C; } 184 185 /// MarkBlockExecutable - This method can be used by clients to mark all of 186 /// the blocks that are known to be intrinsically live in the processed unit. 187 void MarkBlockExecutable(BasicBlock *BB) { 188 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n"; 189 BBExecutable.insert(BB); // Basic block is executable! 190 BBWorkList.push_back(BB); // Add the block to the work list! 191 } 192 193 /// TrackValueOfGlobalVariable - Clients can use this method to 194 /// inform the SCCPSolver that it should track loads and stores to the 195 /// specified global variable if it can. This is only legal to call if 196 /// performing Interprocedural SCCP. 197 void TrackValueOfGlobalVariable(GlobalVariable *GV) { 198 const Type *ElTy = GV->getType()->getElementType(); 199 if (ElTy->isFirstClassType()) { 200 LatticeVal &IV = TrackedGlobals[GV]; 201 if (!isa<UndefValue>(GV->getInitializer())) 202 IV.markConstant(GV->getInitializer()); 203 } 204 } 205 206 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into 207 /// and out of the specified function (which cannot have its address taken), 208 /// this method must be called. 209 void AddTrackedFunction(Function *F) { 210 assert(F->hasLocalLinkage() && "Can only track internal functions!"); 211 // Add an entry, F -> undef. 212 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) { 213 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 214 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i), 215 LatticeVal())); 216 } else 217 TrackedRetVals.insert(std::make_pair(F, LatticeVal())); 218 } 219 220 /// Solve - Solve for constants and executable blocks. 221 /// 222 void Solve(); 223 224 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume 225 /// that branches on undef values cannot reach any of their successors. 226 /// However, this is not a safe assumption. After we solve dataflow, this 227 /// method should be use to handle this. If this returns true, the solver 228 /// should be rerun. 229 bool ResolvedUndefsIn(Function &F); 230 231 bool isBlockExecutable(BasicBlock *BB) const { 232 return BBExecutable.count(BB); 233 } 234 235 /// getValueMapping - Once we have solved for constants, return the mapping of 236 /// LLVM values to LatticeVals. 237 std::map<Value*, LatticeVal> &getValueMapping() { 238 return ValueState; 239 } 240 241 /// getTrackedRetVals - Get the inferred return value map. 242 /// 243 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() { 244 return TrackedRetVals; 245 } 246 247 /// getTrackedGlobals - Get and return the set of inferred initializers for 248 /// global variables. 249 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() { 250 return TrackedGlobals; 251 } 252 253 inline void markOverdefined(Value *V) { 254 markOverdefined(ValueState[V], V); 255 } 256 257private: 258 // markConstant - Make a value be marked as "constant". If the value 259 // is not already a constant, add it to the instruction work list so that 260 // the users of the instruction are updated later. 261 // 262 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) { 263 if (IV.markConstant(C)) { 264 DOUT << "markConstant: " << *C << ": " << *V; 265 InstWorkList.push_back(V); 266 } 267 } 268 269 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) { 270 IV.markForcedConstant(C); 271 DOUT << "markForcedConstant: " << *C << ": " << *V; 272 InstWorkList.push_back(V); 273 } 274 275 inline void markConstant(Value *V, Constant *C) { 276 markConstant(ValueState[V], V, C); 277 } 278 279 // markOverdefined - Make a value be marked as "overdefined". If the 280 // value is not already overdefined, add it to the overdefined instruction 281 // work list so that the users of the instruction are updated later. 282 inline void markOverdefined(LatticeVal &IV, Value *V) { 283 if (IV.markOverdefined()) { 284 DEBUG(DOUT << "markOverdefined: "; 285 if (Function *F = dyn_cast<Function>(V)) 286 DOUT << "Function '" << F->getName() << "'\n"; 287 else 288 DOUT << *V); 289 // Only instructions go on the work list 290 OverdefinedInstWorkList.push_back(V); 291 } 292 } 293 294 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) { 295 if (IV.isOverdefined() || MergeWithV.isUndefined()) 296 return; // Noop. 297 if (MergeWithV.isOverdefined()) 298 markOverdefined(IV, V); 299 else if (IV.isUndefined()) 300 markConstant(IV, V, MergeWithV.getConstant()); 301 else if (IV.getConstant() != MergeWithV.getConstant()) 302 markOverdefined(IV, V); 303 } 304 305 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) { 306 return mergeInValue(ValueState[V], V, MergeWithV); 307 } 308 309 310 // getValueState - Return the LatticeVal object that corresponds to the value. 311 // This function is necessary because not all values should start out in the 312 // underdefined state... Argument's should be overdefined, and 313 // constants should be marked as constants. If a value is not known to be an 314 // Instruction object, then use this accessor to get its value from the map. 315 // 316 inline LatticeVal &getValueState(Value *V) { 317 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V); 318 if (I != ValueState.end()) return I->second; // Common case, in the map 319 320 if (Constant *C = dyn_cast<Constant>(V)) { 321 if (isa<UndefValue>(V)) { 322 // Nothing to do, remain undefined. 323 } else { 324 LatticeVal &LV = ValueState[C]; 325 LV.markConstant(C); // Constants are constant 326 return LV; 327 } 328 } 329 // All others are underdefined by default... 330 return ValueState[V]; 331 } 332 333 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB 334 // work list if it is not already executable... 335 // 336 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { 337 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) 338 return; // This edge is already known to be executable! 339 340 if (BBExecutable.count(Dest)) { 341 DOUT << "Marking Edge Executable: " << Source->getNameStart() 342 << " -> " << Dest->getNameStart() << "\n"; 343 344 // The destination is already executable, but we just made an edge 345 // feasible that wasn't before. Revisit the PHI nodes in the block 346 // because they have potentially new operands. 347 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) 348 visitPHINode(*cast<PHINode>(I)); 349 350 } else { 351 MarkBlockExecutable(Dest); 352 } 353 } 354 355 // getFeasibleSuccessors - Return a vector of booleans to indicate which 356 // successors are reachable from a given terminator instruction. 357 // 358 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs); 359 360 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic 361 // block to the 'To' basic block is currently feasible... 362 // 363 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To); 364 365 // OperandChangedState - This method is invoked on all of the users of an 366 // instruction that was just changed state somehow.... Based on this 367 // information, we need to update the specified user of this instruction. 368 // 369 void OperandChangedState(User *U) { 370 // Only instructions use other variable values! 371 Instruction &I = cast<Instruction>(*U); 372 if (BBExecutable.count(I.getParent())) // Inst is executable? 373 visit(I); 374 } 375 376private: 377 friend class InstVisitor<SCCPSolver>; 378 379 // visit implementations - Something changed in this instruction... Either an 380 // operand made a transition, or the instruction is newly executable. Change 381 // the value type of I to reflect these changes if appropriate. 382 // 383 void visitPHINode(PHINode &I); 384 385 // Terminators 386 void visitReturnInst(ReturnInst &I); 387 void visitTerminatorInst(TerminatorInst &TI); 388 389 void visitCastInst(CastInst &I); 390 void visitSelectInst(SelectInst &I); 391 void visitBinaryOperator(Instruction &I); 392 void visitCmpInst(CmpInst &I); 393 void visitExtractElementInst(ExtractElementInst &I); 394 void visitInsertElementInst(InsertElementInst &I); 395 void visitShuffleVectorInst(ShuffleVectorInst &I); 396 void visitExtractValueInst(ExtractValueInst &EVI); 397 void visitInsertValueInst(InsertValueInst &IVI); 398 399 // Instructions that cannot be folded away... 400 void visitStoreInst (Instruction &I); 401 void visitLoadInst (LoadInst &I); 402 void visitGetElementPtrInst(GetElementPtrInst &I); 403 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); } 404 void visitInvokeInst (InvokeInst &II) { 405 visitCallSite(CallSite::get(&II)); 406 visitTerminatorInst(II); 407 } 408 void visitCallSite (CallSite CS); 409 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ } 410 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ } 411 void visitAllocationInst(Instruction &I) { markOverdefined(&I); } 412 void visitVANextInst (Instruction &I) { markOverdefined(&I); } 413 void visitVAArgInst (Instruction &I) { markOverdefined(&I); } 414 void visitFreeInst (Instruction &I) { /*returns void*/ } 415 416 void visitInstruction(Instruction &I) { 417 // If a new instruction is added to LLVM that we don't handle... 418 cerr << "SCCP: Don't know how to handle: " << I; 419 markOverdefined(&I); // Just in case 420 } 421}; 422 423} // end anonymous namespace 424 425 426// getFeasibleSuccessors - Return a vector of booleans to indicate which 427// successors are reachable from a given terminator instruction. 428// 429void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI, 430 SmallVector<bool, 16> &Succs) { 431 Succs.resize(TI.getNumSuccessors()); 432 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) { 433 if (BI->isUnconditional()) { 434 Succs[0] = true; 435 } else { 436 LatticeVal &BCValue = getValueState(BI->getCondition()); 437 if (BCValue.isOverdefined() || 438 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) { 439 // Overdefined condition variables, and branches on unfoldable constant 440 // conditions, mean the branch could go either way. 441 Succs[0] = Succs[1] = true; 442 } else if (BCValue.isConstant()) { 443 // Constant condition variables mean the branch can only go a single way 444 Succs[BCValue.getConstant() == Context->getConstantIntFalse()] = true; 445 } 446 } 447 } else if (isa<InvokeInst>(&TI)) { 448 // Invoke instructions successors are always executable. 449 Succs[0] = Succs[1] = true; 450 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) { 451 LatticeVal &SCValue = getValueState(SI->getCondition()); 452 if (SCValue.isOverdefined() || // Overdefined condition? 453 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) { 454 // All destinations are executable! 455 Succs.assign(TI.getNumSuccessors(), true); 456 } else if (SCValue.isConstant()) 457 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true; 458 } else { 459 LLVM_UNREACHABLE("SCCP: Don't know how to handle this terminator!"); 460 } 461} 462 463 464// isEdgeFeasible - Return true if the control flow edge from the 'From' basic 465// block to the 'To' basic block is currently feasible... 466// 467bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) { 468 assert(BBExecutable.count(To) && "Dest should always be alive!"); 469 470 // Make sure the source basic block is executable!! 471 if (!BBExecutable.count(From)) return false; 472 473 // Check to make sure this edge itself is actually feasible now... 474 TerminatorInst *TI = From->getTerminator(); 475 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 476 if (BI->isUnconditional()) 477 return true; 478 else { 479 LatticeVal &BCValue = getValueState(BI->getCondition()); 480 if (BCValue.isOverdefined()) { 481 // Overdefined condition variables mean the branch could go either way. 482 return true; 483 } else if (BCValue.isConstant()) { 484 // Not branching on an evaluatable constant? 485 if (!isa<ConstantInt>(BCValue.getConstant())) return true; 486 487 // Constant condition variables mean the branch can only go a single way 488 return BI->getSuccessor(BCValue.getConstant() == 489 Context->getConstantIntFalse()) == To; 490 } 491 return false; 492 } 493 } else if (isa<InvokeInst>(TI)) { 494 // Invoke instructions successors are always executable. 495 return true; 496 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 497 LatticeVal &SCValue = getValueState(SI->getCondition()); 498 if (SCValue.isOverdefined()) { // Overdefined condition? 499 // All destinations are executable! 500 return true; 501 } else if (SCValue.isConstant()) { 502 Constant *CPV = SCValue.getConstant(); 503 if (!isa<ConstantInt>(CPV)) 504 return true; // not a foldable constant? 505 506 // Make sure to skip the "default value" which isn't a value 507 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) 508 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch... 509 return SI->getSuccessor(i) == To; 510 511 // Constant value not equal to any of the branches... must execute 512 // default branch then... 513 return SI->getDefaultDest() == To; 514 } 515 return false; 516 } else { 517#ifndef NDEBUG 518 cerr << "Unknown terminator instruction: " << *TI; 519#endif 520 llvm_unreachable(); 521 } 522} 523 524// visit Implementations - Something changed in this instruction... Either an 525// operand made a transition, or the instruction is newly executable. Change 526// the value type of I to reflect these changes if appropriate. This method 527// makes sure to do the following actions: 528// 529// 1. If a phi node merges two constants in, and has conflicting value coming 530// from different branches, or if the PHI node merges in an overdefined 531// value, then the PHI node becomes overdefined. 532// 2. If a phi node merges only constants in, and they all agree on value, the 533// PHI node becomes a constant value equal to that. 534// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant 535// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined 536// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined 537// 6. If a conditional branch has a value that is constant, make the selected 538// destination executable 539// 7. If a conditional branch has a value that is overdefined, make all 540// successors executable. 541// 542void SCCPSolver::visitPHINode(PHINode &PN) { 543 LatticeVal &PNIV = getValueState(&PN); 544 if (PNIV.isOverdefined()) { 545 // There may be instructions using this PHI node that are not overdefined 546 // themselves. If so, make sure that they know that the PHI node operand 547 // changed. 548 std::multimap<PHINode*, Instruction*>::iterator I, E; 549 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN); 550 if (I != E) { 551 SmallVector<Instruction*, 16> Users; 552 for (; I != E; ++I) Users.push_back(I->second); 553 while (!Users.empty()) { 554 visit(Users.back()); 555 Users.pop_back(); 556 } 557 } 558 return; // Quick exit 559 } 560 561 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant, 562 // and slow us down a lot. Just mark them overdefined. 563 if (PN.getNumIncomingValues() > 64) { 564 markOverdefined(PNIV, &PN); 565 return; 566 } 567 568 // Look at all of the executable operands of the PHI node. If any of them 569 // are overdefined, the PHI becomes overdefined as well. If they are all 570 // constant, and they agree with each other, the PHI becomes the identical 571 // constant. If they are constant and don't agree, the PHI is overdefined. 572 // If there are no executable operands, the PHI remains undefined. 573 // 574 Constant *OperandVal = 0; 575 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 576 LatticeVal &IV = getValueState(PN.getIncomingValue(i)); 577 if (IV.isUndefined()) continue; // Doesn't influence PHI node. 578 579 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) { 580 if (IV.isOverdefined()) { // PHI node becomes overdefined! 581 markOverdefined(&PN); 582 return; 583 } 584 585 if (OperandVal == 0) { // Grab the first value... 586 OperandVal = IV.getConstant(); 587 } else { // Another value is being merged in! 588 // There is already a reachable operand. If we conflict with it, 589 // then the PHI node becomes overdefined. If we agree with it, we 590 // can continue on. 591 592 // Check to see if there are two different constants merging... 593 if (IV.getConstant() != OperandVal) { 594 // Yes there is. This means the PHI node is not constant. 595 // You must be overdefined poor PHI. 596 // 597 markOverdefined(&PN); // The PHI node now becomes overdefined 598 return; // I'm done analyzing you 599 } 600 } 601 } 602 } 603 604 // If we exited the loop, this means that the PHI node only has constant 605 // arguments that agree with each other(and OperandVal is the constant) or 606 // OperandVal is null because there are no defined incoming arguments. If 607 // this is the case, the PHI remains undefined. 608 // 609 if (OperandVal) 610 markConstant(&PN, OperandVal); // Acquire operand value 611} 612 613void SCCPSolver::visitReturnInst(ReturnInst &I) { 614 if (I.getNumOperands() == 0) return; // Ret void 615 616 Function *F = I.getParent()->getParent(); 617 // If we are tracking the return value of this function, merge it in. 618 if (!F->hasLocalLinkage()) 619 return; 620 621 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) { 622 DenseMap<Function*, LatticeVal>::iterator TFRVI = 623 TrackedRetVals.find(F); 624 if (TFRVI != TrackedRetVals.end() && 625 !TFRVI->second.isOverdefined()) { 626 LatticeVal &IV = getValueState(I.getOperand(0)); 627 mergeInValue(TFRVI->second, F, IV); 628 return; 629 } 630 } 631 632 // Handle functions that return multiple values. 633 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) { 634 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 635 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 636 It = TrackedMultipleRetVals.find(std::make_pair(F, i)); 637 if (It == TrackedMultipleRetVals.end()) break; 638 mergeInValue(It->second, F, getValueState(I.getOperand(i))); 639 } 640 } else if (!TrackedMultipleRetVals.empty() && 641 I.getNumOperands() == 1 && 642 isa<StructType>(I.getOperand(0)->getType())) { 643 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes(); 644 i != e; ++i) { 645 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 646 It = TrackedMultipleRetVals.find(std::make_pair(F, i)); 647 if (It == TrackedMultipleRetVals.end()) break; 648 if (Value *Val = FindInsertedValue(I.getOperand(0), i, Context)) 649 mergeInValue(It->second, F, getValueState(Val)); 650 } 651 } 652} 653 654void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) { 655 SmallVector<bool, 16> SuccFeasible; 656 getFeasibleSuccessors(TI, SuccFeasible); 657 658 BasicBlock *BB = TI.getParent(); 659 660 // Mark all feasible successors executable... 661 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i) 662 if (SuccFeasible[i]) 663 markEdgeExecutable(BB, TI.getSuccessor(i)); 664} 665 666void SCCPSolver::visitCastInst(CastInst &I) { 667 Value *V = I.getOperand(0); 668 LatticeVal &VState = getValueState(V); 669 if (VState.isOverdefined()) // Inherit overdefinedness of operand 670 markOverdefined(&I); 671 else if (VState.isConstant()) // Propagate constant value 672 markConstant(&I, Context->getConstantExprCast(I.getOpcode(), 673 VState.getConstant(), I.getType())); 674} 675 676void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) { 677 Value *Aggr = EVI.getAggregateOperand(); 678 679 // If the operand to the extractvalue is an undef, the result is undef. 680 if (isa<UndefValue>(Aggr)) 681 return; 682 683 // Currently only handle single-index extractvalues. 684 if (EVI.getNumIndices() != 1) { 685 markOverdefined(&EVI); 686 return; 687 } 688 689 Function *F = 0; 690 if (CallInst *CI = dyn_cast<CallInst>(Aggr)) 691 F = CI->getCalledFunction(); 692 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr)) 693 F = II->getCalledFunction(); 694 695 // TODO: If IPSCCP resolves the callee of this function, we could propagate a 696 // result back! 697 if (F == 0 || TrackedMultipleRetVals.empty()) { 698 markOverdefined(&EVI); 699 return; 700 } 701 702 // See if we are tracking the result of the callee. If not tracking this 703 // function (for example, it is a declaration) just move to overdefined. 704 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) { 705 markOverdefined(&EVI); 706 return; 707 } 708 709 // Otherwise, the value will be merged in here as a result of CallSite 710 // handling. 711} 712 713void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) { 714 Value *Aggr = IVI.getAggregateOperand(); 715 Value *Val = IVI.getInsertedValueOperand(); 716 717 // If the operands to the insertvalue are undef, the result is undef. 718 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val)) 719 return; 720 721 // Currently only handle single-index insertvalues. 722 if (IVI.getNumIndices() != 1) { 723 markOverdefined(&IVI); 724 return; 725 } 726 727 // Currently only handle insertvalue instructions that are in a single-use 728 // chain that builds up a return value. 729 for (const InsertValueInst *TmpIVI = &IVI; ; ) { 730 if (!TmpIVI->hasOneUse()) { 731 markOverdefined(&IVI); 732 return; 733 } 734 const Value *V = *TmpIVI->use_begin(); 735 if (isa<ReturnInst>(V)) 736 break; 737 TmpIVI = dyn_cast<InsertValueInst>(V); 738 if (!TmpIVI) { 739 markOverdefined(&IVI); 740 return; 741 } 742 } 743 744 // See if we are tracking the result of the callee. 745 Function *F = IVI.getParent()->getParent(); 746 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 747 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin())); 748 749 // Merge in the inserted member value. 750 if (It != TrackedMultipleRetVals.end()) 751 mergeInValue(It->second, F, getValueState(Val)); 752 753 // Mark the aggregate result of the IVI overdefined; any tracking that we do 754 // will be done on the individual member values. 755 markOverdefined(&IVI); 756} 757 758void SCCPSolver::visitSelectInst(SelectInst &I) { 759 LatticeVal &CondValue = getValueState(I.getCondition()); 760 if (CondValue.isUndefined()) 761 return; 762 if (CondValue.isConstant()) { 763 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){ 764 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue() 765 : I.getFalseValue())); 766 return; 767 } 768 } 769 770 // Otherwise, the condition is overdefined or a constant we can't evaluate. 771 // See if we can produce something better than overdefined based on the T/F 772 // value. 773 LatticeVal &TVal = getValueState(I.getTrueValue()); 774 LatticeVal &FVal = getValueState(I.getFalseValue()); 775 776 // select ?, C, C -> C. 777 if (TVal.isConstant() && FVal.isConstant() && 778 TVal.getConstant() == FVal.getConstant()) { 779 markConstant(&I, FVal.getConstant()); 780 return; 781 } 782 783 if (TVal.isUndefined()) { // select ?, undef, X -> X. 784 mergeInValue(&I, FVal); 785 } else if (FVal.isUndefined()) { // select ?, X, undef -> X. 786 mergeInValue(&I, TVal); 787 } else { 788 markOverdefined(&I); 789 } 790} 791 792// Handle BinaryOperators and Shift Instructions... 793void SCCPSolver::visitBinaryOperator(Instruction &I) { 794 LatticeVal &IV = ValueState[&I]; 795 if (IV.isOverdefined()) return; 796 797 LatticeVal &V1State = getValueState(I.getOperand(0)); 798 LatticeVal &V2State = getValueState(I.getOperand(1)); 799 800 if (V1State.isOverdefined() || V2State.isOverdefined()) { 801 // If this is an AND or OR with 0 or -1, it doesn't matter that the other 802 // operand is overdefined. 803 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) { 804 LatticeVal *NonOverdefVal = 0; 805 if (!V1State.isOverdefined()) { 806 NonOverdefVal = &V1State; 807 } else if (!V2State.isOverdefined()) { 808 NonOverdefVal = &V2State; 809 } 810 811 if (NonOverdefVal) { 812 if (NonOverdefVal->isUndefined()) { 813 // Could annihilate value. 814 if (I.getOpcode() == Instruction::And) 815 markConstant(IV, &I, Context->getNullValue(I.getType())); 816 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType())) 817 markConstant(IV, &I, Context->getConstantVectorAllOnesValue(PT)); 818 else 819 markConstant(IV, &I, 820 Context->getConstantIntAllOnesValue(I.getType())); 821 return; 822 } else { 823 if (I.getOpcode() == Instruction::And) { 824 if (NonOverdefVal->getConstant()->isNullValue()) { 825 markConstant(IV, &I, NonOverdefVal->getConstant()); 826 return; // X and 0 = 0 827 } 828 } else { 829 if (ConstantInt *CI = 830 dyn_cast<ConstantInt>(NonOverdefVal->getConstant())) 831 if (CI->isAllOnesValue()) { 832 markConstant(IV, &I, NonOverdefVal->getConstant()); 833 return; // X or -1 = -1 834 } 835 } 836 } 837 } 838 } 839 840 841 // If both operands are PHI nodes, it is possible that this instruction has 842 // a constant value, despite the fact that the PHI node doesn't. Check for 843 // this condition now. 844 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0))) 845 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1))) 846 if (PN1->getParent() == PN2->getParent()) { 847 // Since the two PHI nodes are in the same basic block, they must have 848 // entries for the same predecessors. Walk the predecessor list, and 849 // if all of the incoming values are constants, and the result of 850 // evaluating this expression with all incoming value pairs is the 851 // same, then this expression is a constant even though the PHI node 852 // is not a constant! 853 LatticeVal Result; 854 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) { 855 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i)); 856 BasicBlock *InBlock = PN1->getIncomingBlock(i); 857 LatticeVal &In2 = 858 getValueState(PN2->getIncomingValueForBlock(InBlock)); 859 860 if (In1.isOverdefined() || In2.isOverdefined()) { 861 Result.markOverdefined(); 862 break; // Cannot fold this operation over the PHI nodes! 863 } else if (In1.isConstant() && In2.isConstant()) { 864 Constant *V = 865 Context->getConstantExpr(I.getOpcode(), In1.getConstant(), 866 In2.getConstant()); 867 if (Result.isUndefined()) 868 Result.markConstant(V); 869 else if (Result.isConstant() && Result.getConstant() != V) { 870 Result.markOverdefined(); 871 break; 872 } 873 } 874 } 875 876 // If we found a constant value here, then we know the instruction is 877 // constant despite the fact that the PHI nodes are overdefined. 878 if (Result.isConstant()) { 879 markConstant(IV, &I, Result.getConstant()); 880 // Remember that this instruction is virtually using the PHI node 881 // operands. 882 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I)); 883 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I)); 884 return; 885 } else if (Result.isUndefined()) { 886 return; 887 } 888 889 // Okay, this really is overdefined now. Since we might have 890 // speculatively thought that this was not overdefined before, and 891 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs, 892 // make sure to clean out any entries that we put there, for 893 // efficiency. 894 std::multimap<PHINode*, Instruction*>::iterator It, E; 895 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1); 896 while (It != E) { 897 if (It->second == &I) { 898 UsersOfOverdefinedPHIs.erase(It++); 899 } else 900 ++It; 901 } 902 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2); 903 while (It != E) { 904 if (It->second == &I) { 905 UsersOfOverdefinedPHIs.erase(It++); 906 } else 907 ++It; 908 } 909 } 910 911 markOverdefined(IV, &I); 912 } else if (V1State.isConstant() && V2State.isConstant()) { 913 markConstant(IV, &I, 914 Context->getConstantExpr(I.getOpcode(), V1State.getConstant(), 915 V2State.getConstant())); 916 } 917} 918 919// Handle ICmpInst instruction... 920void SCCPSolver::visitCmpInst(CmpInst &I) { 921 LatticeVal &IV = ValueState[&I]; 922 if (IV.isOverdefined()) return; 923 924 LatticeVal &V1State = getValueState(I.getOperand(0)); 925 LatticeVal &V2State = getValueState(I.getOperand(1)); 926 927 if (V1State.isOverdefined() || V2State.isOverdefined()) { 928 // If both operands are PHI nodes, it is possible that this instruction has 929 // a constant value, despite the fact that the PHI node doesn't. Check for 930 // this condition now. 931 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0))) 932 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1))) 933 if (PN1->getParent() == PN2->getParent()) { 934 // Since the two PHI nodes are in the same basic block, they must have 935 // entries for the same predecessors. Walk the predecessor list, and 936 // if all of the incoming values are constants, and the result of 937 // evaluating this expression with all incoming value pairs is the 938 // same, then this expression is a constant even though the PHI node 939 // is not a constant! 940 LatticeVal Result; 941 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) { 942 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i)); 943 BasicBlock *InBlock = PN1->getIncomingBlock(i); 944 LatticeVal &In2 = 945 getValueState(PN2->getIncomingValueForBlock(InBlock)); 946 947 if (In1.isOverdefined() || In2.isOverdefined()) { 948 Result.markOverdefined(); 949 break; // Cannot fold this operation over the PHI nodes! 950 } else if (In1.isConstant() && In2.isConstant()) { 951 Constant *V = Context->getConstantExprCompare(I.getPredicate(), 952 In1.getConstant(), 953 In2.getConstant()); 954 if (Result.isUndefined()) 955 Result.markConstant(V); 956 else if (Result.isConstant() && Result.getConstant() != V) { 957 Result.markOverdefined(); 958 break; 959 } 960 } 961 } 962 963 // If we found a constant value here, then we know the instruction is 964 // constant despite the fact that the PHI nodes are overdefined. 965 if (Result.isConstant()) { 966 markConstant(IV, &I, Result.getConstant()); 967 // Remember that this instruction is virtually using the PHI node 968 // operands. 969 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I)); 970 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I)); 971 return; 972 } else if (Result.isUndefined()) { 973 return; 974 } 975 976 // Okay, this really is overdefined now. Since we might have 977 // speculatively thought that this was not overdefined before, and 978 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs, 979 // make sure to clean out any entries that we put there, for 980 // efficiency. 981 std::multimap<PHINode*, Instruction*>::iterator It, E; 982 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1); 983 while (It != E) { 984 if (It->second == &I) { 985 UsersOfOverdefinedPHIs.erase(It++); 986 } else 987 ++It; 988 } 989 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2); 990 while (It != E) { 991 if (It->second == &I) { 992 UsersOfOverdefinedPHIs.erase(It++); 993 } else 994 ++It; 995 } 996 } 997 998 markOverdefined(IV, &I); 999 } else if (V1State.isConstant() && V2State.isConstant()) { 1000 markConstant(IV, &I, Context->getConstantExprCompare(I.getPredicate(), 1001 V1State.getConstant(), 1002 V2State.getConstant())); 1003 } 1004} 1005 1006void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) { 1007 // FIXME : SCCP does not handle vectors properly. 1008 markOverdefined(&I); 1009 return; 1010 1011#if 0 1012 LatticeVal &ValState = getValueState(I.getOperand(0)); 1013 LatticeVal &IdxState = getValueState(I.getOperand(1)); 1014 1015 if (ValState.isOverdefined() || IdxState.isOverdefined()) 1016 markOverdefined(&I); 1017 else if(ValState.isConstant() && IdxState.isConstant()) 1018 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(), 1019 IdxState.getConstant())); 1020#endif 1021} 1022 1023void SCCPSolver::visitInsertElementInst(InsertElementInst &I) { 1024 // FIXME : SCCP does not handle vectors properly. 1025 markOverdefined(&I); 1026 return; 1027#if 0 1028 LatticeVal &ValState = getValueState(I.getOperand(0)); 1029 LatticeVal &EltState = getValueState(I.getOperand(1)); 1030 LatticeVal &IdxState = getValueState(I.getOperand(2)); 1031 1032 if (ValState.isOverdefined() || EltState.isOverdefined() || 1033 IdxState.isOverdefined()) 1034 markOverdefined(&I); 1035 else if(ValState.isConstant() && EltState.isConstant() && 1036 IdxState.isConstant()) 1037 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(), 1038 EltState.getConstant(), 1039 IdxState.getConstant())); 1040 else if (ValState.isUndefined() && EltState.isConstant() && 1041 IdxState.isConstant()) 1042 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()), 1043 EltState.getConstant(), 1044 IdxState.getConstant())); 1045#endif 1046} 1047 1048void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) { 1049 // FIXME : SCCP does not handle vectors properly. 1050 markOverdefined(&I); 1051 return; 1052#if 0 1053 LatticeVal &V1State = getValueState(I.getOperand(0)); 1054 LatticeVal &V2State = getValueState(I.getOperand(1)); 1055 LatticeVal &MaskState = getValueState(I.getOperand(2)); 1056 1057 if (MaskState.isUndefined() || 1058 (V1State.isUndefined() && V2State.isUndefined())) 1059 return; // Undefined output if mask or both inputs undefined. 1060 1061 if (V1State.isOverdefined() || V2State.isOverdefined() || 1062 MaskState.isOverdefined()) { 1063 markOverdefined(&I); 1064 } else { 1065 // A mix of constant/undef inputs. 1066 Constant *V1 = V1State.isConstant() ? 1067 V1State.getConstant() : UndefValue::get(I.getType()); 1068 Constant *V2 = V2State.isConstant() ? 1069 V2State.getConstant() : UndefValue::get(I.getType()); 1070 Constant *Mask = MaskState.isConstant() ? 1071 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType()); 1072 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask)); 1073 } 1074#endif 1075} 1076 1077// Handle getelementptr instructions... if all operands are constants then we 1078// can turn this into a getelementptr ConstantExpr. 1079// 1080void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) { 1081 LatticeVal &IV = ValueState[&I]; 1082 if (IV.isOverdefined()) return; 1083 1084 SmallVector<Constant*, 8> Operands; 1085 Operands.reserve(I.getNumOperands()); 1086 1087 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 1088 LatticeVal &State = getValueState(I.getOperand(i)); 1089 if (State.isUndefined()) 1090 return; // Operands are not resolved yet... 1091 else if (State.isOverdefined()) { 1092 markOverdefined(IV, &I); 1093 return; 1094 } 1095 assert(State.isConstant() && "Unknown state!"); 1096 Operands.push_back(State.getConstant()); 1097 } 1098 1099 Constant *Ptr = Operands[0]; 1100 Operands.erase(Operands.begin()); // Erase the pointer from idx list... 1101 1102 markConstant(IV, &I, Context->getConstantExprGetElementPtr(Ptr, &Operands[0], 1103 Operands.size())); 1104} 1105 1106void SCCPSolver::visitStoreInst(Instruction &SI) { 1107 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1))) 1108 return; 1109 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1)); 1110 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV); 1111 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return; 1112 1113 // Get the value we are storing into the global. 1114 LatticeVal &PtrVal = getValueState(SI.getOperand(0)); 1115 1116 mergeInValue(I->second, GV, PtrVal); 1117 if (I->second.isOverdefined()) 1118 TrackedGlobals.erase(I); // No need to keep tracking this! 1119} 1120 1121 1122// Handle load instructions. If the operand is a constant pointer to a constant 1123// global, we can replace the load with the loaded constant value! 1124void SCCPSolver::visitLoadInst(LoadInst &I) { 1125 LatticeVal &IV = ValueState[&I]; 1126 if (IV.isOverdefined()) return; 1127 1128 LatticeVal &PtrVal = getValueState(I.getOperand(0)); 1129 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet! 1130 if (PtrVal.isConstant() && !I.isVolatile()) { 1131 Value *Ptr = PtrVal.getConstant(); 1132 // TODO: Consider a target hook for valid address spaces for this xform. 1133 if (isa<ConstantPointerNull>(Ptr) && 1134 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) { 1135 // load null -> null 1136 markConstant(IV, &I, Context->getNullValue(I.getType())); 1137 return; 1138 } 1139 1140 // Transform load (constant global) into the value loaded. 1141 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) { 1142 if (GV->isConstant()) { 1143 if (GV->hasDefinitiveInitializer()) { 1144 markConstant(IV, &I, GV->getInitializer()); 1145 return; 1146 } 1147 } else if (!TrackedGlobals.empty()) { 1148 // If we are tracking this global, merge in the known value for it. 1149 DenseMap<GlobalVariable*, LatticeVal>::iterator It = 1150 TrackedGlobals.find(GV); 1151 if (It != TrackedGlobals.end()) { 1152 mergeInValue(IV, &I, It->second); 1153 return; 1154 } 1155 } 1156 } 1157 1158 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded. 1159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) 1160 if (CE->getOpcode() == Instruction::GetElementPtr) 1161 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) 1162 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 1163 if (Constant *V = 1164 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 1165 Context)) { 1166 markConstant(IV, &I, V); 1167 return; 1168 } 1169 } 1170 1171 // Otherwise we cannot say for certain what value this load will produce. 1172 // Bail out. 1173 markOverdefined(IV, &I); 1174} 1175 1176void SCCPSolver::visitCallSite(CallSite CS) { 1177 Function *F = CS.getCalledFunction(); 1178 Instruction *I = CS.getInstruction(); 1179 1180 // The common case is that we aren't tracking the callee, either because we 1181 // are not doing interprocedural analysis or the callee is indirect, or is 1182 // external. Handle these cases first. 1183 if (F == 0 || !F->hasLocalLinkage()) { 1184CallOverdefined: 1185 // Void return and not tracking callee, just bail. 1186 if (I->getType() == Type::VoidTy) return; 1187 1188 // Otherwise, if we have a single return value case, and if the function is 1189 // a declaration, maybe we can constant fold it. 1190 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() && 1191 canConstantFoldCallTo(F)) { 1192 1193 SmallVector<Constant*, 8> Operands; 1194 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); 1195 AI != E; ++AI) { 1196 LatticeVal &State = getValueState(*AI); 1197 if (State.isUndefined()) 1198 return; // Operands are not resolved yet. 1199 else if (State.isOverdefined()) { 1200 markOverdefined(I); 1201 return; 1202 } 1203 assert(State.isConstant() && "Unknown state!"); 1204 Operands.push_back(State.getConstant()); 1205 } 1206 1207 // If we can constant fold this, mark the result of the call as a 1208 // constant. 1209 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) { 1210 markConstant(I, C); 1211 return; 1212 } 1213 } 1214 1215 // Otherwise, we don't know anything about this call, mark it overdefined. 1216 markOverdefined(I); 1217 return; 1218 } 1219 1220 // If this is a single/zero retval case, see if we're tracking the function. 1221 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F); 1222 if (TFRVI != TrackedRetVals.end()) { 1223 // If so, propagate the return value of the callee into this call result. 1224 mergeInValue(I, TFRVI->second); 1225 } else if (isa<StructType>(I->getType())) { 1226 // Check to see if we're tracking this callee, if not, handle it in the 1227 // common path above. 1228 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator 1229 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0)); 1230 if (TMRVI == TrackedMultipleRetVals.end()) 1231 goto CallOverdefined; 1232 1233 // If we are tracking this callee, propagate the return values of the call 1234 // into this call site. We do this by walking all the uses. Single-index 1235 // ExtractValueInst uses can be tracked; anything more complicated is 1236 // currently handled conservatively. 1237 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 1238 UI != E; ++UI) { 1239 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) { 1240 if (EVI->getNumIndices() == 1) { 1241 mergeInValue(EVI, 1242 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]); 1243 continue; 1244 } 1245 } 1246 // The aggregate value is used in a way not handled here. Assume nothing. 1247 markOverdefined(*UI); 1248 } 1249 } else { 1250 // Otherwise we're not tracking this callee, so handle it in the 1251 // common path above. 1252 goto CallOverdefined; 1253 } 1254 1255 // Finally, if this is the first call to the function hit, mark its entry 1256 // block executable. 1257 if (!BBExecutable.count(F->begin())) 1258 MarkBlockExecutable(F->begin()); 1259 1260 // Propagate information from this call site into the callee. 1261 CallSite::arg_iterator CAI = CS.arg_begin(); 1262 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1263 AI != E; ++AI, ++CAI) { 1264 LatticeVal &IV = ValueState[AI]; 1265 if (!IV.isOverdefined()) 1266 mergeInValue(IV, AI, getValueState(*CAI)); 1267 } 1268} 1269 1270 1271void SCCPSolver::Solve() { 1272 // Process the work lists until they are empty! 1273 while (!BBWorkList.empty() || !InstWorkList.empty() || 1274 !OverdefinedInstWorkList.empty()) { 1275 // Process the instruction work list... 1276 while (!OverdefinedInstWorkList.empty()) { 1277 Value *I = OverdefinedInstWorkList.back(); 1278 OverdefinedInstWorkList.pop_back(); 1279 1280 DOUT << "\nPopped off OI-WL: " << *I; 1281 1282 // "I" got into the work list because it either made the transition from 1283 // bottom to constant 1284 // 1285 // Anything on this worklist that is overdefined need not be visited 1286 // since all of its users will have already been marked as overdefined 1287 // Update all of the users of this instruction's value... 1288 // 1289 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 1290 UI != E; ++UI) 1291 OperandChangedState(*UI); 1292 } 1293 // Process the instruction work list... 1294 while (!InstWorkList.empty()) { 1295 Value *I = InstWorkList.back(); 1296 InstWorkList.pop_back(); 1297 1298 DOUT << "\nPopped off I-WL: " << *I; 1299 1300 // "I" got into the work list because it either made the transition from 1301 // bottom to constant 1302 // 1303 // Anything on this worklist that is overdefined need not be visited 1304 // since all of its users will have already been marked as overdefined. 1305 // Update all of the users of this instruction's value... 1306 // 1307 if (!getValueState(I).isOverdefined()) 1308 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 1309 UI != E; ++UI) 1310 OperandChangedState(*UI); 1311 } 1312 1313 // Process the basic block work list... 1314 while (!BBWorkList.empty()) { 1315 BasicBlock *BB = BBWorkList.back(); 1316 BBWorkList.pop_back(); 1317 1318 DOUT << "\nPopped off BBWL: " << *BB; 1319 1320 // Notify all instructions in this basic block that they are newly 1321 // executable. 1322 visit(BB); 1323 } 1324 } 1325} 1326 1327/// ResolvedUndefsIn - While solving the dataflow for a function, we assume 1328/// that branches on undef values cannot reach any of their successors. 1329/// However, this is not a safe assumption. After we solve dataflow, this 1330/// method should be use to handle this. If this returns true, the solver 1331/// should be rerun. 1332/// 1333/// This method handles this by finding an unresolved branch and marking it one 1334/// of the edges from the block as being feasible, even though the condition 1335/// doesn't say it would otherwise be. This allows SCCP to find the rest of the 1336/// CFG and only slightly pessimizes the analysis results (by marking one, 1337/// potentially infeasible, edge feasible). This cannot usefully modify the 1338/// constraints on the condition of the branch, as that would impact other users 1339/// of the value. 1340/// 1341/// This scan also checks for values that use undefs, whose results are actually 1342/// defined. For example, 'zext i8 undef to i32' should produce all zeros 1343/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero, 1344/// even if X isn't defined. 1345bool SCCPSolver::ResolvedUndefsIn(Function &F) { 1346 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 1347 if (!BBExecutable.count(BB)) 1348 continue; 1349 1350 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1351 // Look for instructions which produce undef values. 1352 if (I->getType() == Type::VoidTy) continue; 1353 1354 LatticeVal &LV = getValueState(I); 1355 if (!LV.isUndefined()) continue; 1356 1357 // Get the lattice values of the first two operands for use below. 1358 LatticeVal &Op0LV = getValueState(I->getOperand(0)); 1359 LatticeVal Op1LV; 1360 if (I->getNumOperands() == 2) { 1361 // If this is a two-operand instruction, and if both operands are 1362 // undefs, the result stays undef. 1363 Op1LV = getValueState(I->getOperand(1)); 1364 if (Op0LV.isUndefined() && Op1LV.isUndefined()) 1365 continue; 1366 } 1367 1368 // If this is an instructions whose result is defined even if the input is 1369 // not fully defined, propagate the information. 1370 const Type *ITy = I->getType(); 1371 switch (I->getOpcode()) { 1372 default: break; // Leave the instruction as an undef. 1373 case Instruction::ZExt: 1374 // After a zero extend, we know the top part is zero. SExt doesn't have 1375 // to be handled here, because we don't know whether the top part is 1's 1376 // or 0's. 1377 assert(Op0LV.isUndefined()); 1378 markForcedConstant(LV, I, Context->getNullValue(ITy)); 1379 return true; 1380 case Instruction::Mul: 1381 case Instruction::And: 1382 // undef * X -> 0. X could be zero. 1383 // undef & X -> 0. X could be zero. 1384 markForcedConstant(LV, I, Context->getNullValue(ITy)); 1385 return true; 1386 1387 case Instruction::Or: 1388 // undef | X -> -1. X could be -1. 1389 if (const VectorType *PTy = dyn_cast<VectorType>(ITy)) 1390 markForcedConstant(LV, I, 1391 Context->getConstantVectorAllOnesValue(PTy)); 1392 else 1393 markForcedConstant(LV, I, Context->getConstantIntAllOnesValue(ITy)); 1394 return true; 1395 1396 case Instruction::SDiv: 1397 case Instruction::UDiv: 1398 case Instruction::SRem: 1399 case Instruction::URem: 1400 // X / undef -> undef. No change. 1401 // X % undef -> undef. No change. 1402 if (Op1LV.isUndefined()) break; 1403 1404 // undef / X -> 0. X could be maxint. 1405 // undef % X -> 0. X could be 1. 1406 markForcedConstant(LV, I, Context->getNullValue(ITy)); 1407 return true; 1408 1409 case Instruction::AShr: 1410 // undef >>s X -> undef. No change. 1411 if (Op0LV.isUndefined()) break; 1412 1413 // X >>s undef -> X. X could be 0, X could have the high-bit known set. 1414 if (Op0LV.isConstant()) 1415 markForcedConstant(LV, I, Op0LV.getConstant()); 1416 else 1417 markOverdefined(LV, I); 1418 return true; 1419 case Instruction::LShr: 1420 case Instruction::Shl: 1421 // undef >> X -> undef. No change. 1422 // undef << X -> undef. No change. 1423 if (Op0LV.isUndefined()) break; 1424 1425 // X >> undef -> 0. X could be 0. 1426 // X << undef -> 0. X could be 0. 1427 markForcedConstant(LV, I, Context->getNullValue(ITy)); 1428 return true; 1429 case Instruction::Select: 1430 // undef ? X : Y -> X or Y. There could be commonality between X/Y. 1431 if (Op0LV.isUndefined()) { 1432 if (!Op1LV.isConstant()) // Pick the constant one if there is any. 1433 Op1LV = getValueState(I->getOperand(2)); 1434 } else if (Op1LV.isUndefined()) { 1435 // c ? undef : undef -> undef. No change. 1436 Op1LV = getValueState(I->getOperand(2)); 1437 if (Op1LV.isUndefined()) 1438 break; 1439 // Otherwise, c ? undef : x -> x. 1440 } else { 1441 // Leave Op1LV as Operand(1)'s LatticeValue. 1442 } 1443 1444 if (Op1LV.isConstant()) 1445 markForcedConstant(LV, I, Op1LV.getConstant()); 1446 else 1447 markOverdefined(LV, I); 1448 return true; 1449 case Instruction::Call: 1450 // If a call has an undef result, it is because it is constant foldable 1451 // but one of the inputs was undef. Just force the result to 1452 // overdefined. 1453 markOverdefined(LV, I); 1454 return true; 1455 } 1456 } 1457 1458 TerminatorInst *TI = BB->getTerminator(); 1459 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1460 if (!BI->isConditional()) continue; 1461 if (!getValueState(BI->getCondition()).isUndefined()) 1462 continue; 1463 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 1464 if (SI->getNumSuccessors()<2) // no cases 1465 continue; 1466 if (!getValueState(SI->getCondition()).isUndefined()) 1467 continue; 1468 } else { 1469 continue; 1470 } 1471 1472 // If the edge to the second successor isn't thought to be feasible yet, 1473 // mark it so now. We pick the second one so that this goes to some 1474 // enumerated value in a switch instead of going to the default destination. 1475 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1)))) 1476 continue; 1477 1478 // Otherwise, it isn't already thought to be feasible. Mark it as such now 1479 // and return. This will make other blocks reachable, which will allow new 1480 // values to be discovered and existing ones to be moved in the lattice. 1481 markEdgeExecutable(BB, TI->getSuccessor(1)); 1482 1483 // This must be a conditional branch of switch on undef. At this point, 1484 // force the old terminator to branch to the first successor. This is 1485 // required because we are now influencing the dataflow of the function with 1486 // the assumption that this edge is taken. If we leave the branch condition 1487 // as undef, then further analysis could think the undef went another way 1488 // leading to an inconsistent set of conclusions. 1489 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1490 BI->setCondition(Context->getConstantIntFalse()); 1491 } else { 1492 SwitchInst *SI = cast<SwitchInst>(TI); 1493 SI->setCondition(SI->getCaseValue(1)); 1494 } 1495 1496 return true; 1497 } 1498 1499 return false; 1500} 1501 1502 1503namespace { 1504 //===--------------------------------------------------------------------===// 1505 // 1506 /// SCCP Class - This class uses the SCCPSolver to implement a per-function 1507 /// Sparse Conditional Constant Propagator. 1508 /// 1509 struct VISIBILITY_HIDDEN SCCP : public FunctionPass { 1510 static char ID; // Pass identification, replacement for typeid 1511 SCCP() : FunctionPass(&ID) {} 1512 1513 // runOnFunction - Run the Sparse Conditional Constant Propagation 1514 // algorithm, and return true if the function was modified. 1515 // 1516 bool runOnFunction(Function &F); 1517 1518 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 1519 AU.setPreservesCFG(); 1520 } 1521 }; 1522} // end anonymous namespace 1523 1524char SCCP::ID = 0; 1525static RegisterPass<SCCP> 1526X("sccp", "Sparse Conditional Constant Propagation"); 1527 1528// createSCCPPass - This is the public interface to this file... 1529FunctionPass *llvm::createSCCPPass() { 1530 return new SCCP(); 1531} 1532 1533 1534// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm, 1535// and return true if the function was modified. 1536// 1537bool SCCP::runOnFunction(Function &F) { 1538 DOUT << "SCCP on function '" << F.getNameStart() << "'\n"; 1539 SCCPSolver Solver; 1540 Solver.setContext(Context); 1541 1542 // Mark the first block of the function as being executable. 1543 Solver.MarkBlockExecutable(F.begin()); 1544 1545 // Mark all arguments to the function as being overdefined. 1546 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI) 1547 Solver.markOverdefined(AI); 1548 1549 // Solve for constants. 1550 bool ResolvedUndefs = true; 1551 while (ResolvedUndefs) { 1552 Solver.Solve(); 1553 DOUT << "RESOLVING UNDEFs\n"; 1554 ResolvedUndefs = Solver.ResolvedUndefsIn(F); 1555 } 1556 1557 bool MadeChanges = false; 1558 1559 // If we decided that there are basic blocks that are dead in this function, 1560 // delete their contents now. Note that we cannot actually delete the blocks, 1561 // as we cannot modify the CFG of the function. 1562 // 1563 SmallVector<Instruction*, 512> Insts; 1564 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping(); 1565 1566 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 1567 if (!Solver.isBlockExecutable(BB)) { 1568 DOUT << " BasicBlock Dead:" << *BB; 1569 ++NumDeadBlocks; 1570 1571 // Delete the instructions backwards, as it has a reduced likelihood of 1572 // having to update as many def-use and use-def chains. 1573 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator(); 1574 I != E; ++I) 1575 Insts.push_back(I); 1576 while (!Insts.empty()) { 1577 Instruction *I = Insts.back(); 1578 Insts.pop_back(); 1579 if (!I->use_empty()) 1580 I->replaceAllUsesWith(Context->getUndef(I->getType())); 1581 BB->getInstList().erase(I); 1582 MadeChanges = true; 1583 ++NumInstRemoved; 1584 } 1585 } else { 1586 // Iterate over all of the instructions in a function, replacing them with 1587 // constants if we have found them to be of constant values. 1588 // 1589 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1590 Instruction *Inst = BI++; 1591 if (Inst->getType() == Type::VoidTy || 1592 isa<TerminatorInst>(Inst)) 1593 continue; 1594 1595 LatticeVal &IV = Values[Inst]; 1596 if (!IV.isConstant() && !IV.isUndefined()) 1597 continue; 1598 1599 Constant *Const = IV.isConstant() 1600 ? IV.getConstant() : Context->getUndef(Inst->getType()); 1601 DOUT << " Constant: " << *Const << " = " << *Inst; 1602 1603 // Replaces all of the uses of a variable with uses of the constant. 1604 Inst->replaceAllUsesWith(Const); 1605 1606 // Delete the instruction. 1607 Inst->eraseFromParent(); 1608 1609 // Hey, we just changed something! 1610 MadeChanges = true; 1611 ++NumInstRemoved; 1612 } 1613 } 1614 1615 return MadeChanges; 1616} 1617 1618namespace { 1619 //===--------------------------------------------------------------------===// 1620 // 1621 /// IPSCCP Class - This class implements interprocedural Sparse Conditional 1622 /// Constant Propagation. 1623 /// 1624 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass { 1625 static char ID; 1626 IPSCCP() : ModulePass(&ID) {} 1627 bool runOnModule(Module &M); 1628 }; 1629} // end anonymous namespace 1630 1631char IPSCCP::ID = 0; 1632static RegisterPass<IPSCCP> 1633Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation"); 1634 1635// createIPSCCPPass - This is the public interface to this file... 1636ModulePass *llvm::createIPSCCPPass() { 1637 return new IPSCCP(); 1638} 1639 1640 1641static bool AddressIsTaken(GlobalValue *GV) { 1642 // Delete any dead constantexpr klingons. 1643 GV->removeDeadConstantUsers(); 1644 1645 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); 1646 UI != E; ++UI) 1647 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { 1648 if (SI->getOperand(0) == GV || SI->isVolatile()) 1649 return true; // Storing addr of GV. 1650 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) { 1651 // Make sure we are calling the function, not passing the address. 1652 CallSite CS = CallSite::get(cast<Instruction>(*UI)); 1653 if (CS.hasArgument(GV)) 1654 return true; 1655 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 1656 if (LI->isVolatile()) 1657 return true; 1658 } else { 1659 return true; 1660 } 1661 return false; 1662} 1663 1664bool IPSCCP::runOnModule(Module &M) { 1665 SCCPSolver Solver; 1666 1667 // Loop over all functions, marking arguments to those with their addresses 1668 // taken or that are external as overdefined. 1669 // 1670 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 1671 if (!F->hasLocalLinkage() || AddressIsTaken(F)) { 1672 if (!F->isDeclaration()) 1673 Solver.MarkBlockExecutable(F->begin()); 1674 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1675 AI != E; ++AI) 1676 Solver.markOverdefined(AI); 1677 } else { 1678 Solver.AddTrackedFunction(F); 1679 } 1680 1681 // Loop over global variables. We inform the solver about any internal global 1682 // variables that do not have their 'addresses taken'. If they don't have 1683 // their addresses taken, we can propagate constants through them. 1684 for (Module::global_iterator G = M.global_begin(), E = M.global_end(); 1685 G != E; ++G) 1686 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G)) 1687 Solver.TrackValueOfGlobalVariable(G); 1688 1689 // Solve for constants. 1690 bool ResolvedUndefs = true; 1691 while (ResolvedUndefs) { 1692 Solver.Solve(); 1693 1694 DOUT << "RESOLVING UNDEFS\n"; 1695 ResolvedUndefs = false; 1696 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) 1697 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F); 1698 } 1699 1700 bool MadeChanges = false; 1701 1702 // Iterate over all of the instructions in the module, replacing them with 1703 // constants if we have found them to be of constant values. 1704 // 1705 SmallVector<Instruction*, 512> Insts; 1706 SmallVector<BasicBlock*, 512> BlocksToErase; 1707 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping(); 1708 1709 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 1710 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 1711 AI != E; ++AI) 1712 if (!AI->use_empty()) { 1713 LatticeVal &IV = Values[AI]; 1714 if (IV.isConstant() || IV.isUndefined()) { 1715 Constant *CST = IV.isConstant() ? 1716 IV.getConstant() : Context->getUndef(AI->getType()); 1717 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n"; 1718 1719 // Replaces all of the uses of a variable with uses of the 1720 // constant. 1721 AI->replaceAllUsesWith(CST); 1722 ++IPNumArgsElimed; 1723 } 1724 } 1725 1726 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 1727 if (!Solver.isBlockExecutable(BB)) { 1728 DOUT << " BasicBlock Dead:" << *BB; 1729 ++IPNumDeadBlocks; 1730 1731 // Delete the instructions backwards, as it has a reduced likelihood of 1732 // having to update as many def-use and use-def chains. 1733 TerminatorInst *TI = BB->getTerminator(); 1734 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I) 1735 Insts.push_back(I); 1736 1737 while (!Insts.empty()) { 1738 Instruction *I = Insts.back(); 1739 Insts.pop_back(); 1740 if (!I->use_empty()) 1741 I->replaceAllUsesWith(Context->getUndef(I->getType())); 1742 BB->getInstList().erase(I); 1743 MadeChanges = true; 1744 ++IPNumInstRemoved; 1745 } 1746 1747 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 1748 BasicBlock *Succ = TI->getSuccessor(i); 1749 if (!Succ->empty() && isa<PHINode>(Succ->begin())) 1750 TI->getSuccessor(i)->removePredecessor(BB); 1751 } 1752 if (!TI->use_empty()) 1753 TI->replaceAllUsesWith(Context->getUndef(TI->getType())); 1754 BB->getInstList().erase(TI); 1755 1756 if (&*BB != &F->front()) 1757 BlocksToErase.push_back(BB); 1758 else 1759 new UnreachableInst(BB); 1760 1761 } else { 1762 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) { 1763 Instruction *Inst = BI++; 1764 if (Inst->getType() == Type::VoidTy) 1765 continue; 1766 1767 LatticeVal &IV = Values[Inst]; 1768 if (!IV.isConstant() && !IV.isUndefined()) 1769 continue; 1770 1771 Constant *Const = IV.isConstant() 1772 ? IV.getConstant() : Context->getUndef(Inst->getType()); 1773 DOUT << " Constant: " << *Const << " = " << *Inst; 1774 1775 // Replaces all of the uses of a variable with uses of the 1776 // constant. 1777 Inst->replaceAllUsesWith(Const); 1778 1779 // Delete the instruction. 1780 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst)) 1781 Inst->eraseFromParent(); 1782 1783 // Hey, we just changed something! 1784 MadeChanges = true; 1785 ++IPNumInstRemoved; 1786 } 1787 } 1788 1789 // Now that all instructions in the function are constant folded, erase dead 1790 // blocks, because we can now use ConstantFoldTerminator to get rid of 1791 // in-edges. 1792 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) { 1793 // If there are any PHI nodes in this successor, drop entries for BB now. 1794 BasicBlock *DeadBB = BlocksToErase[i]; 1795 while (!DeadBB->use_empty()) { 1796 Instruction *I = cast<Instruction>(DeadBB->use_back()); 1797 bool Folded = ConstantFoldTerminator(I->getParent()); 1798 if (!Folded) { 1799 // The constant folder may not have been able to fold the terminator 1800 // if this is a branch or switch on undef. Fold it manually as a 1801 // branch to the first successor. 1802#ifndef NDEBUG 1803 if (BranchInst *BI = dyn_cast<BranchInst>(I)) { 1804 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) && 1805 "Branch should be foldable!"); 1806 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 1807 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold"); 1808 } else { 1809 LLVM_UNREACHABLE("Didn't fold away reference to block!"); 1810 } 1811#endif 1812 1813 // Make this an uncond branch to the first successor. 1814 TerminatorInst *TI = I->getParent()->getTerminator(); 1815 BranchInst::Create(TI->getSuccessor(0), TI); 1816 1817 // Remove entries in successor phi nodes to remove edges. 1818 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i) 1819 TI->getSuccessor(i)->removePredecessor(TI->getParent()); 1820 1821 // Remove the old terminator. 1822 TI->eraseFromParent(); 1823 } 1824 } 1825 1826 // Finally, delete the basic block. 1827 F->getBasicBlockList().erase(DeadBB); 1828 } 1829 BlocksToErase.clear(); 1830 } 1831 1832 // If we inferred constant or undef return values for a function, we replaced 1833 // all call uses with the inferred value. This means we don't need to bother 1834 // actually returning anything from the function. Replace all return 1835 // instructions with return undef. 1836 // TODO: Process multiple value ret instructions also. 1837 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals(); 1838 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(), 1839 E = RV.end(); I != E; ++I) 1840 if (!I->second.isOverdefined() && 1841 I->first->getReturnType() != Type::VoidTy) { 1842 Function *F = I->first; 1843 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 1844 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) 1845 if (!isa<UndefValue>(RI->getOperand(0))) 1846 RI->setOperand(0, Context->getUndef(F->getReturnType())); 1847 } 1848 1849 // If we infered constant or undef values for globals variables, we can delete 1850 // the global and any stores that remain to it. 1851 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals(); 1852 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(), 1853 E = TG.end(); I != E; ++I) { 1854 GlobalVariable *GV = I->first; 1855 assert(!I->second.isOverdefined() && 1856 "Overdefined values should have been taken out of the map!"); 1857 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n"; 1858 while (!GV->use_empty()) { 1859 StoreInst *SI = cast<StoreInst>(GV->use_back()); 1860 SI->eraseFromParent(); 1861 } 1862 M.getGlobalList().erase(GV); 1863 ++IPNumGlobalConst; 1864 } 1865 1866 return MadeChanges; 1867} 1868