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/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/InstVisitor.h"
39 #include "llvm/ADT/DenseMap.h"
40 #include "llvm/ADT/DenseSet.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/STLExtras.h"
49 STATISTIC(NumInstRemoved, "Number of instructions removed");
50 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
52 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
53 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
54 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
55 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
58 /// LatticeVal class - This class represents the different lattice values that
59 /// an LLVM value may occupy. It is a simple class with value semantics.
61 class VISIBILITY_HIDDEN LatticeVal {
63 /// undefined - This LLVM Value has no known value yet.
66 /// constant - This LLVM Value has a specific constant value.
69 /// forcedconstant - This LLVM Value was thought to be undef until
70 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
71 /// with another (different) constant, it goes to overdefined, instead of
75 /// overdefined - This instruction is not known to be constant, and we know
78 } LatticeValue; // The current lattice position
80 Constant *ConstantVal; // If Constant value, the current value
82 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
84 // markOverdefined - Return true if this is a new status to be in...
85 inline bool markOverdefined() {
86 if (LatticeValue != overdefined) {
87 LatticeValue = overdefined;
93 // markConstant - Return true if this is a new status for us.
94 inline bool markConstant(Constant *V) {
95 if (LatticeValue != constant) {
96 if (LatticeValue == undefined) {
97 LatticeValue = constant;
98 assert(V && "Marking constant with NULL");
101 assert(LatticeValue == forcedconstant &&
102 "Cannot move from overdefined to constant!");
103 // Stay at forcedconstant if the constant is the same.
104 if (V == ConstantVal) return false;
106 // Otherwise, we go to overdefined. Assumptions made based on the
107 // forced value are possibly wrong. Assuming this is another constant
108 // could expose a contradiction.
109 LatticeValue = overdefined;
113 assert(ConstantVal == V && "Marking constant with different value");
118 inline void markForcedConstant(Constant *V) {
119 assert(LatticeValue == undefined && "Can't force a defined value!");
120 LatticeValue = forcedconstant;
124 inline bool isUndefined() const { return LatticeValue == undefined; }
125 inline bool isConstant() const {
126 return LatticeValue == constant || LatticeValue == forcedconstant;
128 inline bool isOverdefined() const { return LatticeValue == overdefined; }
130 inline Constant *getConstant() const {
131 assert(isConstant() && "Cannot get the constant of a non-constant!");
136 //===----------------------------------------------------------------------===//
138 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
139 /// Constant Propagation.
141 class SCCPSolver : public InstVisitor<SCCPSolver> {
142 LLVMContext *Context;
143 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
144 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
146 /// GlobalValue - If we are tracking any values for the contents of a global
147 /// variable, we keep a mapping from the constant accessor to the element of
148 /// the global, to the currently known value. If the value becomes
149 /// overdefined, it's entry is simply removed from this map.
150 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
152 /// TrackedRetVals - If we are tracking arguments into and the return
153 /// value out of a function, it will have an entry in this map, indicating
154 /// what the known return value for the function is.
155 DenseMap<Function*, LatticeVal> TrackedRetVals;
157 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
158 /// that return multiple values.
159 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
161 // The reason for two worklists is that overdefined is the lowest state
162 // on the lattice, and moving things to overdefined as fast as possible
163 // makes SCCP converge much faster.
164 // By having a separate worklist, we accomplish this because everything
165 // possibly overdefined will become overdefined at the soonest possible
167 SmallVector<Value*, 64> OverdefinedInstWorkList;
168 SmallVector<Value*, 64> InstWorkList;
171 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
173 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
174 /// overdefined, despite the fact that the PHI node is overdefined.
175 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
177 /// KnownFeasibleEdges - Entries in this set are edges which have already had
178 /// PHI nodes retriggered.
179 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
180 DenseSet<Edge> KnownFeasibleEdges;
182 void setContext(LLVMContext *C) { Context = C; }
184 /// MarkBlockExecutable - This method can be used by clients to mark all of
185 /// the blocks that are known to be intrinsically live in the processed unit.
186 void MarkBlockExecutable(BasicBlock *BB) {
187 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
188 BBExecutable.insert(BB); // Basic block is executable!
189 BBWorkList.push_back(BB); // Add the block to the work list!
192 /// TrackValueOfGlobalVariable - Clients can use this method to
193 /// inform the SCCPSolver that it should track loads and stores to the
194 /// specified global variable if it can. This is only legal to call if
195 /// performing Interprocedural SCCP.
196 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
197 const Type *ElTy = GV->getType()->getElementType();
198 if (ElTy->isFirstClassType()) {
199 LatticeVal &IV = TrackedGlobals[GV];
200 if (!isa<UndefValue>(GV->getInitializer()))
201 IV.markConstant(GV->getInitializer());
205 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
206 /// and out of the specified function (which cannot have its address taken),
207 /// this method must be called.
208 void AddTrackedFunction(Function *F) {
209 assert(F->hasLocalLinkage() && "Can only track internal functions!");
210 // Add an entry, F -> undef.
211 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
212 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
213 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
216 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
219 /// Solve - Solve for constants and executable blocks.
223 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
224 /// that branches on undef values cannot reach any of their successors.
225 /// However, this is not a safe assumption. After we solve dataflow, this
226 /// method should be use to handle this. If this returns true, the solver
228 bool ResolvedUndefsIn(Function &F);
230 bool isBlockExecutable(BasicBlock *BB) const {
231 return BBExecutable.count(BB);
234 /// getValueMapping - Once we have solved for constants, return the mapping of
235 /// LLVM values to LatticeVals.
236 std::map<Value*, LatticeVal> &getValueMapping() {
240 /// getTrackedRetVals - Get the inferred return value map.
242 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
243 return TrackedRetVals;
246 /// getTrackedGlobals - Get and return the set of inferred initializers for
247 /// global variables.
248 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
249 return TrackedGlobals;
252 inline void markOverdefined(Value *V) {
253 markOverdefined(ValueState[V], V);
257 // markConstant - Make a value be marked as "constant". If the value
258 // is not already a constant, add it to the instruction work list so that
259 // the users of the instruction are updated later.
261 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
262 if (IV.markConstant(C)) {
263 DOUT << "markConstant: " << *C << ": " << *V;
264 InstWorkList.push_back(V);
268 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
269 IV.markForcedConstant(C);
270 DOUT << "markForcedConstant: " << *C << ": " << *V;
271 InstWorkList.push_back(V);
274 inline void markConstant(Value *V, Constant *C) {
275 markConstant(ValueState[V], V, C);
278 // markOverdefined - Make a value be marked as "overdefined". If the
279 // value is not already overdefined, add it to the overdefined instruction
280 // work list so that the users of the instruction are updated later.
281 inline void markOverdefined(LatticeVal &IV, Value *V) {
282 if (IV.markOverdefined()) {
283 DEBUG(DOUT << "markOverdefined: ";
284 if (Function *F = dyn_cast<Function>(V))
285 DOUT << "Function '" << F->getName() << "'\n";
288 // Only instructions go on the work list
289 OverdefinedInstWorkList.push_back(V);
293 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
294 if (IV.isOverdefined() || MergeWithV.isUndefined())
296 if (MergeWithV.isOverdefined())
297 markOverdefined(IV, V);
298 else if (IV.isUndefined())
299 markConstant(IV, V, MergeWithV.getConstant());
300 else if (IV.getConstant() != MergeWithV.getConstant())
301 markOverdefined(IV, V);
304 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
305 return mergeInValue(ValueState[V], V, MergeWithV);
309 // getValueState - Return the LatticeVal object that corresponds to the value.
310 // This function is necessary because not all values should start out in the
311 // underdefined state... Argument's should be overdefined, and
312 // constants should be marked as constants. If a value is not known to be an
313 // Instruction object, then use this accessor to get its value from the map.
315 inline LatticeVal &getValueState(Value *V) {
316 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
317 if (I != ValueState.end()) return I->second; // Common case, in the map
319 if (Constant *C = dyn_cast<Constant>(V)) {
320 if (isa<UndefValue>(V)) {
321 // Nothing to do, remain undefined.
323 LatticeVal &LV = ValueState[C];
324 LV.markConstant(C); // Constants are constant
328 // All others are underdefined by default...
329 return ValueState[V];
332 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
333 // work list if it is not already executable...
335 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
336 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
337 return; // This edge is already known to be executable!
339 if (BBExecutable.count(Dest)) {
340 DOUT << "Marking Edge Executable: " << Source->getNameStart()
341 << " -> " << Dest->getNameStart() << "\n";
343 // The destination is already executable, but we just made an edge
344 // feasible that wasn't before. Revisit the PHI nodes in the block
345 // because they have potentially new operands.
346 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
347 visitPHINode(*cast<PHINode>(I));
350 MarkBlockExecutable(Dest);
354 // getFeasibleSuccessors - Return a vector of booleans to indicate which
355 // successors are reachable from a given terminator instruction.
357 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
359 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
360 // block to the 'To' basic block is currently feasible...
362 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
364 // OperandChangedState - This method is invoked on all of the users of an
365 // instruction that was just changed state somehow.... Based on this
366 // information, we need to update the specified user of this instruction.
368 void OperandChangedState(User *U) {
369 // Only instructions use other variable values!
370 Instruction &I = cast<Instruction>(*U);
371 if (BBExecutable.count(I.getParent())) // Inst is executable?
376 friend class InstVisitor<SCCPSolver>;
378 // visit implementations - Something changed in this instruction... Either an
379 // operand made a transition, or the instruction is newly executable. Change
380 // the value type of I to reflect these changes if appropriate.
382 void visitPHINode(PHINode &I);
385 void visitReturnInst(ReturnInst &I);
386 void visitTerminatorInst(TerminatorInst &TI);
388 void visitCastInst(CastInst &I);
389 void visitSelectInst(SelectInst &I);
390 void visitBinaryOperator(Instruction &I);
391 void visitCmpInst(CmpInst &I);
392 void visitExtractElementInst(ExtractElementInst &I);
393 void visitInsertElementInst(InsertElementInst &I);
394 void visitShuffleVectorInst(ShuffleVectorInst &I);
395 void visitExtractValueInst(ExtractValueInst &EVI);
396 void visitInsertValueInst(InsertValueInst &IVI);
398 // Instructions that cannot be folded away...
399 void visitStoreInst (Instruction &I);
400 void visitLoadInst (LoadInst &I);
401 void visitGetElementPtrInst(GetElementPtrInst &I);
402 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
403 void visitInvokeInst (InvokeInst &II) {
404 visitCallSite(CallSite::get(&II));
405 visitTerminatorInst(II);
407 void visitCallSite (CallSite CS);
408 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
409 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
410 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
411 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
412 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
413 void visitFreeInst (Instruction &I) { /*returns void*/ }
415 void visitInstruction(Instruction &I) {
416 // If a new instruction is added to LLVM that we don't handle...
417 cerr << "SCCP: Don't know how to handle: " << I;
418 markOverdefined(&I); // Just in case
422 } // end anonymous namespace
425 // getFeasibleSuccessors - Return a vector of booleans to indicate which
426 // successors are reachable from a given terminator instruction.
428 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
429 SmallVector<bool, 16> &Succs) {
430 Succs.resize(TI.getNumSuccessors());
431 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
432 if (BI->isUnconditional()) {
435 LatticeVal &BCValue = getValueState(BI->getCondition());
436 if (BCValue.isOverdefined() ||
437 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
438 // Overdefined condition variables, and branches on unfoldable constant
439 // conditions, mean the branch could go either way.
440 Succs[0] = Succs[1] = true;
441 } else if (BCValue.isConstant()) {
442 // Constant condition variables mean the branch can only go a single way
443 Succs[BCValue.getConstant() == Context->getConstantIntFalse()] = true;
446 } else if (isa<InvokeInst>(&TI)) {
447 // Invoke instructions successors are always executable.
448 Succs[0] = Succs[1] = true;
449 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
450 LatticeVal &SCValue = getValueState(SI->getCondition());
451 if (SCValue.isOverdefined() || // Overdefined condition?
452 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
453 // All destinations are executable!
454 Succs.assign(TI.getNumSuccessors(), true);
455 } else if (SCValue.isConstant())
456 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
458 assert(0 && "SCCP: Don't know how to handle this terminator!");
463 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
464 // block to the 'To' basic block is currently feasible...
466 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
467 assert(BBExecutable.count(To) && "Dest should always be alive!");
469 // Make sure the source basic block is executable!!
470 if (!BBExecutable.count(From)) return false;
472 // Check to make sure this edge itself is actually feasible now...
473 TerminatorInst *TI = From->getTerminator();
474 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
475 if (BI->isUnconditional())
478 LatticeVal &BCValue = getValueState(BI->getCondition());
479 if (BCValue.isOverdefined()) {
480 // Overdefined condition variables mean the branch could go either way.
482 } else if (BCValue.isConstant()) {
483 // Not branching on an evaluatable constant?
484 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
486 // Constant condition variables mean the branch can only go a single way
487 return BI->getSuccessor(BCValue.getConstant() ==
488 Context->getConstantIntFalse()) == To;
492 } else if (isa<InvokeInst>(TI)) {
493 // Invoke instructions successors are always executable.
495 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
496 LatticeVal &SCValue = getValueState(SI->getCondition());
497 if (SCValue.isOverdefined()) { // Overdefined condition?
498 // All destinations are executable!
500 } else if (SCValue.isConstant()) {
501 Constant *CPV = SCValue.getConstant();
502 if (!isa<ConstantInt>(CPV))
503 return true; // not a foldable constant?
505 // Make sure to skip the "default value" which isn't a value
506 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
507 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
508 return SI->getSuccessor(i) == To;
510 // Constant value not equal to any of the branches... must execute
511 // default branch then...
512 return SI->getDefaultDest() == To;
516 cerr << "Unknown terminator instruction: " << *TI;
521 // visit Implementations - Something changed in this instruction... Either an
522 // operand made a transition, or the instruction is newly executable. Change
523 // the value type of I to reflect these changes if appropriate. This method
524 // makes sure to do the following actions:
526 // 1. If a phi node merges two constants in, and has conflicting value coming
527 // from different branches, or if the PHI node merges in an overdefined
528 // value, then the PHI node becomes overdefined.
529 // 2. If a phi node merges only constants in, and they all agree on value, the
530 // PHI node becomes a constant value equal to that.
531 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
532 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
533 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
534 // 6. If a conditional branch has a value that is constant, make the selected
535 // destination executable
536 // 7. If a conditional branch has a value that is overdefined, make all
537 // successors executable.
539 void SCCPSolver::visitPHINode(PHINode &PN) {
540 LatticeVal &PNIV = getValueState(&PN);
541 if (PNIV.isOverdefined()) {
542 // There may be instructions using this PHI node that are not overdefined
543 // themselves. If so, make sure that they know that the PHI node operand
545 std::multimap<PHINode*, Instruction*>::iterator I, E;
546 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
548 SmallVector<Instruction*, 16> Users;
549 for (; I != E; ++I) Users.push_back(I->second);
550 while (!Users.empty()) {
555 return; // Quick exit
558 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
559 // and slow us down a lot. Just mark them overdefined.
560 if (PN.getNumIncomingValues() > 64) {
561 markOverdefined(PNIV, &PN);
565 // Look at all of the executable operands of the PHI node. If any of them
566 // are overdefined, the PHI becomes overdefined as well. If they are all
567 // constant, and they agree with each other, the PHI becomes the identical
568 // constant. If they are constant and don't agree, the PHI is overdefined.
569 // If there are no executable operands, the PHI remains undefined.
571 Constant *OperandVal = 0;
572 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
573 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
574 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
576 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
577 if (IV.isOverdefined()) { // PHI node becomes overdefined!
578 markOverdefined(&PN);
582 if (OperandVal == 0) { // Grab the first value...
583 OperandVal = IV.getConstant();
584 } else { // Another value is being merged in!
585 // There is already a reachable operand. If we conflict with it,
586 // then the PHI node becomes overdefined. If we agree with it, we
589 // Check to see if there are two different constants merging...
590 if (IV.getConstant() != OperandVal) {
591 // Yes there is. This means the PHI node is not constant.
592 // You must be overdefined poor PHI.
594 markOverdefined(&PN); // The PHI node now becomes overdefined
595 return; // I'm done analyzing you
601 // If we exited the loop, this means that the PHI node only has constant
602 // arguments that agree with each other(and OperandVal is the constant) or
603 // OperandVal is null because there are no defined incoming arguments. If
604 // this is the case, the PHI remains undefined.
607 markConstant(&PN, OperandVal); // Acquire operand value
610 void SCCPSolver::visitReturnInst(ReturnInst &I) {
611 if (I.getNumOperands() == 0) return; // Ret void
613 Function *F = I.getParent()->getParent();
614 // If we are tracking the return value of this function, merge it in.
615 if (!F->hasLocalLinkage())
618 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
619 DenseMap<Function*, LatticeVal>::iterator TFRVI =
620 TrackedRetVals.find(F);
621 if (TFRVI != TrackedRetVals.end() &&
622 !TFRVI->second.isOverdefined()) {
623 LatticeVal &IV = getValueState(I.getOperand(0));
624 mergeInValue(TFRVI->second, F, IV);
629 // Handle functions that return multiple values.
630 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
631 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
632 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
633 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
634 if (It == TrackedMultipleRetVals.end()) break;
635 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
637 } else if (!TrackedMultipleRetVals.empty() &&
638 I.getNumOperands() == 1 &&
639 isa<StructType>(I.getOperand(0)->getType())) {
640 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
642 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
643 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
644 if (It == TrackedMultipleRetVals.end()) break;
645 if (Value *Val = FindInsertedValue(I.getOperand(0), i, Context))
646 mergeInValue(It->second, F, getValueState(Val));
651 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
652 SmallVector<bool, 16> SuccFeasible;
653 getFeasibleSuccessors(TI, SuccFeasible);
655 BasicBlock *BB = TI.getParent();
657 // Mark all feasible successors executable...
658 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
660 markEdgeExecutable(BB, TI.getSuccessor(i));
663 void SCCPSolver::visitCastInst(CastInst &I) {
664 Value *V = I.getOperand(0);
665 LatticeVal &VState = getValueState(V);
666 if (VState.isOverdefined()) // Inherit overdefinedness of operand
668 else if (VState.isConstant()) // Propagate constant value
669 markConstant(&I, Context->getConstantExprCast(I.getOpcode(),
670 VState.getConstant(), I.getType()));
673 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
674 Value *Aggr = EVI.getAggregateOperand();
676 // If the operand to the extractvalue is an undef, the result is undef.
677 if (isa<UndefValue>(Aggr))
680 // Currently only handle single-index extractvalues.
681 if (EVI.getNumIndices() != 1) {
682 markOverdefined(&EVI);
687 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
688 F = CI->getCalledFunction();
689 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
690 F = II->getCalledFunction();
692 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
694 if (F == 0 || TrackedMultipleRetVals.empty()) {
695 markOverdefined(&EVI);
699 // See if we are tracking the result of the callee. If not tracking this
700 // function (for example, it is a declaration) just move to overdefined.
701 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
702 markOverdefined(&EVI);
706 // Otherwise, the value will be merged in here as a result of CallSite
710 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
711 Value *Aggr = IVI.getAggregateOperand();
712 Value *Val = IVI.getInsertedValueOperand();
714 // If the operands to the insertvalue are undef, the result is undef.
715 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
718 // Currently only handle single-index insertvalues.
719 if (IVI.getNumIndices() != 1) {
720 markOverdefined(&IVI);
724 // Currently only handle insertvalue instructions that are in a single-use
725 // chain that builds up a return value.
726 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
727 if (!TmpIVI->hasOneUse()) {
728 markOverdefined(&IVI);
731 const Value *V = *TmpIVI->use_begin();
732 if (isa<ReturnInst>(V))
734 TmpIVI = dyn_cast<InsertValueInst>(V);
736 markOverdefined(&IVI);
741 // See if we are tracking the result of the callee.
742 Function *F = IVI.getParent()->getParent();
743 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
744 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
746 // Merge in the inserted member value.
747 if (It != TrackedMultipleRetVals.end())
748 mergeInValue(It->second, F, getValueState(Val));
750 // Mark the aggregate result of the IVI overdefined; any tracking that we do
751 // will be done on the individual member values.
752 markOverdefined(&IVI);
755 void SCCPSolver::visitSelectInst(SelectInst &I) {
756 LatticeVal &CondValue = getValueState(I.getCondition());
757 if (CondValue.isUndefined())
759 if (CondValue.isConstant()) {
760 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
761 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
762 : I.getFalseValue()));
767 // Otherwise, the condition is overdefined or a constant we can't evaluate.
768 // See if we can produce something better than overdefined based on the T/F
770 LatticeVal &TVal = getValueState(I.getTrueValue());
771 LatticeVal &FVal = getValueState(I.getFalseValue());
773 // select ?, C, C -> C.
774 if (TVal.isConstant() && FVal.isConstant() &&
775 TVal.getConstant() == FVal.getConstant()) {
776 markConstant(&I, FVal.getConstant());
780 if (TVal.isUndefined()) { // select ?, undef, X -> X.
781 mergeInValue(&I, FVal);
782 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
783 mergeInValue(&I, TVal);
789 // Handle BinaryOperators and Shift Instructions...
790 void SCCPSolver::visitBinaryOperator(Instruction &I) {
791 LatticeVal &IV = ValueState[&I];
792 if (IV.isOverdefined()) return;
794 LatticeVal &V1State = getValueState(I.getOperand(0));
795 LatticeVal &V2State = getValueState(I.getOperand(1));
797 if (V1State.isOverdefined() || V2State.isOverdefined()) {
798 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
799 // operand is overdefined.
800 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
801 LatticeVal *NonOverdefVal = 0;
802 if (!V1State.isOverdefined()) {
803 NonOverdefVal = &V1State;
804 } else if (!V2State.isOverdefined()) {
805 NonOverdefVal = &V2State;
809 if (NonOverdefVal->isUndefined()) {
810 // Could annihilate value.
811 if (I.getOpcode() == Instruction::And)
812 markConstant(IV, &I, Context->getNullValue(I.getType()));
813 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
814 markConstant(IV, &I, Context->getConstantVectorAllOnesValue(PT));
817 Context->getConstantIntAllOnesValue(I.getType()));
820 if (I.getOpcode() == Instruction::And) {
821 if (NonOverdefVal->getConstant()->isNullValue()) {
822 markConstant(IV, &I, NonOverdefVal->getConstant());
823 return; // X and 0 = 0
826 if (ConstantInt *CI =
827 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
828 if (CI->isAllOnesValue()) {
829 markConstant(IV, &I, NonOverdefVal->getConstant());
830 return; // X or -1 = -1
838 // If both operands are PHI nodes, it is possible that this instruction has
839 // a constant value, despite the fact that the PHI node doesn't. Check for
840 // this condition now.
841 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
842 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
843 if (PN1->getParent() == PN2->getParent()) {
844 // Since the two PHI nodes are in the same basic block, they must have
845 // entries for the same predecessors. Walk the predecessor list, and
846 // if all of the incoming values are constants, and the result of
847 // evaluating this expression with all incoming value pairs is the
848 // same, then this expression is a constant even though the PHI node
849 // is not a constant!
851 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
852 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
853 BasicBlock *InBlock = PN1->getIncomingBlock(i);
855 getValueState(PN2->getIncomingValueForBlock(InBlock));
857 if (In1.isOverdefined() || In2.isOverdefined()) {
858 Result.markOverdefined();
859 break; // Cannot fold this operation over the PHI nodes!
860 } else if (In1.isConstant() && In2.isConstant()) {
862 Context->getConstantExpr(I.getOpcode(), In1.getConstant(),
864 if (Result.isUndefined())
865 Result.markConstant(V);
866 else if (Result.isConstant() && Result.getConstant() != V) {
867 Result.markOverdefined();
873 // If we found a constant value here, then we know the instruction is
874 // constant despite the fact that the PHI nodes are overdefined.
875 if (Result.isConstant()) {
876 markConstant(IV, &I, Result.getConstant());
877 // Remember that this instruction is virtually using the PHI node
879 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
880 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
882 } else if (Result.isUndefined()) {
886 // Okay, this really is overdefined now. Since we might have
887 // speculatively thought that this was not overdefined before, and
888 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
889 // make sure to clean out any entries that we put there, for
891 std::multimap<PHINode*, Instruction*>::iterator It, E;
892 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
894 if (It->second == &I) {
895 UsersOfOverdefinedPHIs.erase(It++);
899 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
901 if (It->second == &I) {
902 UsersOfOverdefinedPHIs.erase(It++);
908 markOverdefined(IV, &I);
909 } else if (V1State.isConstant() && V2State.isConstant()) {
911 Context->getConstantExpr(I.getOpcode(), V1State.getConstant(),
912 V2State.getConstant()));
916 // Handle ICmpInst instruction...
917 void SCCPSolver::visitCmpInst(CmpInst &I) {
918 LatticeVal &IV = ValueState[&I];
919 if (IV.isOverdefined()) return;
921 LatticeVal &V1State = getValueState(I.getOperand(0));
922 LatticeVal &V2State = getValueState(I.getOperand(1));
924 if (V1State.isOverdefined() || V2State.isOverdefined()) {
925 // If both operands are PHI nodes, it is possible that this instruction has
926 // a constant value, despite the fact that the PHI node doesn't. Check for
927 // this condition now.
928 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
929 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
930 if (PN1->getParent() == PN2->getParent()) {
931 // Since the two PHI nodes are in the same basic block, they must have
932 // entries for the same predecessors. Walk the predecessor list, and
933 // if all of the incoming values are constants, and the result of
934 // evaluating this expression with all incoming value pairs is the
935 // same, then this expression is a constant even though the PHI node
936 // is not a constant!
938 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
939 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
940 BasicBlock *InBlock = PN1->getIncomingBlock(i);
942 getValueState(PN2->getIncomingValueForBlock(InBlock));
944 if (In1.isOverdefined() || In2.isOverdefined()) {
945 Result.markOverdefined();
946 break; // Cannot fold this operation over the PHI nodes!
947 } else if (In1.isConstant() && In2.isConstant()) {
948 Constant *V = Context->getConstantExprCompare(I.getPredicate(),
951 if (Result.isUndefined())
952 Result.markConstant(V);
953 else if (Result.isConstant() && Result.getConstant() != V) {
954 Result.markOverdefined();
960 // If we found a constant value here, then we know the instruction is
961 // constant despite the fact that the PHI nodes are overdefined.
962 if (Result.isConstant()) {
963 markConstant(IV, &I, Result.getConstant());
964 // Remember that this instruction is virtually using the PHI node
966 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
967 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
969 } else if (Result.isUndefined()) {
973 // Okay, this really is overdefined now. Since we might have
974 // speculatively thought that this was not overdefined before, and
975 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
976 // make sure to clean out any entries that we put there, for
978 std::multimap<PHINode*, Instruction*>::iterator It, E;
979 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
981 if (It->second == &I) {
982 UsersOfOverdefinedPHIs.erase(It++);
986 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
988 if (It->second == &I) {
989 UsersOfOverdefinedPHIs.erase(It++);
995 markOverdefined(IV, &I);
996 } else if (V1State.isConstant() && V2State.isConstant()) {
997 markConstant(IV, &I, Context->getConstantExprCompare(I.getPredicate(),
998 V1State.getConstant(),
999 V2State.getConstant()));
1003 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1004 // FIXME : SCCP does not handle vectors properly.
1005 markOverdefined(&I);
1009 LatticeVal &ValState = getValueState(I.getOperand(0));
1010 LatticeVal &IdxState = getValueState(I.getOperand(1));
1012 if (ValState.isOverdefined() || IdxState.isOverdefined())
1013 markOverdefined(&I);
1014 else if(ValState.isConstant() && IdxState.isConstant())
1015 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1016 IdxState.getConstant()));
1020 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1021 // FIXME : SCCP does not handle vectors properly.
1022 markOverdefined(&I);
1025 LatticeVal &ValState = getValueState(I.getOperand(0));
1026 LatticeVal &EltState = getValueState(I.getOperand(1));
1027 LatticeVal &IdxState = getValueState(I.getOperand(2));
1029 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1030 IdxState.isOverdefined())
1031 markOverdefined(&I);
1032 else if(ValState.isConstant() && EltState.isConstant() &&
1033 IdxState.isConstant())
1034 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1035 EltState.getConstant(),
1036 IdxState.getConstant()));
1037 else if (ValState.isUndefined() && EltState.isConstant() &&
1038 IdxState.isConstant())
1039 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1040 EltState.getConstant(),
1041 IdxState.getConstant()));
1045 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1046 // FIXME : SCCP does not handle vectors properly.
1047 markOverdefined(&I);
1050 LatticeVal &V1State = getValueState(I.getOperand(0));
1051 LatticeVal &V2State = getValueState(I.getOperand(1));
1052 LatticeVal &MaskState = getValueState(I.getOperand(2));
1054 if (MaskState.isUndefined() ||
1055 (V1State.isUndefined() && V2State.isUndefined()))
1056 return; // Undefined output if mask or both inputs undefined.
1058 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1059 MaskState.isOverdefined()) {
1060 markOverdefined(&I);
1062 // A mix of constant/undef inputs.
1063 Constant *V1 = V1State.isConstant() ?
1064 V1State.getConstant() : UndefValue::get(I.getType());
1065 Constant *V2 = V2State.isConstant() ?
1066 V2State.getConstant() : UndefValue::get(I.getType());
1067 Constant *Mask = MaskState.isConstant() ?
1068 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1069 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1074 // Handle getelementptr instructions... if all operands are constants then we
1075 // can turn this into a getelementptr ConstantExpr.
1077 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1078 LatticeVal &IV = ValueState[&I];
1079 if (IV.isOverdefined()) return;
1081 SmallVector<Constant*, 8> Operands;
1082 Operands.reserve(I.getNumOperands());
1084 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1085 LatticeVal &State = getValueState(I.getOperand(i));
1086 if (State.isUndefined())
1087 return; // Operands are not resolved yet...
1088 else if (State.isOverdefined()) {
1089 markOverdefined(IV, &I);
1092 assert(State.isConstant() && "Unknown state!");
1093 Operands.push_back(State.getConstant());
1096 Constant *Ptr = Operands[0];
1097 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1099 markConstant(IV, &I, Context->getConstantExprGetElementPtr(Ptr, &Operands[0],
1103 void SCCPSolver::visitStoreInst(Instruction &SI) {
1104 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1106 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1107 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1108 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1110 // Get the value we are storing into the global.
1111 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1113 mergeInValue(I->second, GV, PtrVal);
1114 if (I->second.isOverdefined())
1115 TrackedGlobals.erase(I); // No need to keep tracking this!
1119 // Handle load instructions. If the operand is a constant pointer to a constant
1120 // global, we can replace the load with the loaded constant value!
1121 void SCCPSolver::visitLoadInst(LoadInst &I) {
1122 LatticeVal &IV = ValueState[&I];
1123 if (IV.isOverdefined()) return;
1125 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1126 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1127 if (PtrVal.isConstant() && !I.isVolatile()) {
1128 Value *Ptr = PtrVal.getConstant();
1129 // TODO: Consider a target hook for valid address spaces for this xform.
1130 if (isa<ConstantPointerNull>(Ptr) &&
1131 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
1132 // load null -> null
1133 markConstant(IV, &I, Context->getNullValue(I.getType()));
1137 // Transform load (constant global) into the value loaded.
1138 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1139 if (GV->isConstant()) {
1140 if (GV->hasDefinitiveInitializer()) {
1141 markConstant(IV, &I, GV->getInitializer());
1144 } else if (!TrackedGlobals.empty()) {
1145 // If we are tracking this global, merge in the known value for it.
1146 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1147 TrackedGlobals.find(GV);
1148 if (It != TrackedGlobals.end()) {
1149 mergeInValue(IV, &I, It->second);
1155 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1156 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1157 if (CE->getOpcode() == Instruction::GetElementPtr)
1158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1159 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1161 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
1163 markConstant(IV, &I, V);
1168 // Otherwise we cannot say for certain what value this load will produce.
1170 markOverdefined(IV, &I);
1173 void SCCPSolver::visitCallSite(CallSite CS) {
1174 Function *F = CS.getCalledFunction();
1175 Instruction *I = CS.getInstruction();
1177 // The common case is that we aren't tracking the callee, either because we
1178 // are not doing interprocedural analysis or the callee is indirect, or is
1179 // external. Handle these cases first.
1180 if (F == 0 || !F->hasLocalLinkage()) {
1182 // Void return and not tracking callee, just bail.
1183 if (I->getType() == Type::VoidTy) return;
1185 // Otherwise, if we have a single return value case, and if the function is
1186 // a declaration, maybe we can constant fold it.
1187 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1188 canConstantFoldCallTo(F)) {
1190 SmallVector<Constant*, 8> Operands;
1191 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1193 LatticeVal &State = getValueState(*AI);
1194 if (State.isUndefined())
1195 return; // Operands are not resolved yet.
1196 else if (State.isOverdefined()) {
1200 assert(State.isConstant() && "Unknown state!");
1201 Operands.push_back(State.getConstant());
1204 // If we can constant fold this, mark the result of the call as a
1206 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
1212 // Otherwise, we don't know anything about this call, mark it overdefined.
1217 // If this is a single/zero retval case, see if we're tracking the function.
1218 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1219 if (TFRVI != TrackedRetVals.end()) {
1220 // If so, propagate the return value of the callee into this call result.
1221 mergeInValue(I, TFRVI->second);
1222 } else if (isa<StructType>(I->getType())) {
1223 // Check to see if we're tracking this callee, if not, handle it in the
1224 // common path above.
1225 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1226 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1227 if (TMRVI == TrackedMultipleRetVals.end())
1228 goto CallOverdefined;
1230 // If we are tracking this callee, propagate the return values of the call
1231 // into this call site. We do this by walking all the uses. Single-index
1232 // ExtractValueInst uses can be tracked; anything more complicated is
1233 // currently handled conservatively.
1234 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1236 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1237 if (EVI->getNumIndices() == 1) {
1239 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
1243 // The aggregate value is used in a way not handled here. Assume nothing.
1244 markOverdefined(*UI);
1247 // Otherwise we're not tracking this callee, so handle it in the
1248 // common path above.
1249 goto CallOverdefined;
1252 // Finally, if this is the first call to the function hit, mark its entry
1253 // block executable.
1254 if (!BBExecutable.count(F->begin()))
1255 MarkBlockExecutable(F->begin());
1257 // Propagate information from this call site into the callee.
1258 CallSite::arg_iterator CAI = CS.arg_begin();
1259 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1260 AI != E; ++AI, ++CAI) {
1261 LatticeVal &IV = ValueState[AI];
1262 if (!IV.isOverdefined())
1263 mergeInValue(IV, AI, getValueState(*CAI));
1268 void SCCPSolver::Solve() {
1269 // Process the work lists until they are empty!
1270 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1271 !OverdefinedInstWorkList.empty()) {
1272 // Process the instruction work list...
1273 while (!OverdefinedInstWorkList.empty()) {
1274 Value *I = OverdefinedInstWorkList.back();
1275 OverdefinedInstWorkList.pop_back();
1277 DOUT << "\nPopped off OI-WL: " << *I;
1279 // "I" got into the work list because it either made the transition from
1280 // bottom to constant
1282 // Anything on this worklist that is overdefined need not be visited
1283 // since all of its users will have already been marked as overdefined
1284 // Update all of the users of this instruction's value...
1286 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1288 OperandChangedState(*UI);
1290 // Process the instruction work list...
1291 while (!InstWorkList.empty()) {
1292 Value *I = InstWorkList.back();
1293 InstWorkList.pop_back();
1295 DOUT << "\nPopped off I-WL: " << *I;
1297 // "I" got into the work list because it either made the transition from
1298 // bottom to constant
1300 // Anything on this worklist that is overdefined need not be visited
1301 // since all of its users will have already been marked as overdefined.
1302 // Update all of the users of this instruction's value...
1304 if (!getValueState(I).isOverdefined())
1305 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1307 OperandChangedState(*UI);
1310 // Process the basic block work list...
1311 while (!BBWorkList.empty()) {
1312 BasicBlock *BB = BBWorkList.back();
1313 BBWorkList.pop_back();
1315 DOUT << "\nPopped off BBWL: " << *BB;
1317 // Notify all instructions in this basic block that they are newly
1324 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1325 /// that branches on undef values cannot reach any of their successors.
1326 /// However, this is not a safe assumption. After we solve dataflow, this
1327 /// method should be use to handle this. If this returns true, the solver
1328 /// should be rerun.
1330 /// This method handles this by finding an unresolved branch and marking it one
1331 /// of the edges from the block as being feasible, even though the condition
1332 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1333 /// CFG and only slightly pessimizes the analysis results (by marking one,
1334 /// potentially infeasible, edge feasible). This cannot usefully modify the
1335 /// constraints on the condition of the branch, as that would impact other users
1338 /// This scan also checks for values that use undefs, whose results are actually
1339 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1340 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1341 /// even if X isn't defined.
1342 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1343 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1344 if (!BBExecutable.count(BB))
1347 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1348 // Look for instructions which produce undef values.
1349 if (I->getType() == Type::VoidTy) continue;
1351 LatticeVal &LV = getValueState(I);
1352 if (!LV.isUndefined()) continue;
1354 // Get the lattice values of the first two operands for use below.
1355 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1357 if (I->getNumOperands() == 2) {
1358 // If this is a two-operand instruction, and if both operands are
1359 // undefs, the result stays undef.
1360 Op1LV = getValueState(I->getOperand(1));
1361 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1365 // If this is an instructions whose result is defined even if the input is
1366 // not fully defined, propagate the information.
1367 const Type *ITy = I->getType();
1368 switch (I->getOpcode()) {
1369 default: break; // Leave the instruction as an undef.
1370 case Instruction::ZExt:
1371 // After a zero extend, we know the top part is zero. SExt doesn't have
1372 // to be handled here, because we don't know whether the top part is 1's
1374 assert(Op0LV.isUndefined());
1375 markForcedConstant(LV, I, Context->getNullValue(ITy));
1377 case Instruction::Mul:
1378 case Instruction::And:
1379 // undef * X -> 0. X could be zero.
1380 // undef & X -> 0. X could be zero.
1381 markForcedConstant(LV, I, Context->getNullValue(ITy));
1384 case Instruction::Or:
1385 // undef | X -> -1. X could be -1.
1386 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1387 markForcedConstant(LV, I,
1388 Context->getConstantVectorAllOnesValue(PTy));
1390 markForcedConstant(LV, I, Context->getConstantIntAllOnesValue(ITy));
1393 case Instruction::SDiv:
1394 case Instruction::UDiv:
1395 case Instruction::SRem:
1396 case Instruction::URem:
1397 // X / undef -> undef. No change.
1398 // X % undef -> undef. No change.
1399 if (Op1LV.isUndefined()) break;
1401 // undef / X -> 0. X could be maxint.
1402 // undef % X -> 0. X could be 1.
1403 markForcedConstant(LV, I, Context->getNullValue(ITy));
1406 case Instruction::AShr:
1407 // undef >>s X -> undef. No change.
1408 if (Op0LV.isUndefined()) break;
1410 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1411 if (Op0LV.isConstant())
1412 markForcedConstant(LV, I, Op0LV.getConstant());
1414 markOverdefined(LV, I);
1416 case Instruction::LShr:
1417 case Instruction::Shl:
1418 // undef >> X -> undef. No change.
1419 // undef << X -> undef. No change.
1420 if (Op0LV.isUndefined()) break;
1422 // X >> undef -> 0. X could be 0.
1423 // X << undef -> 0. X could be 0.
1424 markForcedConstant(LV, I, Context->getNullValue(ITy));
1426 case Instruction::Select:
1427 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1428 if (Op0LV.isUndefined()) {
1429 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1430 Op1LV = getValueState(I->getOperand(2));
1431 } else if (Op1LV.isUndefined()) {
1432 // c ? undef : undef -> undef. No change.
1433 Op1LV = getValueState(I->getOperand(2));
1434 if (Op1LV.isUndefined())
1436 // Otherwise, c ? undef : x -> x.
1438 // Leave Op1LV as Operand(1)'s LatticeValue.
1441 if (Op1LV.isConstant())
1442 markForcedConstant(LV, I, Op1LV.getConstant());
1444 markOverdefined(LV, I);
1446 case Instruction::Call:
1447 // If a call has an undef result, it is because it is constant foldable
1448 // but one of the inputs was undef. Just force the result to
1450 markOverdefined(LV, I);
1455 TerminatorInst *TI = BB->getTerminator();
1456 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1457 if (!BI->isConditional()) continue;
1458 if (!getValueState(BI->getCondition()).isUndefined())
1460 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1461 if (SI->getNumSuccessors()<2) // no cases
1463 if (!getValueState(SI->getCondition()).isUndefined())
1469 // If the edge to the second successor isn't thought to be feasible yet,
1470 // mark it so now. We pick the second one so that this goes to some
1471 // enumerated value in a switch instead of going to the default destination.
1472 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
1475 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1476 // and return. This will make other blocks reachable, which will allow new
1477 // values to be discovered and existing ones to be moved in the lattice.
1478 markEdgeExecutable(BB, TI->getSuccessor(1));
1480 // This must be a conditional branch of switch on undef. At this point,
1481 // force the old terminator to branch to the first successor. This is
1482 // required because we are now influencing the dataflow of the function with
1483 // the assumption that this edge is taken. If we leave the branch condition
1484 // as undef, then further analysis could think the undef went another way
1485 // leading to an inconsistent set of conclusions.
1486 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1487 BI->setCondition(Context->getConstantIntFalse());
1489 SwitchInst *SI = cast<SwitchInst>(TI);
1490 SI->setCondition(SI->getCaseValue(1));
1501 //===--------------------------------------------------------------------===//
1503 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1504 /// Sparse Conditional Constant Propagator.
1506 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1507 static char ID; // Pass identification, replacement for typeid
1508 SCCP() : FunctionPass(&ID) {}
1510 // runOnFunction - Run the Sparse Conditional Constant Propagation
1511 // algorithm, and return true if the function was modified.
1513 bool runOnFunction(Function &F);
1515 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1516 AU.setPreservesCFG();
1519 } // end anonymous namespace
1522 static RegisterPass<SCCP>
1523 X("sccp", "Sparse Conditional Constant Propagation");
1525 // createSCCPPass - This is the public interface to this file...
1526 FunctionPass *llvm::createSCCPPass() {
1531 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1532 // and return true if the function was modified.
1534 bool SCCP::runOnFunction(Function &F) {
1535 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
1537 Solver.setContext(Context);
1539 // Mark the first block of the function as being executable.
1540 Solver.MarkBlockExecutable(F.begin());
1542 // Mark all arguments to the function as being overdefined.
1543 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1544 Solver.markOverdefined(AI);
1546 // Solve for constants.
1547 bool ResolvedUndefs = true;
1548 while (ResolvedUndefs) {
1550 DOUT << "RESOLVING UNDEFs\n";
1551 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1554 bool MadeChanges = false;
1556 // If we decided that there are basic blocks that are dead in this function,
1557 // delete their contents now. Note that we cannot actually delete the blocks,
1558 // as we cannot modify the CFG of the function.
1560 SmallVector<Instruction*, 512> Insts;
1561 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1563 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1564 if (!Solver.isBlockExecutable(BB)) {
1565 DOUT << " BasicBlock Dead:" << *BB;
1568 // Delete the instructions backwards, as it has a reduced likelihood of
1569 // having to update as many def-use and use-def chains.
1570 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1573 while (!Insts.empty()) {
1574 Instruction *I = Insts.back();
1576 if (!I->use_empty())
1577 I->replaceAllUsesWith(Context->getUndef(I->getType()));
1578 BB->getInstList().erase(I);
1583 // Iterate over all of the instructions in a function, replacing them with
1584 // constants if we have found them to be of constant values.
1586 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1587 Instruction *Inst = BI++;
1588 if (Inst->getType() == Type::VoidTy ||
1589 isa<TerminatorInst>(Inst))
1592 LatticeVal &IV = Values[Inst];
1593 if (!IV.isConstant() && !IV.isUndefined())
1596 Constant *Const = IV.isConstant()
1597 ? IV.getConstant() : Context->getUndef(Inst->getType());
1598 DOUT << " Constant: " << *Const << " = " << *Inst;
1600 // Replaces all of the uses of a variable with uses of the constant.
1601 Inst->replaceAllUsesWith(Const);
1603 // Delete the instruction.
1604 Inst->eraseFromParent();
1606 // Hey, we just changed something!
1616 //===--------------------------------------------------------------------===//
1618 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1619 /// Constant Propagation.
1621 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1623 IPSCCP() : ModulePass(&ID) {}
1624 bool runOnModule(Module &M);
1626 } // end anonymous namespace
1628 char IPSCCP::ID = 0;
1629 static RegisterPass<IPSCCP>
1630 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1632 // createIPSCCPPass - This is the public interface to this file...
1633 ModulePass *llvm::createIPSCCPPass() {
1634 return new IPSCCP();
1638 static bool AddressIsTaken(GlobalValue *GV) {
1639 // Delete any dead constantexpr klingons.
1640 GV->removeDeadConstantUsers();
1642 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1644 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1645 if (SI->getOperand(0) == GV || SI->isVolatile())
1646 return true; // Storing addr of GV.
1647 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1648 // Make sure we are calling the function, not passing the address.
1649 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1650 if (CS.hasArgument(GV))
1652 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1653 if (LI->isVolatile())
1661 bool IPSCCP::runOnModule(Module &M) {
1664 // Loop over all functions, marking arguments to those with their addresses
1665 // taken or that are external as overdefined.
1667 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1668 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
1669 if (!F->isDeclaration())
1670 Solver.MarkBlockExecutable(F->begin());
1671 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1673 Solver.markOverdefined(AI);
1675 Solver.AddTrackedFunction(F);
1678 // Loop over global variables. We inform the solver about any internal global
1679 // variables that do not have their 'addresses taken'. If they don't have
1680 // their addresses taken, we can propagate constants through them.
1681 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1683 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1684 Solver.TrackValueOfGlobalVariable(G);
1686 // Solve for constants.
1687 bool ResolvedUndefs = true;
1688 while (ResolvedUndefs) {
1691 DOUT << "RESOLVING UNDEFS\n";
1692 ResolvedUndefs = false;
1693 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1694 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1697 bool MadeChanges = false;
1699 // Iterate over all of the instructions in the module, replacing them with
1700 // constants if we have found them to be of constant values.
1702 SmallVector<Instruction*, 512> Insts;
1703 SmallVector<BasicBlock*, 512> BlocksToErase;
1704 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1706 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1707 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1709 if (!AI->use_empty()) {
1710 LatticeVal &IV = Values[AI];
1711 if (IV.isConstant() || IV.isUndefined()) {
1712 Constant *CST = IV.isConstant() ?
1713 IV.getConstant() : Context->getUndef(AI->getType());
1714 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1716 // Replaces all of the uses of a variable with uses of the
1718 AI->replaceAllUsesWith(CST);
1723 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1724 if (!Solver.isBlockExecutable(BB)) {
1725 DOUT << " BasicBlock Dead:" << *BB;
1728 // Delete the instructions backwards, as it has a reduced likelihood of
1729 // having to update as many def-use and use-def chains.
1730 TerminatorInst *TI = BB->getTerminator();
1731 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1734 while (!Insts.empty()) {
1735 Instruction *I = Insts.back();
1737 if (!I->use_empty())
1738 I->replaceAllUsesWith(Context->getUndef(I->getType()));
1739 BB->getInstList().erase(I);
1744 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1745 BasicBlock *Succ = TI->getSuccessor(i);
1746 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1747 TI->getSuccessor(i)->removePredecessor(BB);
1749 if (!TI->use_empty())
1750 TI->replaceAllUsesWith(Context->getUndef(TI->getType()));
1751 BB->getInstList().erase(TI);
1753 if (&*BB != &F->front())
1754 BlocksToErase.push_back(BB);
1756 new UnreachableInst(BB);
1759 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1760 Instruction *Inst = BI++;
1761 if (Inst->getType() == Type::VoidTy)
1764 LatticeVal &IV = Values[Inst];
1765 if (!IV.isConstant() && !IV.isUndefined())
1768 Constant *Const = IV.isConstant()
1769 ? IV.getConstant() : Context->getUndef(Inst->getType());
1770 DOUT << " Constant: " << *Const << " = " << *Inst;
1772 // Replaces all of the uses of a variable with uses of the
1774 Inst->replaceAllUsesWith(Const);
1776 // Delete the instruction.
1777 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1778 Inst->eraseFromParent();
1780 // Hey, we just changed something!
1786 // Now that all instructions in the function are constant folded, erase dead
1787 // blocks, because we can now use ConstantFoldTerminator to get rid of
1789 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1790 // If there are any PHI nodes in this successor, drop entries for BB now.
1791 BasicBlock *DeadBB = BlocksToErase[i];
1792 while (!DeadBB->use_empty()) {
1793 Instruction *I = cast<Instruction>(DeadBB->use_back());
1794 bool Folded = ConstantFoldTerminator(I->getParent());
1796 // The constant folder may not have been able to fold the terminator
1797 // if this is a branch or switch on undef. Fold it manually as a
1798 // branch to the first successor.
1800 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1801 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1802 "Branch should be foldable!");
1803 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1804 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1806 assert(0 && "Didn't fold away reference to block!");
1810 // Make this an uncond branch to the first successor.
1811 TerminatorInst *TI = I->getParent()->getTerminator();
1812 BranchInst::Create(TI->getSuccessor(0), TI);
1814 // Remove entries in successor phi nodes to remove edges.
1815 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1816 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1818 // Remove the old terminator.
1819 TI->eraseFromParent();
1823 // Finally, delete the basic block.
1824 F->getBasicBlockList().erase(DeadBB);
1826 BlocksToErase.clear();
1829 // If we inferred constant or undef return values for a function, we replaced
1830 // all call uses with the inferred value. This means we don't need to bother
1831 // actually returning anything from the function. Replace all return
1832 // instructions with return undef.
1833 // TODO: Process multiple value ret instructions also.
1834 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1835 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1836 E = RV.end(); I != E; ++I)
1837 if (!I->second.isOverdefined() &&
1838 I->first->getReturnType() != Type::VoidTy) {
1839 Function *F = I->first;
1840 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1841 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1842 if (!isa<UndefValue>(RI->getOperand(0)))
1843 RI->setOperand(0, Context->getUndef(F->getReturnType()));
1846 // If we infered constant or undef values for globals variables, we can delete
1847 // the global and any stores that remain to it.
1848 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1849 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1850 E = TG.end(); I != E; ++I) {
1851 GlobalVariable *GV = I->first;
1852 assert(!I->second.isOverdefined() &&
1853 "Overdefined values should have been taken out of the map!");
1854 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
1855 while (!GV->use_empty()) {
1856 StoreInst *SI = cast<StoreInst>(GV->use_back());
1857 SI->eraseFromParent();
1859 M.getGlobalList().erase(GV);