1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements sparse conditional constant propagation and merging:
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
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.
22 //===----------------------------------------------------------------------===//
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/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/InstVisitor.h"
39 #include "llvm/Support/raw_ostream.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"
50 STATISTIC(NumInstRemoved, "Number of instructions removed");
51 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
53 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
54 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
55 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
56 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
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.
64 /// undefined - This LLVM Value has no known value yet.
67 /// constant - This LLVM Value has a specific constant value.
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
76 /// overdefined - This instruction is not known to be constant, and we know
79 } LatticeValue; // The current lattice position
81 Constant *ConstantVal; // If Constant value, the current value
83 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
85 // markOverdefined - Return true if this is a new status to be in...
86 inline bool markOverdefined() {
87 if (LatticeValue != overdefined) {
88 LatticeValue = overdefined;
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");
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;
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;
114 assert(ConstantVal == V && "Marking constant with different value");
119 inline void markForcedConstant(Constant *V) {
120 assert(LatticeValue == undefined && "Can't force a defined value!");
121 LatticeValue = forcedconstant;
125 inline bool isUndefined() const { return LatticeValue == undefined; }
126 inline bool isConstant() const {
127 return LatticeValue == constant || LatticeValue == forcedconstant;
129 inline bool isOverdefined() const { return LatticeValue == overdefined; }
131 inline Constant *getConstant() const {
132 assert(isConstant() && "Cannot get the constant of a non-constant!");
137 //===----------------------------------------------------------------------===//
139 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
140 /// Constant Propagation.
142 class 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.
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;
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;
158 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
159 /// that return multiple values.
160 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
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
168 SmallVector<Value*, 64> OverdefinedInstWorkList;
169 SmallVector<Value*, 64> InstWorkList;
172 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
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;
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;
183 void setContext(LLVMContext *C) { Context = C; }
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 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
189 BBExecutable.insert(BB); // Basic block is executable!
190 BBWorkList.push_back(BB); // Add the block to the work list!
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());
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),
217 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
220 /// Solve - Solve for constants and executable blocks.
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
229 bool ResolvedUndefsIn(Function &F);
231 bool isBlockExecutable(BasicBlock *BB) const {
232 return BBExecutable.count(BB);
235 /// getValueMapping - Once we have solved for constants, return the mapping of
236 /// LLVM values to LatticeVals.
237 std::map<Value*, LatticeVal> &getValueMapping() {
241 /// getTrackedRetVals - Get the inferred return value map.
243 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
244 return TrackedRetVals;
247 /// getTrackedGlobals - Get and return the set of inferred initializers for
248 /// global variables.
249 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
250 return TrackedGlobals;
253 inline void markOverdefined(Value *V) {
254 markOverdefined(ValueState[V], V);
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.
262 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
263 if (IV.markConstant(C)) {
264 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
265 InstWorkList.push_back(V);
269 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
270 IV.markForcedConstant(C);
271 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
272 InstWorkList.push_back(V);
275 inline void markConstant(Value *V, Constant *C) {
276 markConstant(ValueState[V], V, C);
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(errs() << "markOverdefined: ";
285 if (Function *F = dyn_cast<Function>(V))
286 errs() << "Function '" << F->getName() << "'\n";
288 errs() << *V << '\n');
289 // Only instructions go on the work list
290 OverdefinedInstWorkList.push_back(V);
294 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
295 if (IV.isOverdefined() || MergeWithV.isUndefined())
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);
305 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
306 return mergeInValue(ValueState[V], V, MergeWithV);
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.
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
320 if (Constant *C = dyn_cast<Constant>(V)) {
321 if (isa<UndefValue>(V)) {
322 // Nothing to do, remain undefined.
324 LatticeVal &LV = ValueState[C];
325 LV.markConstant(C); // Constants are constant
329 // All others are underdefined by default...
330 return ValueState[V];
333 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
334 // work list if it is not already executable...
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!
340 if (BBExecutable.count(Dest)) {
341 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
342 << " -> " << Dest->getName() << "\n");
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));
351 MarkBlockExecutable(Dest);
355 // getFeasibleSuccessors - Return a vector of booleans to indicate which
356 // successors are reachable from a given terminator instruction.
358 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
360 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
361 // block to the 'To' basic block is currently feasible...
363 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
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.
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?
377 friend class InstVisitor<SCCPSolver>;
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.
383 void visitPHINode(PHINode &I);
386 void visitReturnInst(ReturnInst &I);
387 void visitTerminatorInst(TerminatorInst &TI);
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);
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) {
404 visitCallSite(CallSite::get(&I));
406 void visitInvokeInst (InvokeInst &II) {
407 visitCallSite(CallSite::get(&II));
408 visitTerminatorInst(II);
410 void visitCallSite (CallSite CS);
411 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
412 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
413 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
414 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
415 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
416 void visitFreeInst (Instruction &I) { /*returns void*/ }
418 void visitInstruction(Instruction &I) {
419 // If a new instruction is added to LLVM that we don't handle...
420 errs() << "SCCP: Don't know how to handle: " << I;
421 markOverdefined(&I); // Just in case
425 } // end anonymous namespace
428 // getFeasibleSuccessors - Return a vector of booleans to indicate which
429 // successors are reachable from a given terminator instruction.
431 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
432 SmallVector<bool, 16> &Succs) {
433 Succs.resize(TI.getNumSuccessors());
434 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
435 if (BI->isUnconditional()) {
438 LatticeVal &BCValue = getValueState(BI->getCondition());
439 if (BCValue.isOverdefined() ||
440 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
441 // Overdefined condition variables, and branches on unfoldable constant
442 // conditions, mean the branch could go either way.
443 Succs[0] = Succs[1] = true;
444 } else if (BCValue.isConstant()) {
445 // Constant condition variables mean the branch can only go a single way
446 Succs[BCValue.getConstant() == ConstantInt::getFalse(*Context)] = true;
449 } else if (isa<InvokeInst>(&TI)) {
450 // Invoke instructions successors are always executable.
451 Succs[0] = Succs[1] = true;
452 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
453 LatticeVal &SCValue = getValueState(SI->getCondition());
454 if (SCValue.isOverdefined() || // Overdefined condition?
455 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
456 // All destinations are executable!
457 Succs.assign(TI.getNumSuccessors(), true);
458 } else if (SCValue.isConstant())
459 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
461 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
466 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
467 // block to the 'To' basic block is currently feasible...
469 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
470 assert(BBExecutable.count(To) && "Dest should always be alive!");
472 // Make sure the source basic block is executable!!
473 if (!BBExecutable.count(From)) return false;
475 // Check to make sure this edge itself is actually feasible now...
476 TerminatorInst *TI = From->getTerminator();
477 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
478 if (BI->isUnconditional())
481 LatticeVal &BCValue = getValueState(BI->getCondition());
482 if (BCValue.isOverdefined()) {
483 // Overdefined condition variables mean the branch could go either way.
485 } else if (BCValue.isConstant()) {
486 // Not branching on an evaluatable constant?
487 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
489 // Constant condition variables mean the branch can only go a single way
490 return BI->getSuccessor(BCValue.getConstant() ==
491 ConstantInt::getFalse(*Context)) == To;
495 } else if (isa<InvokeInst>(TI)) {
496 // Invoke instructions successors are always executable.
498 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
499 LatticeVal &SCValue = getValueState(SI->getCondition());
500 if (SCValue.isOverdefined()) { // Overdefined condition?
501 // All destinations are executable!
503 } else if (SCValue.isConstant()) {
504 Constant *CPV = SCValue.getConstant();
505 if (!isa<ConstantInt>(CPV))
506 return true; // not a foldable constant?
508 // Make sure to skip the "default value" which isn't a value
509 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
510 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
511 return SI->getSuccessor(i) == To;
513 // Constant value not equal to any of the branches... must execute
514 // default branch then...
515 return SI->getDefaultDest() == To;
520 errs() << "Unknown terminator instruction: " << *TI << '\n';
526 // visit Implementations - Something changed in this instruction... Either an
527 // operand made a transition, or the instruction is newly executable. Change
528 // the value type of I to reflect these changes if appropriate. This method
529 // makes sure to do the following actions:
531 // 1. If a phi node merges two constants in, and has conflicting value coming
532 // from different branches, or if the PHI node merges in an overdefined
533 // value, then the PHI node becomes overdefined.
534 // 2. If a phi node merges only constants in, and they all agree on value, the
535 // PHI node becomes a constant value equal to that.
536 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
537 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
538 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
539 // 6. If a conditional branch has a value that is constant, make the selected
540 // destination executable
541 // 7. If a conditional branch has a value that is overdefined, make all
542 // successors executable.
544 void SCCPSolver::visitPHINode(PHINode &PN) {
545 LatticeVal &PNIV = getValueState(&PN);
546 if (PNIV.isOverdefined()) {
547 // There may be instructions using this PHI node that are not overdefined
548 // themselves. If so, make sure that they know that the PHI node operand
550 std::multimap<PHINode*, Instruction*>::iterator I, E;
551 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
553 SmallVector<Instruction*, 16> Users;
554 for (; I != E; ++I) Users.push_back(I->second);
555 while (!Users.empty()) {
560 return; // Quick exit
563 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
564 // and slow us down a lot. Just mark them overdefined.
565 if (PN.getNumIncomingValues() > 64) {
566 markOverdefined(PNIV, &PN);
570 // Look at all of the executable operands of the PHI node. If any of them
571 // are overdefined, the PHI becomes overdefined as well. If they are all
572 // constant, and they agree with each other, the PHI becomes the identical
573 // constant. If they are constant and don't agree, the PHI is overdefined.
574 // If there are no executable operands, the PHI remains undefined.
576 Constant *OperandVal = 0;
577 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
578 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
579 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
581 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
582 if (IV.isOverdefined()) { // PHI node becomes overdefined!
583 markOverdefined(&PN);
587 if (OperandVal == 0) { // Grab the first value...
588 OperandVal = IV.getConstant();
589 } else { // Another value is being merged in!
590 // There is already a reachable operand. If we conflict with it,
591 // then the PHI node becomes overdefined. If we agree with it, we
594 // Check to see if there are two different constants merging...
595 if (IV.getConstant() != OperandVal) {
596 // Yes there is. This means the PHI node is not constant.
597 // You must be overdefined poor PHI.
599 markOverdefined(&PN); // The PHI node now becomes overdefined
600 return; // I'm done analyzing you
606 // If we exited the loop, this means that the PHI node only has constant
607 // arguments that agree with each other(and OperandVal is the constant) or
608 // OperandVal is null because there are no defined incoming arguments. If
609 // this is the case, the PHI remains undefined.
612 markConstant(&PN, OperandVal); // Acquire operand value
615 void SCCPSolver::visitReturnInst(ReturnInst &I) {
616 if (I.getNumOperands() == 0) return; // Ret void
618 Function *F = I.getParent()->getParent();
619 // If we are tracking the return value of this function, merge it in.
620 if (!F->hasLocalLinkage())
623 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
624 DenseMap<Function*, LatticeVal>::iterator TFRVI =
625 TrackedRetVals.find(F);
626 if (TFRVI != TrackedRetVals.end() &&
627 !TFRVI->second.isOverdefined()) {
628 LatticeVal &IV = getValueState(I.getOperand(0));
629 mergeInValue(TFRVI->second, F, IV);
634 // Handle functions that return multiple values.
635 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
636 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
637 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
638 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
639 if (It == TrackedMultipleRetVals.end()) break;
640 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
642 } else if (!TrackedMultipleRetVals.empty() &&
643 I.getNumOperands() == 1 &&
644 isa<StructType>(I.getOperand(0)->getType())) {
645 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
647 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
648 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
649 if (It == TrackedMultipleRetVals.end()) break;
650 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
651 mergeInValue(It->second, F, getValueState(Val));
656 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
657 SmallVector<bool, 16> SuccFeasible;
658 getFeasibleSuccessors(TI, SuccFeasible);
660 BasicBlock *BB = TI.getParent();
662 // Mark all feasible successors executable...
663 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
665 markEdgeExecutable(BB, TI.getSuccessor(i));
668 void SCCPSolver::visitCastInst(CastInst &I) {
669 Value *V = I.getOperand(0);
670 LatticeVal &VState = getValueState(V);
671 if (VState.isOverdefined()) // Inherit overdefinedness of operand
673 else if (VState.isConstant()) // Propagate constant value
674 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
675 VState.getConstant(), I.getType()));
678 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
679 Value *Aggr = EVI.getAggregateOperand();
681 // If the operand to the extractvalue is an undef, the result is undef.
682 if (isa<UndefValue>(Aggr))
685 // Currently only handle single-index extractvalues.
686 if (EVI.getNumIndices() != 1) {
687 markOverdefined(&EVI);
692 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
693 F = CI->getCalledFunction();
694 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
695 F = II->getCalledFunction();
697 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
699 if (F == 0 || TrackedMultipleRetVals.empty()) {
700 markOverdefined(&EVI);
704 // See if we are tracking the result of the callee. If not tracking this
705 // function (for example, it is a declaration) just move to overdefined.
706 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
707 markOverdefined(&EVI);
711 // Otherwise, the value will be merged in here as a result of CallSite
715 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
716 Value *Aggr = IVI.getAggregateOperand();
717 Value *Val = IVI.getInsertedValueOperand();
719 // If the operands to the insertvalue are undef, the result is undef.
720 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
723 // Currently only handle single-index insertvalues.
724 if (IVI.getNumIndices() != 1) {
725 markOverdefined(&IVI);
729 // Currently only handle insertvalue instructions that are in a single-use
730 // chain that builds up a return value.
731 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
732 if (!TmpIVI->hasOneUse()) {
733 markOverdefined(&IVI);
736 const Value *V = *TmpIVI->use_begin();
737 if (isa<ReturnInst>(V))
739 TmpIVI = dyn_cast<InsertValueInst>(V);
741 markOverdefined(&IVI);
746 // See if we are tracking the result of the callee.
747 Function *F = IVI.getParent()->getParent();
748 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
749 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
751 // Merge in the inserted member value.
752 if (It != TrackedMultipleRetVals.end())
753 mergeInValue(It->second, F, getValueState(Val));
755 // Mark the aggregate result of the IVI overdefined; any tracking that we do
756 // will be done on the individual member values.
757 markOverdefined(&IVI);
760 void SCCPSolver::visitSelectInst(SelectInst &I) {
761 LatticeVal &CondValue = getValueState(I.getCondition());
762 if (CondValue.isUndefined())
764 if (CondValue.isConstant()) {
765 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
766 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
767 : I.getFalseValue()));
772 // Otherwise, the condition is overdefined or a constant we can't evaluate.
773 // See if we can produce something better than overdefined based on the T/F
775 LatticeVal &TVal = getValueState(I.getTrueValue());
776 LatticeVal &FVal = getValueState(I.getFalseValue());
778 // select ?, C, C -> C.
779 if (TVal.isConstant() && FVal.isConstant() &&
780 TVal.getConstant() == FVal.getConstant()) {
781 markConstant(&I, FVal.getConstant());
785 if (TVal.isUndefined()) { // select ?, undef, X -> X.
786 mergeInValue(&I, FVal);
787 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
788 mergeInValue(&I, TVal);
794 // Handle BinaryOperators and Shift Instructions...
795 void SCCPSolver::visitBinaryOperator(Instruction &I) {
796 LatticeVal &IV = ValueState[&I];
797 if (IV.isOverdefined()) return;
799 LatticeVal &V1State = getValueState(I.getOperand(0));
800 LatticeVal &V2State = getValueState(I.getOperand(1));
802 if (V1State.isOverdefined() || V2State.isOverdefined()) {
803 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
804 // operand is overdefined.
805 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
806 LatticeVal *NonOverdefVal = 0;
807 if (!V1State.isOverdefined()) {
808 NonOverdefVal = &V1State;
809 } else if (!V2State.isOverdefined()) {
810 NonOverdefVal = &V2State;
814 if (NonOverdefVal->isUndefined()) {
815 // Could annihilate value.
816 if (I.getOpcode() == Instruction::And)
817 markConstant(IV, &I, Constant::getNullValue(I.getType()));
818 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
819 markConstant(IV, &I, Constant::getAllOnesValue(PT));
822 Constant::getAllOnesValue(I.getType()));
825 if (I.getOpcode() == Instruction::And) {
826 if (NonOverdefVal->getConstant()->isNullValue()) {
827 markConstant(IV, &I, NonOverdefVal->getConstant());
828 return; // X and 0 = 0
831 if (ConstantInt *CI =
832 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
833 if (CI->isAllOnesValue()) {
834 markConstant(IV, &I, NonOverdefVal->getConstant());
835 return; // X or -1 = -1
843 // If both operands are PHI nodes, it is possible that this instruction has
844 // a constant value, despite the fact that the PHI node doesn't. Check for
845 // this condition now.
846 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
847 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
848 if (PN1->getParent() == PN2->getParent()) {
849 // Since the two PHI nodes are in the same basic block, they must have
850 // entries for the same predecessors. Walk the predecessor list, and
851 // if all of the incoming values are constants, and the result of
852 // evaluating this expression with all incoming value pairs is the
853 // same, then this expression is a constant even though the PHI node
854 // is not a constant!
856 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
857 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
858 BasicBlock *InBlock = PN1->getIncomingBlock(i);
860 getValueState(PN2->getIncomingValueForBlock(InBlock));
862 if (In1.isOverdefined() || In2.isOverdefined()) {
863 Result.markOverdefined();
864 break; // Cannot fold this operation over the PHI nodes!
865 } else if (In1.isConstant() && In2.isConstant()) {
867 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
869 if (Result.isUndefined())
870 Result.markConstant(V);
871 else if (Result.isConstant() && Result.getConstant() != V) {
872 Result.markOverdefined();
878 // If we found a constant value here, then we know the instruction is
879 // constant despite the fact that the PHI nodes are overdefined.
880 if (Result.isConstant()) {
881 markConstant(IV, &I, Result.getConstant());
882 // Remember that this instruction is virtually using the PHI node
884 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
885 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
887 } else if (Result.isUndefined()) {
891 // Okay, this really is overdefined now. Since we might have
892 // speculatively thought that this was not overdefined before, and
893 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
894 // make sure to clean out any entries that we put there, for
896 std::multimap<PHINode*, Instruction*>::iterator It, E;
897 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
899 if (It->second == &I) {
900 UsersOfOverdefinedPHIs.erase(It++);
904 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
906 if (It->second == &I) {
907 UsersOfOverdefinedPHIs.erase(It++);
913 markOverdefined(IV, &I);
914 } else if (V1State.isConstant() && V2State.isConstant()) {
916 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
917 V2State.getConstant()));
921 // Handle ICmpInst instruction...
922 void SCCPSolver::visitCmpInst(CmpInst &I) {
923 LatticeVal &IV = ValueState[&I];
924 if (IV.isOverdefined()) return;
926 LatticeVal &V1State = getValueState(I.getOperand(0));
927 LatticeVal &V2State = getValueState(I.getOperand(1));
929 if (V1State.isOverdefined() || V2State.isOverdefined()) {
930 // If both operands are PHI nodes, it is possible that this instruction has
931 // a constant value, despite the fact that the PHI node doesn't. Check for
932 // this condition now.
933 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
934 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
935 if (PN1->getParent() == PN2->getParent()) {
936 // Since the two PHI nodes are in the same basic block, they must have
937 // entries for the same predecessors. Walk the predecessor list, and
938 // if all of the incoming values are constants, and the result of
939 // evaluating this expression with all incoming value pairs is the
940 // same, then this expression is a constant even though the PHI node
941 // is not a constant!
943 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
944 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
945 BasicBlock *InBlock = PN1->getIncomingBlock(i);
947 getValueState(PN2->getIncomingValueForBlock(InBlock));
949 if (In1.isOverdefined() || In2.isOverdefined()) {
950 Result.markOverdefined();
951 break; // Cannot fold this operation over the PHI nodes!
952 } else if (In1.isConstant() && In2.isConstant()) {
953 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
956 if (Result.isUndefined())
957 Result.markConstant(V);
958 else if (Result.isConstant() && Result.getConstant() != V) {
959 Result.markOverdefined();
965 // If we found a constant value here, then we know the instruction is
966 // constant despite the fact that the PHI nodes are overdefined.
967 if (Result.isConstant()) {
968 markConstant(IV, &I, Result.getConstant());
969 // Remember that this instruction is virtually using the PHI node
971 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
972 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
974 } else if (Result.isUndefined()) {
978 // Okay, this really is overdefined now. Since we might have
979 // speculatively thought that this was not overdefined before, and
980 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
981 // make sure to clean out any entries that we put there, for
983 std::multimap<PHINode*, Instruction*>::iterator It, E;
984 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
986 if (It->second == &I) {
987 UsersOfOverdefinedPHIs.erase(It++);
991 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
993 if (It->second == &I) {
994 UsersOfOverdefinedPHIs.erase(It++);
1000 markOverdefined(IV, &I);
1001 } else if (V1State.isConstant() && V2State.isConstant()) {
1002 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
1003 V1State.getConstant(),
1004 V2State.getConstant()));
1008 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1009 // FIXME : SCCP does not handle vectors properly.
1010 markOverdefined(&I);
1014 LatticeVal &ValState = getValueState(I.getOperand(0));
1015 LatticeVal &IdxState = getValueState(I.getOperand(1));
1017 if (ValState.isOverdefined() || IdxState.isOverdefined())
1018 markOverdefined(&I);
1019 else if(ValState.isConstant() && IdxState.isConstant())
1020 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1021 IdxState.getConstant()));
1025 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1026 // FIXME : SCCP does not handle vectors properly.
1027 markOverdefined(&I);
1030 LatticeVal &ValState = getValueState(I.getOperand(0));
1031 LatticeVal &EltState = getValueState(I.getOperand(1));
1032 LatticeVal &IdxState = getValueState(I.getOperand(2));
1034 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1035 IdxState.isOverdefined())
1036 markOverdefined(&I);
1037 else if(ValState.isConstant() && EltState.isConstant() &&
1038 IdxState.isConstant())
1039 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1040 EltState.getConstant(),
1041 IdxState.getConstant()));
1042 else if (ValState.isUndefined() && EltState.isConstant() &&
1043 IdxState.isConstant())
1044 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1045 EltState.getConstant(),
1046 IdxState.getConstant()));
1050 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1051 // FIXME : SCCP does not handle vectors properly.
1052 markOverdefined(&I);
1055 LatticeVal &V1State = getValueState(I.getOperand(0));
1056 LatticeVal &V2State = getValueState(I.getOperand(1));
1057 LatticeVal &MaskState = getValueState(I.getOperand(2));
1059 if (MaskState.isUndefined() ||
1060 (V1State.isUndefined() && V2State.isUndefined()))
1061 return; // Undefined output if mask or both inputs undefined.
1063 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1064 MaskState.isOverdefined()) {
1065 markOverdefined(&I);
1067 // A mix of constant/undef inputs.
1068 Constant *V1 = V1State.isConstant() ?
1069 V1State.getConstant() : UndefValue::get(I.getType());
1070 Constant *V2 = V2State.isConstant() ?
1071 V2State.getConstant() : UndefValue::get(I.getType());
1072 Constant *Mask = MaskState.isConstant() ?
1073 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1074 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1079 // Handle getelementptr instructions... if all operands are constants then we
1080 // can turn this into a getelementptr ConstantExpr.
1082 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1083 LatticeVal &IV = ValueState[&I];
1084 if (IV.isOverdefined()) return;
1086 SmallVector<Constant*, 8> Operands;
1087 Operands.reserve(I.getNumOperands());
1089 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1090 LatticeVal &State = getValueState(I.getOperand(i));
1091 if (State.isUndefined())
1092 return; // Operands are not resolved yet...
1093 else if (State.isOverdefined()) {
1094 markOverdefined(IV, &I);
1097 assert(State.isConstant() && "Unknown state!");
1098 Operands.push_back(State.getConstant());
1101 Constant *Ptr = Operands[0];
1102 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1104 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1108 void SCCPSolver::visitStoreInst(Instruction &SI) {
1109 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1111 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1112 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1113 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1115 // Get the value we are storing into the global.
1116 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1118 mergeInValue(I->second, GV, PtrVal);
1119 if (I->second.isOverdefined())
1120 TrackedGlobals.erase(I); // No need to keep tracking this!
1124 // Handle load instructions. If the operand is a constant pointer to a constant
1125 // global, we can replace the load with the loaded constant value!
1126 void SCCPSolver::visitLoadInst(LoadInst &I) {
1127 LatticeVal &IV = ValueState[&I];
1128 if (IV.isOverdefined()) return;
1130 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1131 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1132 if (PtrVal.isConstant() && !I.isVolatile()) {
1133 Value *Ptr = PtrVal.getConstant();
1134 // TODO: Consider a target hook for valid address spaces for this xform.
1135 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
1136 // load null -> null
1137 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1141 // Transform load (constant global) into the value loaded.
1142 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1143 if (GV->isConstant()) {
1144 if (GV->hasDefinitiveInitializer()) {
1145 markConstant(IV, &I, GV->getInitializer());
1148 } else if (!TrackedGlobals.empty()) {
1149 // If we are tracking this global, merge in the known value for it.
1150 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1151 TrackedGlobals.find(GV);
1152 if (It != TrackedGlobals.end()) {
1153 mergeInValue(IV, &I, It->second);
1159 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1161 if (CE->getOpcode() == Instruction::GetElementPtr)
1162 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1163 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1165 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1166 markConstant(IV, &I, V);
1171 // Otherwise we cannot say for certain what value this load will produce.
1173 markOverdefined(IV, &I);
1176 void SCCPSolver::visitCallSite(CallSite CS) {
1177 Function *F = CS.getCalledFunction();
1178 Instruction *I = CS.getInstruction();
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()) {
1185 // Void return and not tracking callee, just bail.
1186 if (I->getType()->isVoidTy()) return;
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)) {
1193 SmallVector<Constant*, 8> Operands;
1194 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1196 LatticeVal &State = getValueState(*AI);
1197 if (State.isUndefined())
1198 return; // Operands are not resolved yet.
1199 else if (State.isOverdefined()) {
1203 assert(State.isConstant() && "Unknown state!");
1204 Operands.push_back(State.getConstant());
1207 // If we can constant fold this, mark the result of the call as a
1209 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
1215 // Otherwise, we don't know anything about this call, mark it overdefined.
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;
1233 // Need to mark as overdefined, otherwise it stays undefined which
1234 // creates extractvalue undef, <idx>
1236 // If we are tracking this callee, propagate the return values of the call
1237 // into this call site. We do this by walking all the uses. Single-index
1238 // ExtractValueInst uses can be tracked; anything more complicated is
1239 // currently handled conservatively.
1240 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1242 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1243 if (EVI->getNumIndices() == 1) {
1245 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
1249 // The aggregate value is used in a way not handled here. Assume nothing.
1250 markOverdefined(*UI);
1253 // Otherwise we're not tracking this callee, so handle it in the
1254 // common path above.
1255 goto CallOverdefined;
1258 // Finally, if this is the first call to the function hit, mark its entry
1259 // block executable.
1260 if (!BBExecutable.count(F->begin()))
1261 MarkBlockExecutable(F->begin());
1263 // Propagate information from this call site into the callee.
1264 CallSite::arg_iterator CAI = CS.arg_begin();
1265 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1266 AI != E; ++AI, ++CAI) {
1267 LatticeVal &IV = ValueState[AI];
1268 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1269 IV.markOverdefined();
1272 if (!IV.isOverdefined())
1273 mergeInValue(IV, AI, getValueState(*CAI));
1277 void SCCPSolver::Solve() {
1278 // Process the work lists until they are empty!
1279 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1280 !OverdefinedInstWorkList.empty()) {
1281 // Process the instruction work list...
1282 while (!OverdefinedInstWorkList.empty()) {
1283 Value *I = OverdefinedInstWorkList.back();
1284 OverdefinedInstWorkList.pop_back();
1286 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
1288 // "I" got into the work list because it either made the transition from
1289 // bottom to constant
1291 // Anything on this worklist that is overdefined need not be visited
1292 // since all of its users will have already been marked as overdefined
1293 // Update all of the users of this instruction's value...
1295 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1297 OperandChangedState(*UI);
1299 // Process the instruction work list...
1300 while (!InstWorkList.empty()) {
1301 Value *I = InstWorkList.back();
1302 InstWorkList.pop_back();
1304 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
1306 // "I" got into the work list because it either made the transition from
1307 // bottom to constant
1309 // Anything on this worklist that is overdefined need not be visited
1310 // since all of its users will have already been marked as overdefined.
1311 // Update all of the users of this instruction's value...
1313 if (!getValueState(I).isOverdefined())
1314 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1316 OperandChangedState(*UI);
1319 // Process the basic block work list...
1320 while (!BBWorkList.empty()) {
1321 BasicBlock *BB = BBWorkList.back();
1322 BBWorkList.pop_back();
1324 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
1326 // Notify all instructions in this basic block that they are newly
1333 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1334 /// that branches on undef values cannot reach any of their successors.
1335 /// However, this is not a safe assumption. After we solve dataflow, this
1336 /// method should be use to handle this. If this returns true, the solver
1337 /// should be rerun.
1339 /// This method handles this by finding an unresolved branch and marking it one
1340 /// of the edges from the block as being feasible, even though the condition
1341 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1342 /// CFG and only slightly pessimizes the analysis results (by marking one,
1343 /// potentially infeasible, edge feasible). This cannot usefully modify the
1344 /// constraints on the condition of the branch, as that would impact other users
1347 /// This scan also checks for values that use undefs, whose results are actually
1348 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1349 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1350 /// even if X isn't defined.
1351 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1352 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1353 if (!BBExecutable.count(BB))
1356 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1357 // Look for instructions which produce undef values.
1358 if (I->getType()->isVoidTy()) continue;
1360 LatticeVal &LV = getValueState(I);
1361 if (!LV.isUndefined()) continue;
1363 // Get the lattice values of the first two operands for use below.
1364 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1366 if (I->getNumOperands() == 2) {
1367 // If this is a two-operand instruction, and if both operands are
1368 // undefs, the result stays undef.
1369 Op1LV = getValueState(I->getOperand(1));
1370 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1374 // If this is an instructions whose result is defined even if the input is
1375 // not fully defined, propagate the information.
1376 const Type *ITy = I->getType();
1377 switch (I->getOpcode()) {
1378 default: break; // Leave the instruction as an undef.
1379 case Instruction::ZExt:
1380 // After a zero extend, we know the top part is zero. SExt doesn't have
1381 // to be handled here, because we don't know whether the top part is 1's
1383 assert(Op0LV.isUndefined());
1384 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1386 case Instruction::Mul:
1387 case Instruction::And:
1388 // undef * X -> 0. X could be zero.
1389 // undef & X -> 0. X could be zero.
1390 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1393 case Instruction::Or:
1394 // undef | X -> -1. X could be -1.
1395 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1396 markForcedConstant(LV, I,
1397 Constant::getAllOnesValue(PTy));
1399 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
1402 case Instruction::SDiv:
1403 case Instruction::UDiv:
1404 case Instruction::SRem:
1405 case Instruction::URem:
1406 // X / undef -> undef. No change.
1407 // X % undef -> undef. No change.
1408 if (Op1LV.isUndefined()) break;
1410 // undef / X -> 0. X could be maxint.
1411 // undef % X -> 0. X could be 1.
1412 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1415 case Instruction::AShr:
1416 // undef >>s X -> undef. No change.
1417 if (Op0LV.isUndefined()) break;
1419 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1420 if (Op0LV.isConstant())
1421 markForcedConstant(LV, I, Op0LV.getConstant());
1423 markOverdefined(LV, I);
1425 case Instruction::LShr:
1426 case Instruction::Shl:
1427 // undef >> X -> undef. No change.
1428 // undef << X -> undef. No change.
1429 if (Op0LV.isUndefined()) break;
1431 // X >> undef -> 0. X could be 0.
1432 // X << undef -> 0. X could be 0.
1433 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1435 case Instruction::Select:
1436 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1437 if (Op0LV.isUndefined()) {
1438 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1439 Op1LV = getValueState(I->getOperand(2));
1440 } else if (Op1LV.isUndefined()) {
1441 // c ? undef : undef -> undef. No change.
1442 Op1LV = getValueState(I->getOperand(2));
1443 if (Op1LV.isUndefined())
1445 // Otherwise, c ? undef : x -> x.
1447 // Leave Op1LV as Operand(1)'s LatticeValue.
1450 if (Op1LV.isConstant())
1451 markForcedConstant(LV, I, Op1LV.getConstant());
1453 markOverdefined(LV, I);
1455 case Instruction::Call:
1456 // If a call has an undef result, it is because it is constant foldable
1457 // but one of the inputs was undef. Just force the result to
1459 markOverdefined(LV, I);
1464 TerminatorInst *TI = BB->getTerminator();
1465 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1466 if (!BI->isConditional()) continue;
1467 if (!getValueState(BI->getCondition()).isUndefined())
1469 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1470 if (SI->getNumSuccessors()<2) // no cases
1472 if (!getValueState(SI->getCondition()).isUndefined())
1478 // If the edge to the second successor isn't thought to be feasible yet,
1479 // mark it so now. We pick the second one so that this goes to some
1480 // enumerated value in a switch instead of going to the default destination.
1481 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
1484 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1485 // and return. This will make other blocks reachable, which will allow new
1486 // values to be discovered and existing ones to be moved in the lattice.
1487 markEdgeExecutable(BB, TI->getSuccessor(1));
1489 // This must be a conditional branch of switch on undef. At this point,
1490 // force the old terminator to branch to the first successor. This is
1491 // required because we are now influencing the dataflow of the function with
1492 // the assumption that this edge is taken. If we leave the branch condition
1493 // as undef, then further analysis could think the undef went another way
1494 // leading to an inconsistent set of conclusions.
1495 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1496 BI->setCondition(ConstantInt::getFalse(*Context));
1498 SwitchInst *SI = cast<SwitchInst>(TI);
1499 SI->setCondition(SI->getCaseValue(1));
1510 //===--------------------------------------------------------------------===//
1512 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1513 /// Sparse Conditional Constant Propagator.
1515 struct SCCP : public FunctionPass {
1516 static char ID; // Pass identification, replacement for typeid
1517 SCCP() : FunctionPass(&ID) {}
1519 // runOnFunction - Run the Sparse Conditional Constant Propagation
1520 // algorithm, and return true if the function was modified.
1522 bool runOnFunction(Function &F);
1524 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1525 AU.setPreservesCFG();
1528 } // end anonymous namespace
1531 static RegisterPass<SCCP>
1532 X("sccp", "Sparse Conditional Constant Propagation");
1534 // createSCCPPass - This is the public interface to this file...
1535 FunctionPass *llvm::createSCCPPass() {
1540 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1541 // and return true if the function was modified.
1543 bool SCCP::runOnFunction(Function &F) {
1544 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
1546 Solver.setContext(&F.getContext());
1548 // Mark the first block of the function as being executable.
1549 Solver.MarkBlockExecutable(F.begin());
1551 // Mark all arguments to the function as being overdefined.
1552 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1553 Solver.markOverdefined(AI);
1555 // Solve for constants.
1556 bool ResolvedUndefs = true;
1557 while (ResolvedUndefs) {
1559 DEBUG(errs() << "RESOLVING UNDEFs\n");
1560 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1563 bool MadeChanges = false;
1565 // If we decided that there are basic blocks that are dead in this function,
1566 // delete their contents now. Note that we cannot actually delete the blocks,
1567 // as we cannot modify the CFG of the function.
1569 SmallVector<Instruction*, 512> Insts;
1570 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1572 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1573 if (!Solver.isBlockExecutable(BB)) {
1574 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1577 // Delete the instructions backwards, as it has a reduced likelihood of
1578 // having to update as many def-use and use-def chains.
1579 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1582 while (!Insts.empty()) {
1583 Instruction *I = Insts.back();
1585 if (!I->use_empty())
1586 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1587 BB->getInstList().erase(I);
1592 // Iterate over all of the instructions in a function, replacing them with
1593 // constants if we have found them to be of constant values.
1595 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1596 Instruction *Inst = BI++;
1597 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1600 LatticeVal &IV = Values[Inst];
1601 if (!IV.isConstant() && !IV.isUndefined())
1604 Constant *Const = IV.isConstant()
1605 ? IV.getConstant() : UndefValue::get(Inst->getType());
1606 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1608 // Replaces all of the uses of a variable with uses of the constant.
1609 Inst->replaceAllUsesWith(Const);
1611 // Delete the instruction.
1612 Inst->eraseFromParent();
1614 // Hey, we just changed something!
1624 //===--------------------------------------------------------------------===//
1626 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1627 /// Constant Propagation.
1629 struct IPSCCP : public ModulePass {
1631 IPSCCP() : ModulePass(&ID) {}
1632 bool runOnModule(Module &M);
1634 } // end anonymous namespace
1636 char IPSCCP::ID = 0;
1637 static RegisterPass<IPSCCP>
1638 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1640 // createIPSCCPPass - This is the public interface to this file...
1641 ModulePass *llvm::createIPSCCPPass() {
1642 return new IPSCCP();
1646 static bool AddressIsTaken(GlobalValue *GV) {
1647 // Delete any dead constantexpr klingons.
1648 GV->removeDeadConstantUsers();
1650 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1652 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1653 if (SI->getOperand(0) == GV || SI->isVolatile())
1654 return true; // Storing addr of GV.
1655 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1656 // Make sure we are calling the function, not passing the address.
1657 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1658 if (CS.hasArgument(GV))
1660 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1661 if (LI->isVolatile())
1669 bool IPSCCP::runOnModule(Module &M) {
1670 LLVMContext *Context = &M.getContext();
1673 Solver.setContext(Context);
1675 // Loop over all functions, marking arguments to those with their addresses
1676 // taken or that are external as overdefined.
1678 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1679 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
1680 if (!F->isDeclaration())
1681 Solver.MarkBlockExecutable(F->begin());
1682 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1684 Solver.markOverdefined(AI);
1686 Solver.AddTrackedFunction(F);
1689 // Loop over global variables. We inform the solver about any internal global
1690 // variables that do not have their 'addresses taken'. If they don't have
1691 // their addresses taken, we can propagate constants through them.
1692 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1694 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1695 Solver.TrackValueOfGlobalVariable(G);
1697 // Solve for constants.
1698 bool ResolvedUndefs = true;
1699 while (ResolvedUndefs) {
1702 DEBUG(errs() << "RESOLVING UNDEFS\n");
1703 ResolvedUndefs = false;
1704 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1705 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1708 bool MadeChanges = false;
1710 // Iterate over all of the instructions in the module, replacing them with
1711 // constants if we have found them to be of constant values.
1713 SmallVector<Instruction*, 512> Insts;
1714 SmallVector<BasicBlock*, 512> BlocksToErase;
1715 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1717 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1718 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1720 if (!AI->use_empty()) {
1721 LatticeVal &IV = Values[AI];
1722 if (IV.isConstant() || IV.isUndefined()) {
1723 Constant *CST = IV.isConstant() ?
1724 IV.getConstant() : UndefValue::get(AI->getType());
1725 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1727 // Replaces all of the uses of a variable with uses of the
1729 AI->replaceAllUsesWith(CST);
1734 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1735 if (!Solver.isBlockExecutable(BB)) {
1736 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1739 // Delete the instructions backwards, as it has a reduced likelihood of
1740 // having to update as many def-use and use-def chains.
1741 TerminatorInst *TI = BB->getTerminator();
1742 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1745 while (!Insts.empty()) {
1746 Instruction *I = Insts.back();
1748 if (!I->use_empty())
1749 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1750 BB->getInstList().erase(I);
1755 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1756 BasicBlock *Succ = TI->getSuccessor(i);
1757 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1758 TI->getSuccessor(i)->removePredecessor(BB);
1760 if (!TI->use_empty())
1761 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1762 BB->getInstList().erase(TI);
1764 if (&*BB != &F->front())
1765 BlocksToErase.push_back(BB);
1767 new UnreachableInst(M.getContext(), BB);
1770 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1771 Instruction *Inst = BI++;
1772 if (Inst->getType()->isVoidTy())
1775 LatticeVal &IV = Values[Inst];
1776 if (!IV.isConstant() && !IV.isUndefined())
1779 Constant *Const = IV.isConstant()
1780 ? IV.getConstant() : UndefValue::get(Inst->getType());
1781 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1783 // Replaces all of the uses of a variable with uses of the
1785 Inst->replaceAllUsesWith(Const);
1787 // Delete the instruction.
1788 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1789 Inst->eraseFromParent();
1791 // Hey, we just changed something!
1797 // Now that all instructions in the function are constant folded, erase dead
1798 // blocks, because we can now use ConstantFoldTerminator to get rid of
1800 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1801 // If there are any PHI nodes in this successor, drop entries for BB now.
1802 BasicBlock *DeadBB = BlocksToErase[i];
1803 while (!DeadBB->use_empty()) {
1804 Instruction *I = cast<Instruction>(DeadBB->use_back());
1805 bool Folded = ConstantFoldTerminator(I->getParent());
1807 // The constant folder may not have been able to fold the terminator
1808 // if this is a branch or switch on undef. Fold it manually as a
1809 // branch to the first successor.
1811 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1812 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1813 "Branch should be foldable!");
1814 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1815 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1817 llvm_unreachable("Didn't fold away reference to block!");
1821 // Make this an uncond branch to the first successor.
1822 TerminatorInst *TI = I->getParent()->getTerminator();
1823 BranchInst::Create(TI->getSuccessor(0), TI);
1825 // Remove entries in successor phi nodes to remove edges.
1826 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1827 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1829 // Remove the old terminator.
1830 TI->eraseFromParent();
1834 // Finally, delete the basic block.
1835 F->getBasicBlockList().erase(DeadBB);
1837 BlocksToErase.clear();
1840 // If we inferred constant or undef return values for a function, we replaced
1841 // all call uses with the inferred value. This means we don't need to bother
1842 // actually returning anything from the function. Replace all return
1843 // instructions with return undef.
1844 // TODO: Process multiple value ret instructions also.
1845 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1846 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1847 E = RV.end(); I != E; ++I)
1848 if (!I->second.isOverdefined() &&
1849 !I->first->getReturnType()->isVoidTy()) {
1850 Function *F = I->first;
1851 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1852 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1853 if (!isa<UndefValue>(RI->getOperand(0)))
1854 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1857 // If we infered constant or undef values for globals variables, we can delete
1858 // the global and any stores that remain to it.
1859 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1860 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1861 E = TG.end(); I != E; ++I) {
1862 GlobalVariable *GV = I->first;
1863 assert(!I->second.isOverdefined() &&
1864 "Overdefined values should have been taken out of the map!");
1865 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1866 while (!GV->use_empty()) {
1867 StoreInst *SI = cast<StoreInst>(GV->use_back());
1868 SI->eraseFromParent();
1870 M.getGlobalList().erase(GV);