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/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/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/InstVisitor.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/STLExtras.h"
46 STATISTIC(NumInstRemoved, "Number of instructions removed");
47 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
50 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
51 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
55 /// LatticeVal class - This class represents the different lattice values that
56 /// an LLVM value may occupy. It is a simple class with value semantics.
58 class VISIBILITY_HIDDEN LatticeVal {
60 /// undefined - This LLVM Value has no known value yet.
63 /// constant - This LLVM Value has a specific constant value.
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
72 /// overdefined - This instruction is not known to be constant, and we know
75 } LatticeValue; // The current lattice position
77 Constant *ConstantVal; // If Constant value, the current value
79 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
81 // markOverdefined - Return true if this is a new status to be in...
82 inline bool markOverdefined() {
83 if (LatticeValue != overdefined) {
84 LatticeValue = overdefined;
90 // markConstant - Return true if this is a new status for us.
91 inline bool markConstant(Constant *V) {
92 if (LatticeValue != constant) {
93 if (LatticeValue == undefined) {
94 LatticeValue = constant;
95 assert(V && "Marking constant with NULL");
98 assert(LatticeValue == forcedconstant &&
99 "Cannot move from overdefined to constant!");
100 // Stay at forcedconstant if the constant is the same.
101 if (V == ConstantVal) return false;
103 // Otherwise, we go to overdefined. Assumptions made based on the
104 // forced value are possibly wrong. Assuming this is another constant
105 // could expose a contradiction.
106 LatticeValue = overdefined;
110 assert(ConstantVal == V && "Marking constant with different value");
115 inline void markForcedConstant(Constant *V) {
116 assert(LatticeValue == undefined && "Can't force a defined value!");
117 LatticeValue = forcedconstant;
121 inline bool isUndefined() const { return LatticeValue == undefined; }
122 inline bool isConstant() const {
123 return LatticeValue == constant || LatticeValue == forcedconstant;
125 inline bool isOverdefined() const { return LatticeValue == overdefined; }
127 inline Constant *getConstant() const {
128 assert(isConstant() && "Cannot get the constant of a non-constant!");
133 //===----------------------------------------------------------------------===//
135 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
136 /// Constant Propagation.
138 class SCCPSolver : public InstVisitor<SCCPSolver> {
139 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
140 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
142 /// GlobalValue - If we are tracking any values for the contents of a global
143 /// variable, we keep a mapping from the constant accessor to the element of
144 /// the global, to the currently known value. If the value becomes
145 /// overdefined, it's entry is simply removed from this map.
146 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
148 /// TrackedRetVals - If we are tracking arguments into and the return
149 /// value out of a function, it will have an entry in this map, indicating
150 /// what the known return value for the function is.
151 DenseMap<Function*, LatticeVal> TrackedRetVals;
153 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
154 /// that return multiple values.
155 std::map<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
157 // The reason for two worklists is that overdefined is the lowest state
158 // on the lattice, and moving things to overdefined as fast as possible
159 // makes SCCP converge much faster.
160 // By having a separate worklist, we accomplish this because everything
161 // possibly overdefined will become overdefined at the soonest possible
163 std::vector<Value*> OverdefinedInstWorkList;
164 std::vector<Value*> InstWorkList;
167 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
169 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
170 /// overdefined, despite the fact that the PHI node is overdefined.
171 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
173 /// KnownFeasibleEdges - Entries in this set are edges which have already had
174 /// PHI nodes retriggered.
175 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
176 std::set<Edge> KnownFeasibleEdges;
179 /// MarkBlockExecutable - This method can be used by clients to mark all of
180 /// the blocks that are known to be intrinsically live in the processed unit.
181 void MarkBlockExecutable(BasicBlock *BB) {
182 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
183 BBExecutable.insert(BB); // Basic block is executable!
184 BBWorkList.push_back(BB); // Add the block to the work list!
187 /// TrackValueOfGlobalVariable - Clients can use this method to
188 /// inform the SCCPSolver that it should track loads and stores to the
189 /// specified global variable if it can. This is only legal to call if
190 /// performing Interprocedural SCCP.
191 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
192 const Type *ElTy = GV->getType()->getElementType();
193 if (ElTy->isFirstClassType()) {
194 LatticeVal &IV = TrackedGlobals[GV];
195 if (!isa<UndefValue>(GV->getInitializer()))
196 IV.markConstant(GV->getInitializer());
200 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
201 /// and out of the specified function (which cannot have its address taken),
202 /// this method must be called.
203 void AddTrackedFunction(Function *F) {
204 assert(F->hasInternalLinkage() && "Can only track internal functions!");
205 // Add an entry, F -> undef.
206 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
207 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
208 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
211 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
214 /// Solve - Solve for constants and executable blocks.
218 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
219 /// that branches on undef values cannot reach any of their successors.
220 /// However, this is not a safe assumption. After we solve dataflow, this
221 /// method should be use to handle this. If this returns true, the solver
223 bool ResolvedUndefsIn(Function &F);
225 /// getExecutableBlocks - Once we have solved for constants, return the set of
226 /// blocks that is known to be executable.
227 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
231 /// getValueMapping - Once we have solved for constants, return the mapping of
232 /// LLVM values to LatticeVals.
233 std::map<Value*, LatticeVal> &getValueMapping() {
237 /// getTrackedRetVals - Get the inferred return value map.
239 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
240 return TrackedRetVals;
243 /// getTrackedGlobals - Get and return the set of inferred initializers for
244 /// global variables.
245 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
246 return TrackedGlobals;
249 inline void markOverdefined(Value *V) {
250 markOverdefined(ValueState[V], V);
254 // markConstant - Make a value be marked as "constant". If the value
255 // is not already a constant, add it to the instruction work list so that
256 // the users of the instruction are updated later.
258 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
259 if (IV.markConstant(C)) {
260 DOUT << "markConstant: " << *C << ": " << *V;
261 InstWorkList.push_back(V);
265 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
266 IV.markForcedConstant(C);
267 DOUT << "markForcedConstant: " << *C << ": " << *V;
268 InstWorkList.push_back(V);
271 inline void markConstant(Value *V, Constant *C) {
272 markConstant(ValueState[V], V, C);
275 // markOverdefined - Make a value be marked as "overdefined". If the
276 // value is not already overdefined, add it to the overdefined instruction
277 // work list so that the users of the instruction are updated later.
278 inline void markOverdefined(LatticeVal &IV, Value *V) {
279 if (IV.markOverdefined()) {
280 DEBUG(DOUT << "markOverdefined: ";
281 if (Function *F = dyn_cast<Function>(V))
282 DOUT << "Function '" << F->getName() << "'\n";
285 // Only instructions go on the work list
286 OverdefinedInstWorkList.push_back(V);
290 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
291 if (IV.isOverdefined() || MergeWithV.isUndefined())
293 if (MergeWithV.isOverdefined())
294 markOverdefined(IV, V);
295 else if (IV.isUndefined())
296 markConstant(IV, V, MergeWithV.getConstant());
297 else if (IV.getConstant() != MergeWithV.getConstant())
298 markOverdefined(IV, V);
301 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
302 return mergeInValue(ValueState[V], V, MergeWithV);
306 // getValueState - Return the LatticeVal object that corresponds to the value.
307 // This function is necessary because not all values should start out in the
308 // underdefined state... Argument's should be overdefined, and
309 // constants should be marked as constants. If a value is not known to be an
310 // Instruction object, then use this accessor to get its value from the map.
312 inline LatticeVal &getValueState(Value *V) {
313 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
314 if (I != ValueState.end()) return I->second; // Common case, in the map
316 if (Constant *C = dyn_cast<Constant>(V)) {
317 if (isa<UndefValue>(V)) {
318 // Nothing to do, remain undefined.
320 LatticeVal &LV = ValueState[C];
321 LV.markConstant(C); // Constants are constant
325 // All others are underdefined by default...
326 return ValueState[V];
329 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
330 // work list if it is not already executable...
332 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
333 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
334 return; // This edge is already known to be executable!
336 if (BBExecutable.count(Dest)) {
337 DOUT << "Marking Edge Executable: " << Source->getNameStart()
338 << " -> " << Dest->getNameStart() << "\n";
340 // The destination is already executable, but we just made an edge
341 // feasible that wasn't before. Revisit the PHI nodes in the block
342 // because they have potentially new operands.
343 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
344 visitPHINode(*cast<PHINode>(I));
347 MarkBlockExecutable(Dest);
351 // getFeasibleSuccessors - Return a vector of booleans to indicate which
352 // successors are reachable from a given terminator instruction.
354 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
356 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
357 // block to the 'To' basic block is currently feasible...
359 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
361 // OperandChangedState - This method is invoked on all of the users of an
362 // instruction that was just changed state somehow.... Based on this
363 // information, we need to update the specified user of this instruction.
365 void OperandChangedState(User *U) {
366 // Only instructions use other variable values!
367 Instruction &I = cast<Instruction>(*U);
368 if (BBExecutable.count(I.getParent())) // Inst is executable?
373 friend class InstVisitor<SCCPSolver>;
375 // visit implementations - Something changed in this instruction... Either an
376 // operand made a transition, or the instruction is newly executable. Change
377 // the value type of I to reflect these changes if appropriate.
379 void visitPHINode(PHINode &I);
382 void visitReturnInst(ReturnInst &I);
383 void visitTerminatorInst(TerminatorInst &TI);
385 void visitCastInst(CastInst &I);
386 void visitGetResultInst(GetResultInst &GRI);
387 void visitSelectInst(SelectInst &I);
388 void visitBinaryOperator(Instruction &I);
389 void visitCmpInst(CmpInst &I);
390 void visitExtractElementInst(ExtractElementInst &I);
391 void visitInsertElementInst(InsertElementInst &I);
392 void visitShuffleVectorInst(ShuffleVectorInst &I);
394 // Instructions that cannot be folded away...
395 void visitStoreInst (Instruction &I);
396 void visitLoadInst (LoadInst &I);
397 void visitGetElementPtrInst(GetElementPtrInst &I);
398 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
399 void visitInvokeInst (InvokeInst &II) {
400 visitCallSite(CallSite::get(&II));
401 visitTerminatorInst(II);
403 void visitCallSite (CallSite CS);
404 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
405 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
406 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
407 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
408 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
409 void visitFreeInst (Instruction &I) { /*returns void*/ }
411 void visitInstruction(Instruction &I) {
412 // If a new instruction is added to LLVM that we don't handle...
413 cerr << "SCCP: Don't know how to handle: " << I;
414 markOverdefined(&I); // Just in case
418 } // end anonymous namespace
421 // getFeasibleSuccessors - Return a vector of booleans to indicate which
422 // successors are reachable from a given terminator instruction.
424 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
425 SmallVector<bool, 16> &Succs) {
426 Succs.resize(TI.getNumSuccessors());
427 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
428 if (BI->isUnconditional()) {
431 LatticeVal &BCValue = getValueState(BI->getCondition());
432 if (BCValue.isOverdefined() ||
433 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
434 // Overdefined condition variables, and branches on unfoldable constant
435 // conditions, mean the branch could go either way.
436 Succs[0] = Succs[1] = true;
437 } else if (BCValue.isConstant()) {
438 // Constant condition variables mean the branch can only go a single way
439 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
442 } else if (isa<InvokeInst>(&TI)) {
443 // Invoke instructions successors are always executable.
444 Succs[0] = Succs[1] = true;
445 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
446 LatticeVal &SCValue = getValueState(SI->getCondition());
447 if (SCValue.isOverdefined() || // Overdefined condition?
448 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
449 // All destinations are executable!
450 Succs.assign(TI.getNumSuccessors(), true);
451 } else if (SCValue.isConstant())
452 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
454 assert(0 && "SCCP: Don't know how to handle this terminator!");
459 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
460 // block to the 'To' basic block is currently feasible...
462 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
463 assert(BBExecutable.count(To) && "Dest should always be alive!");
465 // Make sure the source basic block is executable!!
466 if (!BBExecutable.count(From)) return false;
468 // Check to make sure this edge itself is actually feasible now...
469 TerminatorInst *TI = From->getTerminator();
470 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
471 if (BI->isUnconditional())
474 LatticeVal &BCValue = getValueState(BI->getCondition());
475 if (BCValue.isOverdefined()) {
476 // Overdefined condition variables mean the branch could go either way.
478 } else if (BCValue.isConstant()) {
479 // Not branching on an evaluatable constant?
480 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
482 // Constant condition variables mean the branch can only go a single way
483 return BI->getSuccessor(BCValue.getConstant() ==
484 ConstantInt::getFalse()) == To;
488 } else if (isa<InvokeInst>(TI)) {
489 // Invoke instructions successors are always executable.
491 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
492 LatticeVal &SCValue = getValueState(SI->getCondition());
493 if (SCValue.isOverdefined()) { // Overdefined condition?
494 // All destinations are executable!
496 } else if (SCValue.isConstant()) {
497 Constant *CPV = SCValue.getConstant();
498 if (!isa<ConstantInt>(CPV))
499 return true; // not a foldable constant?
501 // Make sure to skip the "default value" which isn't a value
502 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
503 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
504 return SI->getSuccessor(i) == To;
506 // Constant value not equal to any of the branches... must execute
507 // default branch then...
508 return SI->getDefaultDest() == To;
512 cerr << "Unknown terminator instruction: " << *TI;
517 // visit Implementations - Something changed in this instruction... Either an
518 // operand made a transition, or the instruction is newly executable. Change
519 // the value type of I to reflect these changes if appropriate. This method
520 // makes sure to do the following actions:
522 // 1. If a phi node merges two constants in, and has conflicting value coming
523 // from different branches, or if the PHI node merges in an overdefined
524 // value, then the PHI node becomes overdefined.
525 // 2. If a phi node merges only constants in, and they all agree on value, the
526 // PHI node becomes a constant value equal to that.
527 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
528 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
529 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
530 // 6. If a conditional branch has a value that is constant, make the selected
531 // destination executable
532 // 7. If a conditional branch has a value that is overdefined, make all
533 // successors executable.
535 void SCCPSolver::visitPHINode(PHINode &PN) {
536 LatticeVal &PNIV = getValueState(&PN);
537 if (PNIV.isOverdefined()) {
538 // There may be instructions using this PHI node that are not overdefined
539 // themselves. If so, make sure that they know that the PHI node operand
541 std::multimap<PHINode*, Instruction*>::iterator I, E;
542 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
544 SmallVector<Instruction*, 16> Users;
545 for (; I != E; ++I) Users.push_back(I->second);
546 while (!Users.empty()) {
551 return; // Quick exit
554 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
555 // and slow us down a lot. Just mark them overdefined.
556 if (PN.getNumIncomingValues() > 64) {
557 markOverdefined(PNIV, &PN);
561 // Look at all of the executable operands of the PHI node. If any of them
562 // are overdefined, the PHI becomes overdefined as well. If they are all
563 // constant, and they agree with each other, the PHI becomes the identical
564 // constant. If they are constant and don't agree, the PHI is overdefined.
565 // If there are no executable operands, the PHI remains undefined.
567 Constant *OperandVal = 0;
568 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
569 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
570 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
572 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
573 if (IV.isOverdefined()) { // PHI node becomes overdefined!
574 markOverdefined(PNIV, &PN);
578 if (OperandVal == 0) { // Grab the first value...
579 OperandVal = IV.getConstant();
580 } else { // Another value is being merged in!
581 // There is already a reachable operand. If we conflict with it,
582 // then the PHI node becomes overdefined. If we agree with it, we
585 // Check to see if there are two different constants merging...
586 if (IV.getConstant() != OperandVal) {
587 // Yes there is. This means the PHI node is not constant.
588 // You must be overdefined poor PHI.
590 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
591 return; // I'm done analyzing you
597 // If we exited the loop, this means that the PHI node only has constant
598 // arguments that agree with each other(and OperandVal is the constant) or
599 // OperandVal is null because there are no defined incoming arguments. If
600 // this is the case, the PHI remains undefined.
603 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
606 void SCCPSolver::visitReturnInst(ReturnInst &I) {
607 if (I.getNumOperands() == 0) return; // Ret void
609 Function *F = I.getParent()->getParent();
610 // If we are tracking the return value of this function, merge it in.
611 if (!F->hasInternalLinkage())
614 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
615 DenseMap<Function*, LatticeVal>::iterator TFRVI =
616 TrackedRetVals.find(F);
617 if (TFRVI != TrackedRetVals.end() &&
618 !TFRVI->second.isOverdefined()) {
619 LatticeVal &IV = getValueState(I.getOperand(0));
620 mergeInValue(TFRVI->second, F, IV);
625 // Handle functions that return multiple values.
626 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
627 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
628 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
629 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
630 if (It == TrackedMultipleRetVals.end()) break;
631 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
636 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
637 SmallVector<bool, 16> SuccFeasible;
638 getFeasibleSuccessors(TI, SuccFeasible);
640 BasicBlock *BB = TI.getParent();
642 // Mark all feasible successors executable...
643 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
645 markEdgeExecutable(BB, TI.getSuccessor(i));
648 void SCCPSolver::visitCastInst(CastInst &I) {
649 Value *V = I.getOperand(0);
650 LatticeVal &VState = getValueState(V);
651 if (VState.isOverdefined()) // Inherit overdefinedness of operand
653 else if (VState.isConstant()) // Propagate constant value
654 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
655 VState.getConstant(), I.getType()));
658 void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
659 Value *Aggr = GRI.getOperand(0);
661 // If the operand to the getresult is an undef, the result is undef.
662 if (isa<UndefValue>(Aggr))
666 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
667 F = CI->getCalledFunction();
669 F = cast<InvokeInst>(Aggr)->getCalledFunction();
671 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
673 if (F == 0 || TrackedMultipleRetVals.empty()) {
674 markOverdefined(&GRI);
678 // See if we are tracking the result of the callee.
679 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
680 It = TrackedMultipleRetVals.find(std::make_pair(F, GRI.getIndex()));
682 // If not tracking this function (for example, it is a declaration) just move
684 if (It == TrackedMultipleRetVals.end()) {
685 markOverdefined(&GRI);
689 // Otherwise, the value will be merged in here as a result of CallSite
693 void SCCPSolver::visitSelectInst(SelectInst &I) {
694 LatticeVal &CondValue = getValueState(I.getCondition());
695 if (CondValue.isUndefined())
697 if (CondValue.isConstant()) {
698 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
699 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
700 : I.getFalseValue()));
705 // Otherwise, the condition is overdefined or a constant we can't evaluate.
706 // See if we can produce something better than overdefined based on the T/F
708 LatticeVal &TVal = getValueState(I.getTrueValue());
709 LatticeVal &FVal = getValueState(I.getFalseValue());
711 // select ?, C, C -> C.
712 if (TVal.isConstant() && FVal.isConstant() &&
713 TVal.getConstant() == FVal.getConstant()) {
714 markConstant(&I, FVal.getConstant());
718 if (TVal.isUndefined()) { // select ?, undef, X -> X.
719 mergeInValue(&I, FVal);
720 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
721 mergeInValue(&I, TVal);
727 // Handle BinaryOperators and Shift Instructions...
728 void SCCPSolver::visitBinaryOperator(Instruction &I) {
729 LatticeVal &IV = ValueState[&I];
730 if (IV.isOverdefined()) return;
732 LatticeVal &V1State = getValueState(I.getOperand(0));
733 LatticeVal &V2State = getValueState(I.getOperand(1));
735 if (V1State.isOverdefined() || V2State.isOverdefined()) {
736 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
737 // operand is overdefined.
738 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
739 LatticeVal *NonOverdefVal = 0;
740 if (!V1State.isOverdefined()) {
741 NonOverdefVal = &V1State;
742 } else if (!V2State.isOverdefined()) {
743 NonOverdefVal = &V2State;
747 if (NonOverdefVal->isUndefined()) {
748 // Could annihilate value.
749 if (I.getOpcode() == Instruction::And)
750 markConstant(IV, &I, Constant::getNullValue(I.getType()));
751 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
752 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
754 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
757 if (I.getOpcode() == Instruction::And) {
758 if (NonOverdefVal->getConstant()->isNullValue()) {
759 markConstant(IV, &I, NonOverdefVal->getConstant());
760 return; // X and 0 = 0
763 if (ConstantInt *CI =
764 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
765 if (CI->isAllOnesValue()) {
766 markConstant(IV, &I, NonOverdefVal->getConstant());
767 return; // X or -1 = -1
775 // If both operands are PHI nodes, it is possible that this instruction has
776 // a constant value, despite the fact that the PHI node doesn't. Check for
777 // this condition now.
778 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
779 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
780 if (PN1->getParent() == PN2->getParent()) {
781 // Since the two PHI nodes are in the same basic block, they must have
782 // entries for the same predecessors. Walk the predecessor list, and
783 // if all of the incoming values are constants, and the result of
784 // evaluating this expression with all incoming value pairs is the
785 // same, then this expression is a constant even though the PHI node
786 // is not a constant!
788 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
789 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
790 BasicBlock *InBlock = PN1->getIncomingBlock(i);
792 getValueState(PN2->getIncomingValueForBlock(InBlock));
794 if (In1.isOverdefined() || In2.isOverdefined()) {
795 Result.markOverdefined();
796 break; // Cannot fold this operation over the PHI nodes!
797 } else if (In1.isConstant() && In2.isConstant()) {
798 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
800 if (Result.isUndefined())
801 Result.markConstant(V);
802 else if (Result.isConstant() && Result.getConstant() != V) {
803 Result.markOverdefined();
809 // If we found a constant value here, then we know the instruction is
810 // constant despite the fact that the PHI nodes are overdefined.
811 if (Result.isConstant()) {
812 markConstant(IV, &I, Result.getConstant());
813 // Remember that this instruction is virtually using the PHI node
815 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
816 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
818 } else if (Result.isUndefined()) {
822 // Okay, this really is overdefined now. Since we might have
823 // speculatively thought that this was not overdefined before, and
824 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
825 // make sure to clean out any entries that we put there, for
827 std::multimap<PHINode*, Instruction*>::iterator It, E;
828 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
830 if (It->second == &I) {
831 UsersOfOverdefinedPHIs.erase(It++);
835 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
837 if (It->second == &I) {
838 UsersOfOverdefinedPHIs.erase(It++);
844 markOverdefined(IV, &I);
845 } else if (V1State.isConstant() && V2State.isConstant()) {
846 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
847 V2State.getConstant()));
851 // Handle ICmpInst instruction...
852 void SCCPSolver::visitCmpInst(CmpInst &I) {
853 LatticeVal &IV = ValueState[&I];
854 if (IV.isOverdefined()) return;
856 LatticeVal &V1State = getValueState(I.getOperand(0));
857 LatticeVal &V2State = getValueState(I.getOperand(1));
859 if (V1State.isOverdefined() || V2State.isOverdefined()) {
860 // If both operands are PHI nodes, it is possible that this instruction has
861 // a constant value, despite the fact that the PHI node doesn't. Check for
862 // this condition now.
863 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
864 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
865 if (PN1->getParent() == PN2->getParent()) {
866 // Since the two PHI nodes are in the same basic block, they must have
867 // entries for the same predecessors. Walk the predecessor list, and
868 // if all of the incoming values are constants, and the result of
869 // evaluating this expression with all incoming value pairs is the
870 // same, then this expression is a constant even though the PHI node
871 // is not a constant!
873 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
874 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
875 BasicBlock *InBlock = PN1->getIncomingBlock(i);
877 getValueState(PN2->getIncomingValueForBlock(InBlock));
879 if (In1.isOverdefined() || In2.isOverdefined()) {
880 Result.markOverdefined();
881 break; // Cannot fold this operation over the PHI nodes!
882 } else if (In1.isConstant() && In2.isConstant()) {
883 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
886 if (Result.isUndefined())
887 Result.markConstant(V);
888 else if (Result.isConstant() && Result.getConstant() != V) {
889 Result.markOverdefined();
895 // If we found a constant value here, then we know the instruction is
896 // constant despite the fact that the PHI nodes are overdefined.
897 if (Result.isConstant()) {
898 markConstant(IV, &I, Result.getConstant());
899 // Remember that this instruction is virtually using the PHI node
901 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
902 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
904 } else if (Result.isUndefined()) {
908 // Okay, this really is overdefined now. Since we might have
909 // speculatively thought that this was not overdefined before, and
910 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
911 // make sure to clean out any entries that we put there, for
913 std::multimap<PHINode*, Instruction*>::iterator It, E;
914 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
916 if (It->second == &I) {
917 UsersOfOverdefinedPHIs.erase(It++);
921 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
923 if (It->second == &I) {
924 UsersOfOverdefinedPHIs.erase(It++);
930 markOverdefined(IV, &I);
931 } else if (V1State.isConstant() && V2State.isConstant()) {
932 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
933 V1State.getConstant(),
934 V2State.getConstant()));
938 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
939 // FIXME : SCCP does not handle vectors properly.
944 LatticeVal &ValState = getValueState(I.getOperand(0));
945 LatticeVal &IdxState = getValueState(I.getOperand(1));
947 if (ValState.isOverdefined() || IdxState.isOverdefined())
949 else if(ValState.isConstant() && IdxState.isConstant())
950 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
951 IdxState.getConstant()));
955 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
956 // FIXME : SCCP does not handle vectors properly.
960 LatticeVal &ValState = getValueState(I.getOperand(0));
961 LatticeVal &EltState = getValueState(I.getOperand(1));
962 LatticeVal &IdxState = getValueState(I.getOperand(2));
964 if (ValState.isOverdefined() || EltState.isOverdefined() ||
965 IdxState.isOverdefined())
967 else if(ValState.isConstant() && EltState.isConstant() &&
968 IdxState.isConstant())
969 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
970 EltState.getConstant(),
971 IdxState.getConstant()));
972 else if (ValState.isUndefined() && EltState.isConstant() &&
973 IdxState.isConstant())
974 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
975 EltState.getConstant(),
976 IdxState.getConstant()));
980 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
981 // FIXME : SCCP does not handle vectors properly.
985 LatticeVal &V1State = getValueState(I.getOperand(0));
986 LatticeVal &V2State = getValueState(I.getOperand(1));
987 LatticeVal &MaskState = getValueState(I.getOperand(2));
989 if (MaskState.isUndefined() ||
990 (V1State.isUndefined() && V2State.isUndefined()))
991 return; // Undefined output if mask or both inputs undefined.
993 if (V1State.isOverdefined() || V2State.isOverdefined() ||
994 MaskState.isOverdefined()) {
997 // A mix of constant/undef inputs.
998 Constant *V1 = V1State.isConstant() ?
999 V1State.getConstant() : UndefValue::get(I.getType());
1000 Constant *V2 = V2State.isConstant() ?
1001 V2State.getConstant() : UndefValue::get(I.getType());
1002 Constant *Mask = MaskState.isConstant() ?
1003 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1004 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1009 // Handle getelementptr instructions... if all operands are constants then we
1010 // can turn this into a getelementptr ConstantExpr.
1012 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1013 LatticeVal &IV = ValueState[&I];
1014 if (IV.isOverdefined()) return;
1016 SmallVector<Constant*, 8> Operands;
1017 Operands.reserve(I.getNumOperands());
1019 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1020 LatticeVal &State = getValueState(I.getOperand(i));
1021 if (State.isUndefined())
1022 return; // Operands are not resolved yet...
1023 else if (State.isOverdefined()) {
1024 markOverdefined(IV, &I);
1027 assert(State.isConstant() && "Unknown state!");
1028 Operands.push_back(State.getConstant());
1031 Constant *Ptr = Operands[0];
1032 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1034 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1038 void SCCPSolver::visitStoreInst(Instruction &SI) {
1039 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1041 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1042 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1043 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1045 // Get the value we are storing into the global.
1046 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1048 mergeInValue(I->second, GV, PtrVal);
1049 if (I->second.isOverdefined())
1050 TrackedGlobals.erase(I); // No need to keep tracking this!
1054 // Handle load instructions. If the operand is a constant pointer to a constant
1055 // global, we can replace the load with the loaded constant value!
1056 void SCCPSolver::visitLoadInst(LoadInst &I) {
1057 LatticeVal &IV = ValueState[&I];
1058 if (IV.isOverdefined()) return;
1060 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1061 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1062 if (PtrVal.isConstant() && !I.isVolatile()) {
1063 Value *Ptr = PtrVal.getConstant();
1064 // TODO: Consider a target hook for valid address spaces for this xform.
1065 if (isa<ConstantPointerNull>(Ptr) &&
1066 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
1067 // load null -> null
1068 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1072 // Transform load (constant global) into the value loaded.
1073 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1074 if (GV->isConstant()) {
1075 if (!GV->isDeclaration()) {
1076 markConstant(IV, &I, GV->getInitializer());
1079 } else if (!TrackedGlobals.empty()) {
1080 // If we are tracking this global, merge in the known value for it.
1081 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1082 TrackedGlobals.find(GV);
1083 if (It != TrackedGlobals.end()) {
1084 mergeInValue(IV, &I, It->second);
1090 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1091 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1092 if (CE->getOpcode() == Instruction::GetElementPtr)
1093 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1094 if (GV->isConstant() && !GV->isDeclaration())
1096 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1097 markConstant(IV, &I, V);
1102 // Otherwise we cannot say for certain what value this load will produce.
1104 markOverdefined(IV, &I);
1107 void SCCPSolver::visitCallSite(CallSite CS) {
1108 Function *F = CS.getCalledFunction();
1109 Instruction *I = CS.getInstruction();
1111 // The common case is that we aren't tracking the callee, either because we
1112 // are not doing interprocedural analysis or the callee is indirect, or is
1113 // external. Handle these cases first.
1114 if (F == 0 || !F->hasInternalLinkage()) {
1116 // Void return and not tracking callee, just bail.
1117 if (I->getType() == Type::VoidTy) return;
1119 // Otherwise, if we have a single return value case, and if the function is
1120 // a declaration, maybe we can constant fold it.
1121 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1122 canConstantFoldCallTo(F)) {
1124 SmallVector<Constant*, 8> Operands;
1125 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1127 LatticeVal &State = getValueState(*AI);
1128 if (State.isUndefined())
1129 return; // Operands are not resolved yet.
1130 else if (State.isOverdefined()) {
1134 assert(State.isConstant() && "Unknown state!");
1135 Operands.push_back(State.getConstant());
1138 // If we can constant fold this, mark the result of the call as a
1140 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1146 // Otherwise, we don't know anything about this call, mark it overdefined.
1151 // If this is a single/zero retval case, see if we're tracking the function.
1152 const StructType *RetSTy = dyn_cast<StructType>(I->getType());
1154 // Check to see if we're tracking this callee, if not, handle it in the
1155 // common path above.
1156 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1157 if (TFRVI == TrackedRetVals.end())
1158 goto CallOverdefined;
1160 // If so, propagate the return value of the callee into this call result.
1161 mergeInValue(I, TFRVI->second);
1163 // Check to see if we're tracking this callee, if not, handle it in the
1164 // common path above.
1165 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1166 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1167 if (TMRVI == TrackedMultipleRetVals.end())
1168 goto CallOverdefined;
1170 // If we are tracking this callee, propagate the return values of the call
1171 // into this call site. We do this by walking all the getresult uses.
1172 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1174 GetResultInst *GRI = cast<GetResultInst>(*UI);
1176 TrackedMultipleRetVals[std::make_pair(F, GRI->getIndex())]);
1180 // Finally, if this is the first call to the function hit, mark its entry
1181 // block executable.
1182 if (!BBExecutable.count(F->begin()))
1183 MarkBlockExecutable(F->begin());
1185 // Propagate information from this call site into the callee.
1186 CallSite::arg_iterator CAI = CS.arg_begin();
1187 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1188 AI != E; ++AI, ++CAI) {
1189 LatticeVal &IV = ValueState[AI];
1190 if (!IV.isOverdefined())
1191 mergeInValue(IV, AI, getValueState(*CAI));
1196 void SCCPSolver::Solve() {
1197 // Process the work lists until they are empty!
1198 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1199 !OverdefinedInstWorkList.empty()) {
1200 // Process the instruction work list...
1201 while (!OverdefinedInstWorkList.empty()) {
1202 Value *I = OverdefinedInstWorkList.back();
1203 OverdefinedInstWorkList.pop_back();
1205 DOUT << "\nPopped off OI-WL: " << *I;
1207 // "I" got into the work list because it either made the transition from
1208 // bottom to constant
1210 // Anything on this worklist that is overdefined need not be visited
1211 // since all of its users will have already been marked as overdefined
1212 // Update all of the users of this instruction's value...
1214 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1216 OperandChangedState(*UI);
1218 // Process the instruction work list...
1219 while (!InstWorkList.empty()) {
1220 Value *I = InstWorkList.back();
1221 InstWorkList.pop_back();
1223 DOUT << "\nPopped off I-WL: " << *I;
1225 // "I" got into the work list because it either made the transition from
1226 // bottom to constant
1228 // Anything on this worklist that is overdefined need not be visited
1229 // since all of its users will have already been marked as overdefined.
1230 // Update all of the users of this instruction's value...
1232 if (!getValueState(I).isOverdefined())
1233 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1235 OperandChangedState(*UI);
1238 // Process the basic block work list...
1239 while (!BBWorkList.empty()) {
1240 BasicBlock *BB = BBWorkList.back();
1241 BBWorkList.pop_back();
1243 DOUT << "\nPopped off BBWL: " << *BB;
1245 // Notify all instructions in this basic block that they are newly
1252 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1253 /// that branches on undef values cannot reach any of their successors.
1254 /// However, this is not a safe assumption. After we solve dataflow, this
1255 /// method should be use to handle this. If this returns true, the solver
1256 /// should be rerun.
1258 /// This method handles this by finding an unresolved branch and marking it one
1259 /// of the edges from the block as being feasible, even though the condition
1260 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1261 /// CFG and only slightly pessimizes the analysis results (by marking one,
1262 /// potentially infeasible, edge feasible). This cannot usefully modify the
1263 /// constraints on the condition of the branch, as that would impact other users
1266 /// This scan also checks for values that use undefs, whose results are actually
1267 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1268 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1269 /// even if X isn't defined.
1270 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1271 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1272 if (!BBExecutable.count(BB))
1275 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1276 // Look for instructions which produce undef values.
1277 if (I->getType() == Type::VoidTy) continue;
1279 LatticeVal &LV = getValueState(I);
1280 if (!LV.isUndefined()) continue;
1282 // Get the lattice values of the first two operands for use below.
1283 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1285 if (I->getNumOperands() == 2) {
1286 // If this is a two-operand instruction, and if both operands are
1287 // undefs, the result stays undef.
1288 Op1LV = getValueState(I->getOperand(1));
1289 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1293 // If this is an instructions whose result is defined even if the input is
1294 // not fully defined, propagate the information.
1295 const Type *ITy = I->getType();
1296 switch (I->getOpcode()) {
1297 default: break; // Leave the instruction as an undef.
1298 case Instruction::ZExt:
1299 // After a zero extend, we know the top part is zero. SExt doesn't have
1300 // to be handled here, because we don't know whether the top part is 1's
1302 assert(Op0LV.isUndefined());
1303 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1305 case Instruction::Mul:
1306 case Instruction::And:
1307 // undef * X -> 0. X could be zero.
1308 // undef & X -> 0. X could be zero.
1309 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1312 case Instruction::Or:
1313 // undef | X -> -1. X could be -1.
1314 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1315 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
1317 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1320 case Instruction::SDiv:
1321 case Instruction::UDiv:
1322 case Instruction::SRem:
1323 case Instruction::URem:
1324 // X / undef -> undef. No change.
1325 // X % undef -> undef. No change.
1326 if (Op1LV.isUndefined()) break;
1328 // undef / X -> 0. X could be maxint.
1329 // undef % X -> 0. X could be 1.
1330 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1333 case Instruction::AShr:
1334 // undef >>s X -> undef. No change.
1335 if (Op0LV.isUndefined()) break;
1337 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1338 if (Op0LV.isConstant())
1339 markForcedConstant(LV, I, Op0LV.getConstant());
1341 markOverdefined(LV, I);
1343 case Instruction::LShr:
1344 case Instruction::Shl:
1345 // undef >> X -> undef. No change.
1346 // undef << X -> undef. No change.
1347 if (Op0LV.isUndefined()) break;
1349 // X >> undef -> 0. X could be 0.
1350 // X << undef -> 0. X could be 0.
1351 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1353 case Instruction::Select:
1354 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1355 if (Op0LV.isUndefined()) {
1356 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1357 Op1LV = getValueState(I->getOperand(2));
1358 } else if (Op1LV.isUndefined()) {
1359 // c ? undef : undef -> undef. No change.
1360 Op1LV = getValueState(I->getOperand(2));
1361 if (Op1LV.isUndefined())
1363 // Otherwise, c ? undef : x -> x.
1365 // Leave Op1LV as Operand(1)'s LatticeValue.
1368 if (Op1LV.isConstant())
1369 markForcedConstant(LV, I, Op1LV.getConstant());
1371 markOverdefined(LV, I);
1376 TerminatorInst *TI = BB->getTerminator();
1377 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1378 if (!BI->isConditional()) continue;
1379 if (!getValueState(BI->getCondition()).isUndefined())
1381 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1382 if (!getValueState(SI->getCondition()).isUndefined())
1388 // If the edge to the second successor isn't thought to be feasible yet,
1389 // mark it so now. We pick the second one so that this goes to some
1390 // enumerated value in a switch instead of going to the default destination.
1391 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
1394 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1395 // and return. This will make other blocks reachable, which will allow new
1396 // values to be discovered and existing ones to be moved in the lattice.
1397 markEdgeExecutable(BB, TI->getSuccessor(1));
1399 // This must be a conditional branch of switch on undef. At this point,
1400 // force the old terminator to branch to the first successor. This is
1401 // required because we are now influencing the dataflow of the function with
1402 // the assumption that this edge is taken. If we leave the branch condition
1403 // as undef, then further analysis could think the undef went another way
1404 // leading to an inconsistent set of conclusions.
1405 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1406 BI->setCondition(ConstantInt::getFalse());
1408 SwitchInst *SI = cast<SwitchInst>(TI);
1409 SI->setCondition(SI->getCaseValue(1));
1420 //===--------------------------------------------------------------------===//
1422 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1423 /// Sparse Conditional Constant Propagator.
1425 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1426 static char ID; // Pass identification, replacement for typeid
1427 SCCP() : FunctionPass((intptr_t)&ID) {}
1429 // runOnFunction - Run the Sparse Conditional Constant Propagation
1430 // algorithm, and return true if the function was modified.
1432 bool runOnFunction(Function &F);
1434 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1435 AU.setPreservesCFG();
1438 } // end anonymous namespace
1441 static RegisterPass<SCCP>
1442 X("sccp", "Sparse Conditional Constant Propagation");
1444 // createSCCPPass - This is the public interface to this file...
1445 FunctionPass *llvm::createSCCPPass() {
1450 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1451 // and return true if the function was modified.
1453 bool SCCP::runOnFunction(Function &F) {
1454 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
1457 // Mark the first block of the function as being executable.
1458 Solver.MarkBlockExecutable(F.begin());
1460 // Mark all arguments to the function as being overdefined.
1461 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1462 Solver.markOverdefined(AI);
1464 // Solve for constants.
1465 bool ResolvedUndefs = true;
1466 while (ResolvedUndefs) {
1468 DOUT << "RESOLVING UNDEFs\n";
1469 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1472 bool MadeChanges = false;
1474 // If we decided that there are basic blocks that are dead in this function,
1475 // delete their contents now. Note that we cannot actually delete the blocks,
1476 // as we cannot modify the CFG of the function.
1478 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1479 SmallVector<Instruction*, 32> Insts;
1480 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1482 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1483 if (!ExecutableBBs.count(BB)) {
1484 DOUT << " BasicBlock Dead:" << *BB;
1487 // Delete the instructions backwards, as it has a reduced likelihood of
1488 // having to update as many def-use and use-def chains.
1489 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1492 while (!Insts.empty()) {
1493 Instruction *I = Insts.back();
1495 if (!I->use_empty())
1496 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1497 BB->getInstList().erase(I);
1502 // Iterate over all of the instructions in a function, replacing them with
1503 // constants if we have found them to be of constant values.
1505 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1506 Instruction *Inst = BI++;
1507 if (Inst->getType() == Type::VoidTy ||
1508 isa<StructType>(Inst->getType()) ||
1509 isa<TerminatorInst>(Inst))
1512 LatticeVal &IV = Values[Inst];
1513 if (!IV.isConstant() && !IV.isUndefined())
1516 Constant *Const = IV.isConstant()
1517 ? IV.getConstant() : UndefValue::get(Inst->getType());
1518 DOUT << " Constant: " << *Const << " = " << *Inst;
1520 // Replaces all of the uses of a variable with uses of the constant.
1521 Inst->replaceAllUsesWith(Const);
1523 // Delete the instruction.
1524 Inst->eraseFromParent();
1526 // Hey, we just changed something!
1536 //===--------------------------------------------------------------------===//
1538 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1539 /// Constant Propagation.
1541 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1543 IPSCCP() : ModulePass((intptr_t)&ID) {}
1544 bool runOnModule(Module &M);
1546 } // end anonymous namespace
1548 char IPSCCP::ID = 0;
1549 static RegisterPass<IPSCCP>
1550 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1552 // createIPSCCPPass - This is the public interface to this file...
1553 ModulePass *llvm::createIPSCCPPass() {
1554 return new IPSCCP();
1558 static bool AddressIsTaken(GlobalValue *GV) {
1559 // Delete any dead constantexpr klingons.
1560 GV->removeDeadConstantUsers();
1562 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1564 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1565 if (SI->getOperand(0) == GV || SI->isVolatile())
1566 return true; // Storing addr of GV.
1567 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1568 // Make sure we are calling the function, not passing the address.
1569 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1570 for (CallSite::arg_iterator AI = CS.arg_begin(),
1571 E = CS.arg_end(); AI != E; ++AI)
1574 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1575 if (LI->isVolatile())
1583 bool IPSCCP::runOnModule(Module &M) {
1586 // Loop over all functions, marking arguments to those with their addresses
1587 // taken or that are external as overdefined.
1589 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1590 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1591 if (!F->isDeclaration())
1592 Solver.MarkBlockExecutable(F->begin());
1593 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1595 Solver.markOverdefined(AI);
1597 Solver.AddTrackedFunction(F);
1600 // Loop over global variables. We inform the solver about any internal global
1601 // variables that do not have their 'addresses taken'. If they don't have
1602 // their addresses taken, we can propagate constants through them.
1603 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1605 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1606 Solver.TrackValueOfGlobalVariable(G);
1608 // Solve for constants.
1609 bool ResolvedUndefs = true;
1610 while (ResolvedUndefs) {
1613 DOUT << "RESOLVING UNDEFS\n";
1614 ResolvedUndefs = false;
1615 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1616 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1619 bool MadeChanges = false;
1621 // Iterate over all of the instructions in the module, replacing them with
1622 // constants if we have found them to be of constant values.
1624 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
1625 SmallVector<Instruction*, 32> Insts;
1626 SmallVector<BasicBlock*, 32> BlocksToErase;
1627 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1629 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1630 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1632 if (!AI->use_empty()) {
1633 LatticeVal &IV = Values[AI];
1634 if (IV.isConstant() || IV.isUndefined()) {
1635 Constant *CST = IV.isConstant() ?
1636 IV.getConstant() : UndefValue::get(AI->getType());
1637 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1639 // Replaces all of the uses of a variable with uses of the
1641 AI->replaceAllUsesWith(CST);
1646 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1647 if (!ExecutableBBs.count(BB)) {
1648 DOUT << " BasicBlock Dead:" << *BB;
1651 // Delete the instructions backwards, as it has a reduced likelihood of
1652 // having to update as many def-use and use-def chains.
1653 TerminatorInst *TI = BB->getTerminator();
1654 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1657 while (!Insts.empty()) {
1658 Instruction *I = Insts.back();
1660 if (!I->use_empty())
1661 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1662 BB->getInstList().erase(I);
1667 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1668 BasicBlock *Succ = TI->getSuccessor(i);
1669 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1670 TI->getSuccessor(i)->removePredecessor(BB);
1672 if (!TI->use_empty())
1673 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1674 BB->getInstList().erase(TI);
1676 if (&*BB != &F->front())
1677 BlocksToErase.push_back(BB);
1679 new UnreachableInst(BB);
1682 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1683 Instruction *Inst = BI++;
1684 if (Inst->getType() == Type::VoidTy ||
1685 isa<StructType>(Inst->getType()) ||
1686 isa<TerminatorInst>(Inst))
1689 LatticeVal &IV = Values[Inst];
1690 if (!IV.isConstant() && !IV.isUndefined())
1693 Constant *Const = IV.isConstant()
1694 ? IV.getConstant() : UndefValue::get(Inst->getType());
1695 DOUT << " Constant: " << *Const << " = " << *Inst;
1697 // Replaces all of the uses of a variable with uses of the
1699 Inst->replaceAllUsesWith(Const);
1701 // Delete the instruction.
1702 if (!isa<CallInst>(Inst))
1703 Inst->eraseFromParent();
1705 // Hey, we just changed something!
1711 // Now that all instructions in the function are constant folded, erase dead
1712 // blocks, because we can now use ConstantFoldTerminator to get rid of
1714 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1715 // If there are any PHI nodes in this successor, drop entries for BB now.
1716 BasicBlock *DeadBB = BlocksToErase[i];
1717 while (!DeadBB->use_empty()) {
1718 Instruction *I = cast<Instruction>(DeadBB->use_back());
1719 bool Folded = ConstantFoldTerminator(I->getParent());
1721 // The constant folder may not have been able to fold the terminator
1722 // if this is a branch or switch on undef. Fold it manually as a
1723 // branch to the first successor.
1724 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1725 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1726 "Branch should be foldable!");
1727 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1728 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1730 assert(0 && "Didn't fold away reference to block!");
1733 // Make this an uncond branch to the first successor.
1734 TerminatorInst *TI = I->getParent()->getTerminator();
1735 BranchInst::Create(TI->getSuccessor(0), TI);
1737 // Remove entries in successor phi nodes to remove edges.
1738 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1739 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1741 // Remove the old terminator.
1742 TI->eraseFromParent();
1746 // Finally, delete the basic block.
1747 F->getBasicBlockList().erase(DeadBB);
1749 BlocksToErase.clear();
1752 // If we inferred constant or undef return values for a function, we replaced
1753 // all call uses with the inferred value. This means we don't need to bother
1754 // actually returning anything from the function. Replace all return
1755 // instructions with return undef.
1756 // TODO: Process multiple value ret instructions also.
1757 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1758 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1759 E = RV.end(); I != E; ++I)
1760 if (!I->second.isOverdefined() &&
1761 I->first->getReturnType() != Type::VoidTy) {
1762 Function *F = I->first;
1763 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1764 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1765 if (!isa<UndefValue>(RI->getOperand(0)))
1766 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1769 // If we infered constant or undef values for globals variables, we can delete
1770 // the global and any stores that remain to it.
1771 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1772 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1773 E = TG.end(); I != E; ++I) {
1774 GlobalVariable *GV = I->first;
1775 assert(!I->second.isOverdefined() &&
1776 "Overdefined values should have been taken out of the map!");
1777 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
1778 while (!GV->use_empty()) {
1779 StoreInst *SI = cast<StoreInst>(GV->use_back());
1780 SI->eraseFromParent();
1782 M.getGlobalList().erase(GV);