1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Pass.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/InstVisitor.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/STLExtras.h"
44 STATISTIC(NumInstRemoved, "Number of instructions removed");
45 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
47 STATISTIC(IPNumInstRemoved, "Number ofinstructions removed by IPSCCP");
48 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
49 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
50 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53 /// LatticeVal class - This class represents the different lattice values that
54 /// an LLVM value may occupy. It is a simple class with value semantics.
58 /// undefined - This LLVM Value has no known value yet.
61 /// constant - This LLVM Value has a specific constant value.
64 /// forcedconstant - This LLVM Value was thought to be undef until
65 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
66 /// with another (different) constant, it goes to overdefined, instead of
70 /// overdefined - This instruction is not known to be constant, and we know
73 } LatticeValue; // The current lattice position
75 Constant *ConstantVal; // If Constant value, the current value
77 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
79 // markOverdefined - Return true if this is a new status to be in...
80 inline bool markOverdefined() {
81 if (LatticeValue != overdefined) {
82 LatticeValue = overdefined;
88 // markConstant - Return true if this is a new status for us.
89 inline bool markConstant(Constant *V) {
90 if (LatticeValue != constant) {
91 if (LatticeValue == undefined) {
92 LatticeValue = constant;
93 assert(V && "Marking constant with NULL");
96 assert(LatticeValue == forcedconstant &&
97 "Cannot move from overdefined to constant!");
98 // Stay at forcedconstant if the constant is the same.
99 if (V == ConstantVal) return false;
101 // Otherwise, we go to overdefined. Assumptions made based on the
102 // forced value are possibly wrong. Assuming this is another constant
103 // could expose a contradiction.
104 LatticeValue = overdefined;
108 assert(ConstantVal == V && "Marking constant with different value");
113 inline void markForcedConstant(Constant *V) {
114 assert(LatticeValue == undefined && "Can't force a defined value!");
115 LatticeValue = forcedconstant;
119 inline bool isUndefined() const { return LatticeValue == undefined; }
120 inline bool isConstant() const {
121 return LatticeValue == constant || LatticeValue == forcedconstant;
123 inline bool isOverdefined() const { return LatticeValue == overdefined; }
125 inline Constant *getConstant() const {
126 assert(isConstant() && "Cannot get the constant of a non-constant!");
131 } // end anonymous namespace
134 //===----------------------------------------------------------------------===//
136 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
137 /// Constant Propagation.
139 class SCCPSolver : public InstVisitor<SCCPSolver> {
140 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
141 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
143 /// GlobalValue - If we are tracking any values for the contents of a global
144 /// variable, we keep a mapping from the constant accessor to the element of
145 /// the global, to the currently known value. If the value becomes
146 /// overdefined, it's entry is simply removed from this map.
147 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
149 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
150 /// value out of a function, it will have an entry in this map, indicating
151 /// what the known return value for the function is.
152 DenseMap<Function*, LatticeVal> TrackedFunctionRetVals;
154 // The reason for two worklists is that overdefined is the lowest state
155 // on the lattice, and moving things to overdefined as fast as possible
156 // makes SCCP converge much faster.
157 // By having a separate worklist, we accomplish this because everything
158 // possibly overdefined will become overdefined at the soonest possible
160 std::vector<Value*> OverdefinedInstWorkList;
161 std::vector<Value*> InstWorkList;
164 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
166 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
167 /// overdefined, despite the fact that the PHI node is overdefined.
168 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
170 /// KnownFeasibleEdges - Entries in this set are edges which have already had
171 /// PHI nodes retriggered.
172 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
173 std::set<Edge> KnownFeasibleEdges;
176 /// MarkBlockExecutable - This method can be used by clients to mark all of
177 /// the blocks that are known to be intrinsically live in the processed unit.
178 void MarkBlockExecutable(BasicBlock *BB) {
179 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
180 BBExecutable.insert(BB); // Basic block is executable!
181 BBWorkList.push_back(BB); // Add the block to the work list!
184 /// TrackValueOfGlobalVariable - Clients can use this method to
185 /// inform the SCCPSolver that it should track loads and stores to the
186 /// specified global variable if it can. This is only legal to call if
187 /// performing Interprocedural SCCP.
188 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
189 const Type *ElTy = GV->getType()->getElementType();
190 if (ElTy->isFirstClassType()) {
191 LatticeVal &IV = TrackedGlobals[GV];
192 if (!isa<UndefValue>(GV->getInitializer()))
193 IV.markConstant(GV->getInitializer());
197 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
198 /// and out of the specified function (which cannot have its address taken),
199 /// this method must be called.
200 void AddTrackedFunction(Function *F) {
201 assert(F->hasInternalLinkage() && "Can only track internal functions!");
202 // Add an entry, F -> undef.
203 TrackedFunctionRetVals[F];
206 /// Solve - Solve for constants and executable blocks.
210 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
211 /// that branches on undef values cannot reach any of their successors.
212 /// However, this is not a safe assumption. After we solve dataflow, this
213 /// method should be use to handle this. If this returns true, the solver
215 bool ResolvedUndefsIn(Function &F);
217 /// getExecutableBlocks - Once we have solved for constants, return the set of
218 /// blocks that is known to be executable.
219 std::set<BasicBlock*> &getExecutableBlocks() {
223 /// getValueMapping - Once we have solved for constants, return the mapping of
224 /// LLVM values to LatticeVals.
225 DenseMap<Value*, LatticeVal> &getValueMapping() {
229 /// getTrackedFunctionRetVals - Get the inferred return value map.
231 const DenseMap<Function*, LatticeVal> &getTrackedFunctionRetVals() {
232 return TrackedFunctionRetVals;
235 /// getTrackedGlobals - Get and return the set of inferred initializers for
236 /// global variables.
237 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
238 return TrackedGlobals;
243 // markConstant - Make a value be marked as "constant". If the value
244 // is not already a constant, add it to the instruction work list so that
245 // the users of the instruction are updated later.
247 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
248 if (IV.markConstant(C)) {
249 DOUT << "markConstant: " << *C << ": " << *V;
250 InstWorkList.push_back(V);
254 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
255 IV.markForcedConstant(C);
256 DOUT << "markForcedConstant: " << *C << ": " << *V;
257 InstWorkList.push_back(V);
260 inline void markConstant(Value *V, Constant *C) {
261 markConstant(ValueState[V], V, C);
264 // markOverdefined - Make a value be marked as "overdefined". If the
265 // value is not already overdefined, add it to the overdefined instruction
266 // work list so that the users of the instruction are updated later.
268 inline void markOverdefined(LatticeVal &IV, Value *V) {
269 if (IV.markOverdefined()) {
270 DEBUG(DOUT << "markOverdefined: ";
271 if (Function *F = dyn_cast<Function>(V))
272 DOUT << "Function '" << F->getName() << "'\n";
275 // Only instructions go on the work list
276 OverdefinedInstWorkList.push_back(V);
279 inline void markOverdefined(Value *V) {
280 markOverdefined(ValueState[V], V);
283 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
284 if (IV.isOverdefined() || MergeWithV.isUndefined())
286 if (MergeWithV.isOverdefined())
287 markOverdefined(IV, V);
288 else if (IV.isUndefined())
289 markConstant(IV, V, MergeWithV.getConstant());
290 else if (IV.getConstant() != MergeWithV.getConstant())
291 markOverdefined(IV, V);
294 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
295 return mergeInValue(ValueState[V], V, MergeWithV);
299 // getValueState - Return the LatticeVal object that corresponds to the value.
300 // This function is necessary because not all values should start out in the
301 // underdefined state... Argument's should be overdefined, and
302 // constants should be marked as constants. If a value is not known to be an
303 // Instruction object, then use this accessor to get its value from the map.
305 inline LatticeVal &getValueState(Value *V) {
306 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
307 if (I != ValueState.end()) return I->second; // Common case, in the map
309 if (Constant *C = dyn_cast<Constant>(V)) {
310 if (isa<UndefValue>(V)) {
311 // Nothing to do, remain undefined.
313 LatticeVal &LV = ValueState[C];
314 LV.markConstant(C); // Constants are constant
318 // All others are underdefined by default...
319 return ValueState[V];
322 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
323 // work list if it is not already executable...
325 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
326 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
327 return; // This edge is already known to be executable!
329 if (BBExecutable.count(Dest)) {
330 DOUT << "Marking Edge Executable: " << Source->getName()
331 << " -> " << Dest->getName() << "\n";
333 // The destination is already executable, but we just made an edge
334 // feasible that wasn't before. Revisit the PHI nodes in the block
335 // because they have potentially new operands.
336 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
337 visitPHINode(*cast<PHINode>(I));
340 MarkBlockExecutable(Dest);
344 // getFeasibleSuccessors - Return a vector of booleans to indicate which
345 // successors are reachable from a given terminator instruction.
347 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
349 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
350 // block to the 'To' basic block is currently feasible...
352 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
354 // OperandChangedState - This method is invoked on all of the users of an
355 // instruction that was just changed state somehow.... Based on this
356 // information, we need to update the specified user of this instruction.
358 void OperandChangedState(User *U) {
359 // Only instructions use other variable values!
360 Instruction &I = cast<Instruction>(*U);
361 if (BBExecutable.count(I.getParent())) // Inst is executable?
366 friend class InstVisitor<SCCPSolver>;
368 // visit implementations - Something changed in this instruction... Either an
369 // operand made a transition, or the instruction is newly executable. Change
370 // the value type of I to reflect these changes if appropriate.
372 void visitPHINode(PHINode &I);
375 void visitReturnInst(ReturnInst &I);
376 void visitTerminatorInst(TerminatorInst &TI);
378 void visitCastInst(CastInst &I);
379 void visitSelectInst(SelectInst &I);
380 void visitBinaryOperator(Instruction &I);
381 void visitCmpInst(CmpInst &I);
382 void visitExtractElementInst(ExtractElementInst &I);
383 void visitInsertElementInst(InsertElementInst &I);
384 void visitShuffleVectorInst(ShuffleVectorInst &I);
386 // Instructions that cannot be folded away...
387 void visitStoreInst (Instruction &I);
388 void visitLoadInst (LoadInst &I);
389 void visitGetElementPtrInst(GetElementPtrInst &I);
390 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
391 void visitInvokeInst (InvokeInst &II) {
392 visitCallSite(CallSite::get(&II));
393 visitTerminatorInst(II);
395 void visitCallSite (CallSite CS);
396 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
397 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
398 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
399 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
400 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
401 void visitFreeInst (Instruction &I) { /*returns void*/ }
403 void visitInstruction(Instruction &I) {
404 // If a new instruction is added to LLVM that we don't handle...
405 cerr << "SCCP: Don't know how to handle: " << I;
406 markOverdefined(&I); // Just in case
410 // getFeasibleSuccessors - Return a vector of booleans to indicate which
411 // successors are reachable from a given terminator instruction.
413 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
414 std::vector<bool> &Succs) {
415 Succs.resize(TI.getNumSuccessors());
416 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
417 if (BI->isUnconditional()) {
420 LatticeVal &BCValue = getValueState(BI->getCondition());
421 if (BCValue.isOverdefined() ||
422 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
423 // Overdefined condition variables, and branches on unfoldable constant
424 // conditions, mean the branch could go either way.
425 Succs[0] = Succs[1] = true;
426 } else if (BCValue.isConstant()) {
427 // Constant condition variables mean the branch can only go a single way
428 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
431 } else if (isa<InvokeInst>(&TI)) {
432 // Invoke instructions successors are always executable.
433 Succs[0] = Succs[1] = true;
434 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
435 LatticeVal &SCValue = getValueState(SI->getCondition());
436 if (SCValue.isOverdefined() || // Overdefined condition?
437 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
438 // All destinations are executable!
439 Succs.assign(TI.getNumSuccessors(), true);
440 } else if (SCValue.isConstant()) {
441 Constant *CPV = SCValue.getConstant();
442 // Make sure to skip the "default value" which isn't a value
443 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
444 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
450 // Constant value not equal to any of the branches... must execute
451 // default branch then...
455 cerr << "SCCP: Don't know how to handle: " << TI;
456 Succs.assign(TI.getNumSuccessors(), true);
461 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
462 // block to the 'To' basic block is currently feasible...
464 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
465 assert(BBExecutable.count(To) && "Dest should always be alive!");
467 // Make sure the source basic block is executable!!
468 if (!BBExecutable.count(From)) return false;
470 // Check to make sure this edge itself is actually feasible now...
471 TerminatorInst *TI = From->getTerminator();
472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
473 if (BI->isUnconditional())
476 LatticeVal &BCValue = getValueState(BI->getCondition());
477 if (BCValue.isOverdefined()) {
478 // Overdefined condition variables mean the branch could go either way.
480 } else if (BCValue.isConstant()) {
481 // Not branching on an evaluatable constant?
482 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
484 // Constant condition variables mean the branch can only go a single way
485 return BI->getSuccessor(BCValue.getConstant() ==
486 ConstantInt::getFalse()) == To;
490 } else if (isa<InvokeInst>(TI)) {
491 // Invoke instructions successors are always executable.
493 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
494 LatticeVal &SCValue = getValueState(SI->getCondition());
495 if (SCValue.isOverdefined()) { // Overdefined condition?
496 // All destinations are executable!
498 } else if (SCValue.isConstant()) {
499 Constant *CPV = SCValue.getConstant();
500 if (!isa<ConstantInt>(CPV))
501 return true; // not a foldable constant?
503 // Make sure to skip the "default value" which isn't a value
504 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
505 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
506 return SI->getSuccessor(i) == To;
508 // Constant value not equal to any of the branches... must execute
509 // default branch then...
510 return SI->getDefaultDest() == To;
514 cerr << "Unknown terminator instruction: " << *TI;
519 // visit Implementations - Something changed in this instruction... Either an
520 // operand made a transition, or the instruction is newly executable. Change
521 // the value type of I to reflect these changes if appropriate. This method
522 // makes sure to do the following actions:
524 // 1. If a phi node merges two constants in, and has conflicting value coming
525 // from different branches, or if the PHI node merges in an overdefined
526 // value, then the PHI node becomes overdefined.
527 // 2. If a phi node merges only constants in, and they all agree on value, the
528 // PHI node becomes a constant value equal to that.
529 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
530 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
531 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
532 // 6. If a conditional branch has a value that is constant, make the selected
533 // destination executable
534 // 7. If a conditional branch has a value that is overdefined, make all
535 // successors executable.
537 void SCCPSolver::visitPHINode(PHINode &PN) {
538 LatticeVal &PNIV = getValueState(&PN);
539 if (PNIV.isOverdefined()) {
540 // There may be instructions using this PHI node that are not overdefined
541 // themselves. If so, make sure that they know that the PHI node operand
543 std::multimap<PHINode*, Instruction*>::iterator I, E;
544 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
546 std::vector<Instruction*> Users;
547 Users.reserve(std::distance(I, E));
548 for (; I != E; ++I) Users.push_back(I->second);
549 while (!Users.empty()) {
554 return; // Quick exit
557 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
558 // and slow us down a lot. Just mark them overdefined.
559 if (PN.getNumIncomingValues() > 64) {
560 markOverdefined(PNIV, &PN);
564 // Look at all of the executable operands of the PHI node. If any of them
565 // are overdefined, the PHI becomes overdefined as well. If they are all
566 // constant, and they agree with each other, the PHI becomes the identical
567 // constant. If they are constant and don't agree, the PHI is overdefined.
568 // If there are no executable operands, the PHI remains undefined.
570 Constant *OperandVal = 0;
571 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
572 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
573 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
575 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
576 if (IV.isOverdefined()) { // PHI node becomes overdefined!
577 markOverdefined(PNIV, &PN);
581 if (OperandVal == 0) { // Grab the first value...
582 OperandVal = IV.getConstant();
583 } else { // Another value is being merged in!
584 // There is already a reachable operand. If we conflict with it,
585 // then the PHI node becomes overdefined. If we agree with it, we
588 // Check to see if there are two different constants merging...
589 if (IV.getConstant() != OperandVal) {
590 // Yes there is. This means the PHI node is not constant.
591 // You must be overdefined poor PHI.
593 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
594 return; // I'm done analyzing you
600 // If we exited the loop, this means that the PHI node only has constant
601 // arguments that agree with each other(and OperandVal is the constant) or
602 // OperandVal is null because there are no defined incoming arguments. If
603 // this is the case, the PHI remains undefined.
606 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
609 void SCCPSolver::visitReturnInst(ReturnInst &I) {
610 if (I.getNumOperands() == 0) return; // Ret void
612 // If we are tracking the return value of this function, merge it in.
613 Function *F = I.getParent()->getParent();
614 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
615 DenseMap<Function*, LatticeVal>::iterator TFRVI =
616 TrackedFunctionRetVals.find(F);
617 if (TFRVI != TrackedFunctionRetVals.end() &&
618 !TFRVI->second.isOverdefined()) {
619 LatticeVal &IV = getValueState(I.getOperand(0));
620 mergeInValue(TFRVI->second, F, IV);
626 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
627 std::vector<bool> SuccFeasible;
628 getFeasibleSuccessors(TI, SuccFeasible);
630 BasicBlock *BB = TI.getParent();
632 // Mark all feasible successors executable...
633 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
635 markEdgeExecutable(BB, TI.getSuccessor(i));
638 void SCCPSolver::visitCastInst(CastInst &I) {
639 Value *V = I.getOperand(0);
640 LatticeVal &VState = getValueState(V);
641 if (VState.isOverdefined()) // Inherit overdefinedness of operand
643 else if (VState.isConstant()) // Propagate constant value
644 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
645 VState.getConstant(), I.getType()));
648 void SCCPSolver::visitSelectInst(SelectInst &I) {
649 LatticeVal &CondValue = getValueState(I.getCondition());
650 if (CondValue.isUndefined())
652 if (CondValue.isConstant()) {
653 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
654 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
655 : I.getFalseValue()));
660 // Otherwise, the condition is overdefined or a constant we can't evaluate.
661 // See if we can produce something better than overdefined based on the T/F
663 LatticeVal &TVal = getValueState(I.getTrueValue());
664 LatticeVal &FVal = getValueState(I.getFalseValue());
666 // select ?, C, C -> C.
667 if (TVal.isConstant() && FVal.isConstant() &&
668 TVal.getConstant() == FVal.getConstant()) {
669 markConstant(&I, FVal.getConstant());
673 if (TVal.isUndefined()) { // select ?, undef, X -> X.
674 mergeInValue(&I, FVal);
675 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
676 mergeInValue(&I, TVal);
682 // Handle BinaryOperators and Shift Instructions...
683 void SCCPSolver::visitBinaryOperator(Instruction &I) {
684 LatticeVal &IV = ValueState[&I];
685 if (IV.isOverdefined()) return;
687 LatticeVal &V1State = getValueState(I.getOperand(0));
688 LatticeVal &V2State = getValueState(I.getOperand(1));
690 if (V1State.isOverdefined() || V2State.isOverdefined()) {
691 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
692 // operand is overdefined.
693 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
694 LatticeVal *NonOverdefVal = 0;
695 if (!V1State.isOverdefined()) {
696 NonOverdefVal = &V1State;
697 } else if (!V2State.isOverdefined()) {
698 NonOverdefVal = &V2State;
702 if (NonOverdefVal->isUndefined()) {
703 // Could annihilate value.
704 if (I.getOpcode() == Instruction::And)
705 markConstant(IV, &I, Constant::getNullValue(I.getType()));
706 else if (const PackedType *PT = dyn_cast<PackedType>(I.getType()))
707 markConstant(IV, &I, ConstantPacked::getAllOnesValue(PT));
709 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
712 if (I.getOpcode() == Instruction::And) {
713 if (NonOverdefVal->getConstant()->isNullValue()) {
714 markConstant(IV, &I, NonOverdefVal->getConstant());
715 return; // X and 0 = 0
718 if (ConstantInt *CI =
719 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
720 if (CI->isAllOnesValue()) {
721 markConstant(IV, &I, NonOverdefVal->getConstant());
722 return; // X or -1 = -1
730 // If both operands are PHI nodes, it is possible that this instruction has
731 // a constant value, despite the fact that the PHI node doesn't. Check for
732 // this condition now.
733 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
734 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
735 if (PN1->getParent() == PN2->getParent()) {
736 // Since the two PHI nodes are in the same basic block, they must have
737 // entries for the same predecessors. Walk the predecessor list, and
738 // if all of the incoming values are constants, and the result of
739 // evaluating this expression with all incoming value pairs is the
740 // same, then this expression is a constant even though the PHI node
741 // is not a constant!
743 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
744 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
745 BasicBlock *InBlock = PN1->getIncomingBlock(i);
747 getValueState(PN2->getIncomingValueForBlock(InBlock));
749 if (In1.isOverdefined() || In2.isOverdefined()) {
750 Result.markOverdefined();
751 break; // Cannot fold this operation over the PHI nodes!
752 } else if (In1.isConstant() && In2.isConstant()) {
753 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
755 if (Result.isUndefined())
756 Result.markConstant(V);
757 else if (Result.isConstant() && Result.getConstant() != V) {
758 Result.markOverdefined();
764 // If we found a constant value here, then we know the instruction is
765 // constant despite the fact that the PHI nodes are overdefined.
766 if (Result.isConstant()) {
767 markConstant(IV, &I, Result.getConstant());
768 // Remember that this instruction is virtually using the PHI node
770 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
771 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
773 } else if (Result.isUndefined()) {
777 // Okay, this really is overdefined now. Since we might have
778 // speculatively thought that this was not overdefined before, and
779 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
780 // make sure to clean out any entries that we put there, for
782 std::multimap<PHINode*, Instruction*>::iterator It, E;
783 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
785 if (It->second == &I) {
786 UsersOfOverdefinedPHIs.erase(It++);
790 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
792 if (It->second == &I) {
793 UsersOfOverdefinedPHIs.erase(It++);
799 markOverdefined(IV, &I);
800 } else if (V1State.isConstant() && V2State.isConstant()) {
801 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
802 V2State.getConstant()));
806 // Handle ICmpInst instruction...
807 void SCCPSolver::visitCmpInst(CmpInst &I) {
808 LatticeVal &IV = ValueState[&I];
809 if (IV.isOverdefined()) return;
811 LatticeVal &V1State = getValueState(I.getOperand(0));
812 LatticeVal &V2State = getValueState(I.getOperand(1));
814 if (V1State.isOverdefined() || V2State.isOverdefined()) {
815 // If both operands are PHI nodes, it is possible that this instruction has
816 // a constant value, despite the fact that the PHI node doesn't. Check for
817 // this condition now.
818 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
819 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
820 if (PN1->getParent() == PN2->getParent()) {
821 // Since the two PHI nodes are in the same basic block, they must have
822 // entries for the same predecessors. Walk the predecessor list, and
823 // if all of the incoming values are constants, and the result of
824 // evaluating this expression with all incoming value pairs is the
825 // same, then this expression is a constant even though the PHI node
826 // is not a constant!
828 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
829 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
830 BasicBlock *InBlock = PN1->getIncomingBlock(i);
832 getValueState(PN2->getIncomingValueForBlock(InBlock));
834 if (In1.isOverdefined() || In2.isOverdefined()) {
835 Result.markOverdefined();
836 break; // Cannot fold this operation over the PHI nodes!
837 } else if (In1.isConstant() && In2.isConstant()) {
838 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
841 if (Result.isUndefined())
842 Result.markConstant(V);
843 else if (Result.isConstant() && Result.getConstant() != V) {
844 Result.markOverdefined();
850 // If we found a constant value here, then we know the instruction is
851 // constant despite the fact that the PHI nodes are overdefined.
852 if (Result.isConstant()) {
853 markConstant(IV, &I, Result.getConstant());
854 // Remember that this instruction is virtually using the PHI node
856 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
857 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
859 } else if (Result.isUndefined()) {
863 // Okay, this really is overdefined now. Since we might have
864 // speculatively thought that this was not overdefined before, and
865 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
866 // make sure to clean out any entries that we put there, for
868 std::multimap<PHINode*, Instruction*>::iterator It, E;
869 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
871 if (It->second == &I) {
872 UsersOfOverdefinedPHIs.erase(It++);
876 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
878 if (It->second == &I) {
879 UsersOfOverdefinedPHIs.erase(It++);
885 markOverdefined(IV, &I);
886 } else if (V1State.isConstant() && V2State.isConstant()) {
887 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
888 V1State.getConstant(),
889 V2State.getConstant()));
893 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
894 // FIXME : SCCP does not handle vectors properly.
899 LatticeVal &ValState = getValueState(I.getOperand(0));
900 LatticeVal &IdxState = getValueState(I.getOperand(1));
902 if (ValState.isOverdefined() || IdxState.isOverdefined())
904 else if(ValState.isConstant() && IdxState.isConstant())
905 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
906 IdxState.getConstant()));
910 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
911 // FIXME : SCCP does not handle vectors properly.
915 LatticeVal &ValState = getValueState(I.getOperand(0));
916 LatticeVal &EltState = getValueState(I.getOperand(1));
917 LatticeVal &IdxState = getValueState(I.getOperand(2));
919 if (ValState.isOverdefined() || EltState.isOverdefined() ||
920 IdxState.isOverdefined())
922 else if(ValState.isConstant() && EltState.isConstant() &&
923 IdxState.isConstant())
924 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
925 EltState.getConstant(),
926 IdxState.getConstant()));
927 else if (ValState.isUndefined() && EltState.isConstant() &&
928 IdxState.isConstant())
929 markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
930 EltState.getConstant(),
931 IdxState.getConstant()));
935 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
936 // FIXME : SCCP does not handle vectors properly.
940 LatticeVal &V1State = getValueState(I.getOperand(0));
941 LatticeVal &V2State = getValueState(I.getOperand(1));
942 LatticeVal &MaskState = getValueState(I.getOperand(2));
944 if (MaskState.isUndefined() ||
945 (V1State.isUndefined() && V2State.isUndefined()))
946 return; // Undefined output if mask or both inputs undefined.
948 if (V1State.isOverdefined() || V2State.isOverdefined() ||
949 MaskState.isOverdefined()) {
952 // A mix of constant/undef inputs.
953 Constant *V1 = V1State.isConstant() ?
954 V1State.getConstant() : UndefValue::get(I.getType());
955 Constant *V2 = V2State.isConstant() ?
956 V2State.getConstant() : UndefValue::get(I.getType());
957 Constant *Mask = MaskState.isConstant() ?
958 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
959 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
964 // Handle getelementptr instructions... if all operands are constants then we
965 // can turn this into a getelementptr ConstantExpr.
967 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
968 LatticeVal &IV = ValueState[&I];
969 if (IV.isOverdefined()) return;
971 SmallVector<Constant*, 8> Operands;
972 Operands.reserve(I.getNumOperands());
974 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
975 LatticeVal &State = getValueState(I.getOperand(i));
976 if (State.isUndefined())
977 return; // Operands are not resolved yet...
978 else if (State.isOverdefined()) {
979 markOverdefined(IV, &I);
982 assert(State.isConstant() && "Unknown state!");
983 Operands.push_back(State.getConstant());
986 Constant *Ptr = Operands[0];
987 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
989 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
993 void SCCPSolver::visitStoreInst(Instruction &SI) {
994 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
996 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
997 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
998 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1000 // Get the value we are storing into the global.
1001 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1003 mergeInValue(I->second, GV, PtrVal);
1004 if (I->second.isOverdefined())
1005 TrackedGlobals.erase(I); // No need to keep tracking this!
1009 // Handle load instructions. If the operand is a constant pointer to a constant
1010 // global, we can replace the load with the loaded constant value!
1011 void SCCPSolver::visitLoadInst(LoadInst &I) {
1012 LatticeVal &IV = ValueState[&I];
1013 if (IV.isOverdefined()) return;
1015 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1016 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1017 if (PtrVal.isConstant() && !I.isVolatile()) {
1018 Value *Ptr = PtrVal.getConstant();
1019 if (isa<ConstantPointerNull>(Ptr)) {
1020 // load null -> null
1021 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1025 // Transform load (constant global) into the value loaded.
1026 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1027 if (GV->isConstant()) {
1028 if (!GV->isDeclaration()) {
1029 markConstant(IV, &I, GV->getInitializer());
1032 } else if (!TrackedGlobals.empty()) {
1033 // If we are tracking this global, merge in the known value for it.
1034 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1035 TrackedGlobals.find(GV);
1036 if (It != TrackedGlobals.end()) {
1037 mergeInValue(IV, &I, It->second);
1043 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1044 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1045 if (CE->getOpcode() == Instruction::GetElementPtr)
1046 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1047 if (GV->isConstant() && !GV->isDeclaration())
1049 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1050 markConstant(IV, &I, V);
1055 // Otherwise we cannot say for certain what value this load will produce.
1057 markOverdefined(IV, &I);
1060 void SCCPSolver::visitCallSite(CallSite CS) {
1061 Function *F = CS.getCalledFunction();
1063 // If we are tracking this function, we must make sure to bind arguments as
1065 DenseMap<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
1066 if (F && F->hasInternalLinkage())
1067 TFRVI = TrackedFunctionRetVals.find(F);
1069 if (TFRVI != TrackedFunctionRetVals.end()) {
1070 // If this is the first call to the function hit, mark its entry block
1072 if (!BBExecutable.count(F->begin()))
1073 MarkBlockExecutable(F->begin());
1075 CallSite::arg_iterator CAI = CS.arg_begin();
1076 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1077 AI != E; ++AI, ++CAI) {
1078 LatticeVal &IV = ValueState[AI];
1079 if (!IV.isOverdefined())
1080 mergeInValue(IV, AI, getValueState(*CAI));
1083 Instruction *I = CS.getInstruction();
1084 if (I->getType() == Type::VoidTy) return;
1086 LatticeVal &IV = ValueState[I];
1087 if (IV.isOverdefined()) return;
1089 // Propagate the return value of the function to the value of the instruction.
1090 if (TFRVI != TrackedFunctionRetVals.end()) {
1091 mergeInValue(IV, I, TFRVI->second);
1095 if (F == 0 || !F->isDeclaration() || !canConstantFoldCallTo(F)) {
1096 markOverdefined(IV, I);
1100 SmallVector<Constant*, 8> Operands;
1101 Operands.reserve(I->getNumOperands()-1);
1103 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1105 LatticeVal &State = getValueState(*AI);
1106 if (State.isUndefined())
1107 return; // Operands are not resolved yet...
1108 else if (State.isOverdefined()) {
1109 markOverdefined(IV, I);
1112 assert(State.isConstant() && "Unknown state!");
1113 Operands.push_back(State.getConstant());
1116 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size()))
1117 markConstant(IV, I, C);
1119 markOverdefined(IV, I);
1123 void SCCPSolver::Solve() {
1124 // Process the work lists until they are empty!
1125 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1126 !OverdefinedInstWorkList.empty()) {
1127 // Process the instruction work list...
1128 while (!OverdefinedInstWorkList.empty()) {
1129 Value *I = OverdefinedInstWorkList.back();
1130 OverdefinedInstWorkList.pop_back();
1132 DOUT << "\nPopped off OI-WL: " << *I;
1134 // "I" got into the work list because it either made the transition from
1135 // bottom to constant
1137 // Anything on this worklist that is overdefined need not be visited
1138 // since all of its users will have already been marked as overdefined
1139 // Update all of the users of this instruction's value...
1141 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1143 OperandChangedState(*UI);
1145 // Process the instruction work list...
1146 while (!InstWorkList.empty()) {
1147 Value *I = InstWorkList.back();
1148 InstWorkList.pop_back();
1150 DOUT << "\nPopped off I-WL: " << *I;
1152 // "I" got into the work list because it either made the transition from
1153 // bottom to constant
1155 // Anything on this worklist that is overdefined need not be visited
1156 // since all of its users will have already been marked as overdefined.
1157 // Update all of the users of this instruction's value...
1159 if (!getValueState(I).isOverdefined())
1160 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1162 OperandChangedState(*UI);
1165 // Process the basic block work list...
1166 while (!BBWorkList.empty()) {
1167 BasicBlock *BB = BBWorkList.back();
1168 BBWorkList.pop_back();
1170 DOUT << "\nPopped off BBWL: " << *BB;
1172 // Notify all instructions in this basic block that they are newly
1179 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1180 /// that branches on undef values cannot reach any of their successors.
1181 /// However, this is not a safe assumption. After we solve dataflow, this
1182 /// method should be use to handle this. If this returns true, the solver
1183 /// should be rerun.
1185 /// This method handles this by finding an unresolved branch and marking it one
1186 /// of the edges from the block as being feasible, even though the condition
1187 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1188 /// CFG and only slightly pessimizes the analysis results (by marking one,
1189 /// potentially infeasible, edge feasible). This cannot usefully modify the
1190 /// constraints on the condition of the branch, as that would impact other users
1193 /// This scan also checks for values that use undefs, whose results are actually
1194 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1195 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1196 /// even if X isn't defined.
1197 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1198 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1199 if (!BBExecutable.count(BB))
1202 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1203 // Look for instructions which produce undef values.
1204 if (I->getType() == Type::VoidTy) continue;
1206 LatticeVal &LV = getValueState(I);
1207 if (!LV.isUndefined()) continue;
1209 // Get the lattice values of the first two operands for use below.
1210 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1212 if (I->getNumOperands() == 2) {
1213 // If this is a two-operand instruction, and if both operands are
1214 // undefs, the result stays undef.
1215 Op1LV = getValueState(I->getOperand(1));
1216 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1220 // If this is an instructions whose result is defined even if the input is
1221 // not fully defined, propagate the information.
1222 const Type *ITy = I->getType();
1223 switch (I->getOpcode()) {
1224 default: break; // Leave the instruction as an undef.
1225 case Instruction::ZExt:
1226 // After a zero extend, we know the top part is zero. SExt doesn't have
1227 // to be handled here, because we don't know whether the top part is 1's
1229 assert(Op0LV.isUndefined());
1230 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1232 case Instruction::Mul:
1233 case Instruction::And:
1234 // undef * X -> 0. X could be zero.
1235 // undef & X -> 0. X could be zero.
1236 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1239 case Instruction::Or:
1240 // undef | X -> -1. X could be -1.
1241 if (const PackedType *PTy = dyn_cast<PackedType>(ITy))
1242 markForcedConstant(LV, I, ConstantPacked::getAllOnesValue(PTy));
1244 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1247 case Instruction::SDiv:
1248 case Instruction::UDiv:
1249 case Instruction::SRem:
1250 case Instruction::URem:
1251 // X / undef -> undef. No change.
1252 // X % undef -> undef. No change.
1253 if (Op1LV.isUndefined()) break;
1255 // undef / X -> 0. X could be maxint.
1256 // undef % X -> 0. X could be 1.
1257 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1260 case Instruction::AShr:
1261 // undef >>s X -> undef. No change.
1262 if (Op0LV.isUndefined()) break;
1264 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1265 if (Op0LV.isConstant())
1266 markForcedConstant(LV, I, Op0LV.getConstant());
1268 markOverdefined(LV, I);
1270 case Instruction::LShr:
1271 case Instruction::Shl:
1272 // undef >> X -> undef. No change.
1273 // undef << X -> undef. No change.
1274 if (Op0LV.isUndefined()) break;
1276 // X >> undef -> 0. X could be 0.
1277 // X << undef -> 0. X could be 0.
1278 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1280 case Instruction::Select:
1281 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1282 if (Op0LV.isUndefined()) {
1283 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1284 Op1LV = getValueState(I->getOperand(2));
1285 } else if (Op1LV.isUndefined()) {
1286 // c ? undef : undef -> undef. No change.
1287 Op1LV = getValueState(I->getOperand(2));
1288 if (Op1LV.isUndefined())
1290 // Otherwise, c ? undef : x -> x.
1292 // Leave Op1LV as Operand(1)'s LatticeValue.
1295 if (Op1LV.isConstant())
1296 markForcedConstant(LV, I, Op1LV.getConstant());
1298 markOverdefined(LV, I);
1303 TerminatorInst *TI = BB->getTerminator();
1304 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1305 if (!BI->isConditional()) continue;
1306 if (!getValueState(BI->getCondition()).isUndefined())
1308 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1309 if (!getValueState(SI->getCondition()).isUndefined())
1315 // If the edge to the first successor isn't thought to be feasible yet, mark
1317 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(0))))
1320 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1321 // and return. This will make other blocks reachable, which will allow new
1322 // values to be discovered and existing ones to be moved in the lattice.
1323 markEdgeExecutable(BB, TI->getSuccessor(0));
1332 //===--------------------------------------------------------------------===//
1334 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1335 /// Sparse Conditional Constant Propagator.
1337 struct SCCP : public FunctionPass {
1338 // runOnFunction - Run the Sparse Conditional Constant Propagation
1339 // algorithm, and return true if the function was modified.
1341 bool runOnFunction(Function &F);
1343 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1344 AU.setPreservesCFG();
1348 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
1349 } // end anonymous namespace
1352 // createSCCPPass - This is the public interface to this file...
1353 FunctionPass *llvm::createSCCPPass() {
1358 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1359 // and return true if the function was modified.
1361 bool SCCP::runOnFunction(Function &F) {
1362 DOUT << "SCCP on function '" << F.getName() << "'\n";
1365 // Mark the first block of the function as being executable.
1366 Solver.MarkBlockExecutable(F.begin());
1368 // Mark all arguments to the function as being overdefined.
1369 DenseMap<Value*, LatticeVal> &Values = Solver.getValueMapping();
1370 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
1371 Values[AI].markOverdefined();
1373 // Solve for constants.
1374 bool ResolvedUndefs = true;
1375 while (ResolvedUndefs) {
1377 DOUT << "RESOLVING UNDEFs\n";
1378 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1381 bool MadeChanges = false;
1383 // If we decided that there are basic blocks that are dead in this function,
1384 // delete their contents now. Note that we cannot actually delete the blocks,
1385 // as we cannot modify the CFG of the function.
1387 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1388 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1389 if (!ExecutableBBs.count(BB)) {
1390 DOUT << " BasicBlock Dead:" << *BB;
1393 // Delete the instructions backwards, as it has a reduced likelihood of
1394 // having to update as many def-use and use-def chains.
1395 std::vector<Instruction*> Insts;
1396 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1399 while (!Insts.empty()) {
1400 Instruction *I = Insts.back();
1402 if (!I->use_empty())
1403 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1404 BB->getInstList().erase(I);
1409 // Iterate over all of the instructions in a function, replacing them with
1410 // constants if we have found them to be of constant values.
1412 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1413 Instruction *Inst = BI++;
1414 if (Inst->getType() != Type::VoidTy) {
1415 LatticeVal &IV = Values[Inst];
1416 if (IV.isConstant() || IV.isUndefined() &&
1417 !isa<TerminatorInst>(Inst)) {
1418 Constant *Const = IV.isConstant()
1419 ? IV.getConstant() : UndefValue::get(Inst->getType());
1420 DOUT << " Constant: " << *Const << " = " << *Inst;
1422 // Replaces all of the uses of a variable with uses of the constant.
1423 Inst->replaceAllUsesWith(Const);
1425 // Delete the instruction.
1426 BB->getInstList().erase(Inst);
1428 // Hey, we just changed something!
1440 //===--------------------------------------------------------------------===//
1442 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1443 /// Constant Propagation.
1445 struct IPSCCP : public ModulePass {
1446 bool runOnModule(Module &M);
1449 RegisterPass<IPSCCP>
1450 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1451 } // end anonymous namespace
1453 // createIPSCCPPass - This is the public interface to this file...
1454 ModulePass *llvm::createIPSCCPPass() {
1455 return new IPSCCP();
1459 static bool AddressIsTaken(GlobalValue *GV) {
1460 // Delete any dead constantexpr klingons.
1461 GV->removeDeadConstantUsers();
1463 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1465 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1466 if (SI->getOperand(0) == GV || SI->isVolatile())
1467 return true; // Storing addr of GV.
1468 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1469 // Make sure we are calling the function, not passing the address.
1470 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1471 for (CallSite::arg_iterator AI = CS.arg_begin(),
1472 E = CS.arg_end(); AI != E; ++AI)
1475 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1476 if (LI->isVolatile())
1484 bool IPSCCP::runOnModule(Module &M) {
1487 // Loop over all functions, marking arguments to those with their addresses
1488 // taken or that are external as overdefined.
1490 DenseMap<Value*, LatticeVal> &Values = Solver.getValueMapping();
1491 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1492 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1493 if (!F->isDeclaration())
1494 Solver.MarkBlockExecutable(F->begin());
1495 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1497 Values[AI].markOverdefined();
1499 Solver.AddTrackedFunction(F);
1502 // Loop over global variables. We inform the solver about any internal global
1503 // variables that do not have their 'addresses taken'. If they don't have
1504 // their addresses taken, we can propagate constants through them.
1505 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1507 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1508 Solver.TrackValueOfGlobalVariable(G);
1510 // Solve for constants.
1511 bool ResolvedUndefs = true;
1512 while (ResolvedUndefs) {
1515 DOUT << "RESOLVING UNDEFS\n";
1516 ResolvedUndefs = false;
1517 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1518 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1521 bool MadeChanges = false;
1523 // Iterate over all of the instructions in the module, replacing them with
1524 // constants if we have found them to be of constant values.
1526 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1527 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1528 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1530 if (!AI->use_empty()) {
1531 LatticeVal &IV = Values[AI];
1532 if (IV.isConstant() || IV.isUndefined()) {
1533 Constant *CST = IV.isConstant() ?
1534 IV.getConstant() : UndefValue::get(AI->getType());
1535 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1537 // Replaces all of the uses of a variable with uses of the
1539 AI->replaceAllUsesWith(CST);
1544 std::vector<BasicBlock*> BlocksToErase;
1545 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1546 if (!ExecutableBBs.count(BB)) {
1547 DOUT << " BasicBlock Dead:" << *BB;
1550 // Delete the instructions backwards, as it has a reduced likelihood of
1551 // having to update as many def-use and use-def chains.
1552 std::vector<Instruction*> Insts;
1553 TerminatorInst *TI = BB->getTerminator();
1554 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1557 while (!Insts.empty()) {
1558 Instruction *I = Insts.back();
1560 if (!I->use_empty())
1561 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1562 BB->getInstList().erase(I);
1567 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1568 BasicBlock *Succ = TI->getSuccessor(i);
1569 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1570 TI->getSuccessor(i)->removePredecessor(BB);
1572 if (!TI->use_empty())
1573 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1574 BB->getInstList().erase(TI);
1576 if (&*BB != &F->front())
1577 BlocksToErase.push_back(BB);
1579 new UnreachableInst(BB);
1582 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1583 Instruction *Inst = BI++;
1584 if (Inst->getType() != Type::VoidTy) {
1585 LatticeVal &IV = Values[Inst];
1586 if (IV.isConstant() || IV.isUndefined() &&
1587 !isa<TerminatorInst>(Inst)) {
1588 Constant *Const = IV.isConstant()
1589 ? IV.getConstant() : UndefValue::get(Inst->getType());
1590 DOUT << " Constant: " << *Const << " = " << *Inst;
1592 // Replaces all of the uses of a variable with uses of the
1594 Inst->replaceAllUsesWith(Const);
1596 // Delete the instruction.
1597 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1598 BB->getInstList().erase(Inst);
1600 // Hey, we just changed something!
1608 // Now that all instructions in the function are constant folded, erase dead
1609 // blocks, because we can now use ConstantFoldTerminator to get rid of
1611 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1612 // If there are any PHI nodes in this successor, drop entries for BB now.
1613 BasicBlock *DeadBB = BlocksToErase[i];
1614 while (!DeadBB->use_empty()) {
1615 Instruction *I = cast<Instruction>(DeadBB->use_back());
1616 bool Folded = ConstantFoldTerminator(I->getParent());
1618 // The constant folder may not have been able to fold the terminator
1619 // if this is a branch or switch on undef. Fold it manually as a
1620 // branch to the first successor.
1621 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1622 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1623 "Branch should be foldable!");
1624 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1625 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1627 assert(0 && "Didn't fold away reference to block!");
1630 // Make this an uncond branch to the first successor.
1631 TerminatorInst *TI = I->getParent()->getTerminator();
1632 new BranchInst(TI->getSuccessor(0), TI);
1634 // Remove entries in successor phi nodes to remove edges.
1635 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1636 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1638 // Remove the old terminator.
1639 TI->eraseFromParent();
1643 // Finally, delete the basic block.
1644 F->getBasicBlockList().erase(DeadBB);
1648 // If we inferred constant or undef return values for a function, we replaced
1649 // all call uses with the inferred value. This means we don't need to bother
1650 // actually returning anything from the function. Replace all return
1651 // instructions with return undef.
1652 const DenseMap<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1653 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1654 E = RV.end(); I != E; ++I)
1655 if (!I->second.isOverdefined() &&
1656 I->first->getReturnType() != Type::VoidTy) {
1657 Function *F = I->first;
1658 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1659 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1660 if (!isa<UndefValue>(RI->getOperand(0)))
1661 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1664 // If we infered constant or undef values for globals variables, we can delete
1665 // the global and any stores that remain to it.
1666 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1667 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1668 E = TG.end(); I != E; ++I) {
1669 GlobalVariable *GV = I->first;
1670 assert(!I->second.isOverdefined() &&
1671 "Overdefined values should have been taken out of the map!");
1672 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
1673 while (!GV->use_empty()) {
1674 StoreInst *SI = cast<StoreInst>(GV->use_back());
1675 SI->eraseFromParent();
1677 M.getGlobalList().erase(GV);