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 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Type.h"
31 #include "llvm/Support/InstVisitor.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/ADT/hash_map"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
41 // InstVal class - This class represents the different lattice values that an
42 // instruction may occupy. It is a simple class with value semantics.
45 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
49 undefined, // This instruction has no known value
50 constant, // This instruction has a constant value
51 overdefined // This instruction has an unknown value
52 } LatticeValue; // The current lattice position
53 Constant *ConstantVal; // If Constant value, the current value
55 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
57 // markOverdefined - Return true if this is a new status to be in...
58 inline bool markOverdefined() {
59 if (LatticeValue != overdefined) {
60 LatticeValue = overdefined;
66 // markConstant - Return true if this is a new status for us...
67 inline bool markConstant(Constant *V) {
68 if (LatticeValue != constant) {
69 LatticeValue = constant;
73 assert(ConstantVal == V && "Marking constant with different value");
78 inline bool isUndefined() const { return LatticeValue == undefined; }
79 inline bool isConstant() const { return LatticeValue == constant; }
80 inline bool isOverdefined() const { return LatticeValue == overdefined; }
82 inline Constant *getConstant() const {
83 assert(isConstant() && "Cannot get the constant of a non-constant!");
88 } // end anonymous namespace
91 //===----------------------------------------------------------------------===//
94 // This class does all of the work of Sparse Conditional Constant Propagation.
97 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
98 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
99 hash_map<Value*, InstVal> ValueState; // The state each value is in...
101 // The reason for two worklists is that overdefined is the lowest state
102 // on the lattice, and moving things to overdefined as fast as possible
103 // makes SCCP converge much faster.
104 // By having a separate worklist, we accomplish this because everything
105 // possibly overdefined will become overdefined at the soonest possible
107 std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined
108 // instruction work list
109 std::vector<Instruction*> InstWorkList;// The instruction work list
112 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
114 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
115 /// overdefined, despite the fact that the PHI node is overdefined.
116 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
118 /// KnownFeasibleEdges - Entries in this set are edges which have already had
119 /// PHI nodes retriggered.
120 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
121 std::set<Edge> KnownFeasibleEdges;
124 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
125 // and return true if the function was modified.
127 bool runOnFunction(Function &F);
129 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
130 AU.setPreservesCFG();
134 //===--------------------------------------------------------------------===//
135 // The implementation of this class
138 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
140 // markConstant - Make a value be marked as "constant". If the value
141 // is not already a constant, add it to the instruction work list so that
142 // the users of the instruction are updated later.
144 inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
145 if (IV.markConstant(C)) {
146 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
147 InstWorkList.push_back(I);
150 inline void markConstant(Instruction *I, Constant *C) {
151 markConstant(ValueState[I], I, C);
154 // markOverdefined - Make a value be marked as "overdefined". If the
155 // value is not already overdefined, add it to the overdefined instruction
156 // work list so that the users of the instruction are updated later.
158 inline void markOverdefined(InstVal &IV, Instruction *I) {
159 if (IV.markOverdefined()) {
160 DEBUG(std::cerr << "markOverdefined: " << *I);
161 OverdefinedInstWorkList.push_back(I); // Only instructions go on the work list
164 inline void markOverdefined(Instruction *I) {
165 markOverdefined(ValueState[I], I);
168 // getValueState - Return the InstVal object that corresponds to the value.
169 // This function is necessary because not all values should start out in the
170 // underdefined state... Argument's should be overdefined, and
171 // constants should be marked as constants. If a value is not known to be an
172 // Instruction object, then use this accessor to get its value from the map.
174 inline InstVal &getValueState(Value *V) {
175 hash_map<Value*, InstVal>::iterator I = ValueState.find(V);
176 if (I != ValueState.end()) return I->second; // Common case, in the map
178 if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
179 ValueState[CPV].markConstant(CPV);
180 } else if (isa<Argument>(V)) { // Arguments are overdefined
181 ValueState[V].markOverdefined();
183 // All others are underdefined by default...
184 return ValueState[V];
187 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
188 // work list if it is not already executable...
190 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
191 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
192 return; // This edge is already known to be executable!
194 if (BBExecutable.count(Dest)) {
195 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
196 << " -> " << Dest->getName() << "\n");
198 // The destination is already executable, but we just made an edge
199 // feasible that wasn't before. Revisit the PHI nodes in the block
200 // because they have potentially new operands.
201 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) {
202 PHINode *PN = cast<PHINode>(I);
207 DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
208 BBExecutable.insert(Dest); // Basic block is executable!
209 BBWorkList.push_back(Dest); // Add the block to the work list!
214 // visit implementations - Something changed in this instruction... Either an
215 // operand made a transition, or the instruction is newly executable. Change
216 // the value type of I to reflect these changes if appropriate.
218 void visitPHINode(PHINode &I);
221 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
222 void visitTerminatorInst(TerminatorInst &TI);
224 void visitCastInst(CastInst &I);
225 void visitSelectInst(SelectInst &I);
226 void visitBinaryOperator(Instruction &I);
227 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
229 // Instructions that cannot be folded away...
230 void visitStoreInst (Instruction &I) { /*returns void*/ }
231 void visitLoadInst (LoadInst &I);
232 void visitGetElementPtrInst(GetElementPtrInst &I);
233 void visitCallInst (CallInst &I);
234 void visitInvokeInst (TerminatorInst &I) {
235 if (I.getType() != Type::VoidTy) markOverdefined(&I);
236 visitTerminatorInst(I);
238 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
239 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
240 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
241 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
242 void visitFreeInst (Instruction &I) { /*returns void*/ }
244 void visitInstruction(Instruction &I) {
245 // If a new instruction is added to LLVM that we don't handle...
246 std::cerr << "SCCP: Don't know how to handle: " << I;
247 markOverdefined(&I); // Just in case
250 // getFeasibleSuccessors - Return a vector of booleans to indicate which
251 // successors are reachable from a given terminator instruction.
253 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
255 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
256 // block to the 'To' basic block is currently feasible...
258 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
260 // OperandChangedState - This method is invoked on all of the users of an
261 // instruction that was just changed state somehow.... Based on this
262 // information, we need to update the specified user of this instruction.
264 void OperandChangedState(User *U) {
265 // Only instructions use other variable values!
266 Instruction &I = cast<Instruction>(*U);
267 if (BBExecutable.count(I.getParent())) // Inst is executable?
272 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
273 } // end anonymous namespace
276 // createSCCPPass - This is the public interface to this file...
277 FunctionPass *llvm::createSCCPPass() {
282 //===----------------------------------------------------------------------===//
283 // SCCP Class Implementation
286 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
287 // and return true if the function was modified.
289 bool SCCP::runOnFunction(Function &F) {
290 // Mark the first block of the function as being executable...
291 BBExecutable.insert(F.begin()); // Basic block is executable!
292 BBWorkList.push_back(F.begin()); // Add the block to the work list!
294 // Process the work lists until they are empty!
295 while (!BBWorkList.empty() || !InstWorkList.empty() ||
296 !OverdefinedInstWorkList.empty()) {
297 // Process the instruction work list...
298 while (!OverdefinedInstWorkList.empty()) {
299 Instruction *I = OverdefinedInstWorkList.back();
300 OverdefinedInstWorkList.pop_back();
302 DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
304 // "I" got into the work list because it either made the transition from
305 // bottom to constant
307 // Anything on this worklist that is overdefined need not be visited
308 // since all of its users will have already been marked as overdefined
309 // Update all of the users of this instruction's value...
311 for_each(I->use_begin(), I->use_end(),
312 bind_obj(this, &SCCP::OperandChangedState));
314 // Process the instruction work list...
315 while (!InstWorkList.empty()) {
316 Instruction *I = InstWorkList.back();
317 InstWorkList.pop_back();
319 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
321 // "I" got into the work list because it either made the transition from
322 // bottom to constant
324 // Anything on this worklist that is overdefined need not be visited
325 // since all of its users will have already been marked as overdefined.
326 // Update all of the users of this instruction's value...
328 InstVal &Ival = getValueState (I);
329 if (!Ival.isOverdefined())
330 for_each(I->use_begin(), I->use_end(),
331 bind_obj(this, &SCCP::OperandChangedState));
334 // Process the basic block work list...
335 while (!BBWorkList.empty()) {
336 BasicBlock *BB = BBWorkList.back();
337 BBWorkList.pop_back();
339 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
341 // Notify all instructions in this basic block that they are newly
347 DEBUG(for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
348 if (!BBExecutable.count(I))
349 std::cerr << "BasicBlock Dead:" << *I);
351 // Iterate over all of the instructions in a function, replacing them with
352 // constants if we have found them to be of constant values.
354 bool MadeChanges = false;
355 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
356 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
357 Instruction &Inst = *BI;
358 InstVal &IV = ValueState[&Inst];
359 if (IV.isConstant()) {
360 Constant *Const = IV.getConstant();
361 DEBUG(std::cerr << "Constant: " << *Const << " = " << Inst);
363 // Replaces all of the uses of a variable with uses of the constant.
364 Inst.replaceAllUsesWith(Const);
366 // Remove the operator from the list of definitions... and delete it.
367 BI = BB->getInstList().erase(BI);
369 // Hey, we just changed something!
377 // Reset state so that the next invocation will have empty data structures
378 BBExecutable.clear();
380 std::vector<Instruction*>().swap(OverdefinedInstWorkList);
381 std::vector<Instruction*>().swap(InstWorkList);
382 std::vector<BasicBlock*>().swap(BBWorkList);
388 // getFeasibleSuccessors - Return a vector of booleans to indicate which
389 // successors are reachable from a given terminator instruction.
391 void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
392 Succs.resize(TI.getNumSuccessors());
393 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
394 if (BI->isUnconditional()) {
397 InstVal &BCValue = getValueState(BI->getCondition());
398 if (BCValue.isOverdefined() ||
399 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
400 // Overdefined condition variables, and branches on unfoldable constant
401 // conditions, mean the branch could go either way.
402 Succs[0] = Succs[1] = true;
403 } else if (BCValue.isConstant()) {
404 // Constant condition variables mean the branch can only go a single way
405 Succs[BCValue.getConstant() == ConstantBool::False] = true;
408 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
409 // Invoke instructions successors are always executable.
410 Succs[0] = Succs[1] = true;
411 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
412 InstVal &SCValue = getValueState(SI->getCondition());
413 if (SCValue.isOverdefined() || // Overdefined condition?
414 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
415 // All destinations are executable!
416 Succs.assign(TI.getNumSuccessors(), true);
417 } else if (SCValue.isConstant()) {
418 Constant *CPV = SCValue.getConstant();
419 // Make sure to skip the "default value" which isn't a value
420 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
421 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
427 // Constant value not equal to any of the branches... must execute
428 // default branch then...
432 std::cerr << "SCCP: Don't know how to handle: " << TI;
433 Succs.assign(TI.getNumSuccessors(), true);
438 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
439 // block to the 'To' basic block is currently feasible...
441 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
442 assert(BBExecutable.count(To) && "Dest should always be alive!");
444 // Make sure the source basic block is executable!!
445 if (!BBExecutable.count(From)) return false;
447 // Check to make sure this edge itself is actually feasible now...
448 TerminatorInst *TI = From->getTerminator();
449 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
450 if (BI->isUnconditional())
453 InstVal &BCValue = getValueState(BI->getCondition());
454 if (BCValue.isOverdefined()) {
455 // Overdefined condition variables mean the branch could go either way.
457 } else if (BCValue.isConstant()) {
458 // Not branching on an evaluatable constant?
459 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
461 // Constant condition variables mean the branch can only go a single way
462 return BI->getSuccessor(BCValue.getConstant() ==
463 ConstantBool::False) == To;
467 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
468 // Invoke instructions successors are always executable.
470 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
471 InstVal &SCValue = getValueState(SI->getCondition());
472 if (SCValue.isOverdefined()) { // Overdefined condition?
473 // All destinations are executable!
475 } else if (SCValue.isConstant()) {
476 Constant *CPV = SCValue.getConstant();
477 if (!isa<ConstantInt>(CPV))
478 return true; // not a foldable constant?
480 // Make sure to skip the "default value" which isn't a value
481 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
482 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
483 return SI->getSuccessor(i) == To;
485 // Constant value not equal to any of the branches... must execute
486 // default branch then...
487 return SI->getDefaultDest() == To;
491 std::cerr << "Unknown terminator instruction: " << *TI;
496 // visit Implementations - Something changed in this instruction... Either an
497 // operand made a transition, or the instruction is newly executable. Change
498 // the value type of I to reflect these changes if appropriate. This method
499 // makes sure to do the following actions:
501 // 1. If a phi node merges two constants in, and has conflicting value coming
502 // from different branches, or if the PHI node merges in an overdefined
503 // value, then the PHI node becomes overdefined.
504 // 2. If a phi node merges only constants in, and they all agree on value, the
505 // PHI node becomes a constant value equal to that.
506 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
507 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
508 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
509 // 6. If a conditional branch has a value that is constant, make the selected
510 // destination executable
511 // 7. If a conditional branch has a value that is overdefined, make all
512 // successors executable.
514 void SCCP::visitPHINode(PHINode &PN) {
515 InstVal &PNIV = getValueState(&PN);
516 if (PNIV.isOverdefined()) {
517 // There may be instructions using this PHI node that are not overdefined
518 // themselves. If so, make sure that they know that the PHI node operand
520 std::multimap<PHINode*, Instruction*>::iterator I, E;
521 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
523 std::vector<Instruction*> Users;
524 Users.reserve(std::distance(I, E));
525 for (; I != E; ++I) Users.push_back(I->second);
526 while (!Users.empty()) {
531 return; // Quick exit
534 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
535 // and slow us down a lot. Just mark them overdefined.
536 if (PN.getNumIncomingValues() > 64) {
537 markOverdefined(PNIV, &PN);
541 // Look at all of the executable operands of the PHI node. If any of them
542 // are overdefined, the PHI becomes overdefined as well. If they are all
543 // constant, and they agree with each other, the PHI becomes the identical
544 // constant. If they are constant and don't agree, the PHI is overdefined.
545 // If there are no executable operands, the PHI remains undefined.
547 Constant *OperandVal = 0;
548 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
549 InstVal &IV = getValueState(PN.getIncomingValue(i));
550 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
552 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
553 if (IV.isOverdefined()) { // PHI node becomes overdefined!
554 markOverdefined(PNIV, &PN);
558 if (OperandVal == 0) { // Grab the first value...
559 OperandVal = IV.getConstant();
560 } else { // Another value is being merged in!
561 // There is already a reachable operand. If we conflict with it,
562 // then the PHI node becomes overdefined. If we agree with it, we
565 // Check to see if there are two different constants merging...
566 if (IV.getConstant() != OperandVal) {
567 // Yes there is. This means the PHI node is not constant.
568 // You must be overdefined poor PHI.
570 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
571 return; // I'm done analyzing you
577 // If we exited the loop, this means that the PHI node only has constant
578 // arguments that agree with each other(and OperandVal is the constant) or
579 // OperandVal is null because there are no defined incoming arguments. If
580 // this is the case, the PHI remains undefined.
583 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
586 void SCCP::visitTerminatorInst(TerminatorInst &TI) {
587 std::vector<bool> SuccFeasible;
588 getFeasibleSuccessors(TI, SuccFeasible);
590 BasicBlock *BB = TI.getParent();
592 // Mark all feasible successors executable...
593 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
595 markEdgeExecutable(BB, TI.getSuccessor(i));
598 void SCCP::visitCastInst(CastInst &I) {
599 Value *V = I.getOperand(0);
600 InstVal &VState = getValueState(V);
601 if (VState.isOverdefined()) // Inherit overdefinedness of operand
603 else if (VState.isConstant()) // Propagate constant value
604 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
607 void SCCP::visitSelectInst(SelectInst &I) {
608 InstVal &CondValue = getValueState(I.getCondition());
609 if (CondValue.isOverdefined())
611 else if (CondValue.isConstant()) {
612 if (CondValue.getConstant() == ConstantBool::True) {
613 InstVal &Val = getValueState(I.getTrueValue());
614 if (Val.isOverdefined())
616 else if (Val.isConstant())
617 markConstant(&I, Val.getConstant());
618 } else if (CondValue.getConstant() == ConstantBool::False) {
619 InstVal &Val = getValueState(I.getFalseValue());
620 if (Val.isOverdefined())
622 else if (Val.isConstant())
623 markConstant(&I, Val.getConstant());
629 // Handle BinaryOperators and Shift Instructions...
630 void SCCP::visitBinaryOperator(Instruction &I) {
631 InstVal &IV = ValueState[&I];
632 if (IV.isOverdefined()) return;
634 InstVal &V1State = getValueState(I.getOperand(0));
635 InstVal &V2State = getValueState(I.getOperand(1));
637 if (V1State.isOverdefined() || V2State.isOverdefined()) {
638 // If both operands are PHI nodes, it is possible that this instruction has
639 // a constant value, despite the fact that the PHI node doesn't. Check for
640 // this condition now.
641 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
642 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
643 if (PN1->getParent() == PN2->getParent()) {
644 // Since the two PHI nodes are in the same basic block, they must have
645 // entries for the same predecessors. Walk the predecessor list, and
646 // if all of the incoming values are constants, and the result of
647 // evaluating this expression with all incoming value pairs is the
648 // same, then this expression is a constant even though the PHI node
649 // is not a constant!
651 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
652 InstVal &In1 = getValueState(PN1->getIncomingValue(i));
653 BasicBlock *InBlock = PN1->getIncomingBlock(i);
654 InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
656 if (In1.isOverdefined() || In2.isOverdefined()) {
657 Result.markOverdefined();
658 break; // Cannot fold this operation over the PHI nodes!
659 } else if (In1.isConstant() && In2.isConstant()) {
660 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
662 if (Result.isUndefined())
663 Result.markConstant(V);
664 else if (Result.isConstant() && Result.getConstant() != V) {
665 Result.markOverdefined();
671 // If we found a constant value here, then we know the instruction is
672 // constant despite the fact that the PHI nodes are overdefined.
673 if (Result.isConstant()) {
674 markConstant(IV, &I, Result.getConstant());
675 // Remember that this instruction is virtually using the PHI node
677 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
678 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
680 } else if (Result.isUndefined()) {
684 // Okay, this really is overdefined now. Since we might have
685 // speculatively thought that this was not overdefined before, and
686 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
687 // make sure to clean out any entries that we put there, for
689 std::multimap<PHINode*, Instruction*>::iterator It, E;
690 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
692 if (It->second == &I) {
693 UsersOfOverdefinedPHIs.erase(It++);
697 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
699 if (It->second == &I) {
700 UsersOfOverdefinedPHIs.erase(It++);
706 markOverdefined(IV, &I);
707 } else if (V1State.isConstant() && V2State.isConstant()) {
708 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
709 V2State.getConstant()));
713 // Handle getelementptr instructions... if all operands are constants then we
714 // can turn this into a getelementptr ConstantExpr.
716 void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
717 InstVal &IV = ValueState[&I];
718 if (IV.isOverdefined()) return;
720 std::vector<Constant*> Operands;
721 Operands.reserve(I.getNumOperands());
723 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
724 InstVal &State = getValueState(I.getOperand(i));
725 if (State.isUndefined())
726 return; // Operands are not resolved yet...
727 else if (State.isOverdefined()) {
728 markOverdefined(IV, &I);
731 assert(State.isConstant() && "Unknown state!");
732 Operands.push_back(State.getConstant());
735 Constant *Ptr = Operands[0];
736 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
738 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
741 /// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
742 /// return the constant value being addressed by the constant expression, or
743 /// null if something is funny.
745 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
746 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
747 return 0; // Do not allow stepping over the value!
749 // Loop over all of the operands, tracking down which value we are
751 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
752 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
753 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
754 if (CS == 0) return 0;
755 if (CU->getValue() >= CS->getNumOperands()) return 0;
756 C = CS->getOperand(CU->getValue());
757 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
758 ConstantArray *CA = dyn_cast<ConstantArray>(C);
759 if (CA == 0) return 0;
760 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
761 C = CA->getOperand(CS->getValue());
767 // Handle load instructions. If the operand is a constant pointer to a constant
768 // global, we can replace the load with the loaded constant value!
769 void SCCP::visitLoadInst(LoadInst &I) {
770 InstVal &IV = ValueState[&I];
771 if (IV.isOverdefined()) return;
773 InstVal &PtrVal = getValueState(I.getOperand(0));
774 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
775 if (PtrVal.isConstant() && !I.isVolatile()) {
776 Value *Ptr = PtrVal.getConstant();
777 if (isa<ConstantPointerNull>(Ptr)) {
779 markConstant(IV, &I, Constant::getNullValue(I.getType()));
783 // Transform load (constant global) into the value loaded.
784 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
785 if (GV->isConstant() && !GV->isExternal()) {
786 markConstant(IV, &I, GV->getInitializer());
790 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
791 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
792 if (CE->getOpcode() == Instruction::GetElementPtr)
793 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
794 if (GV->isConstant() && !GV->isExternal())
796 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
797 markConstant(IV, &I, V);
802 // Otherwise we cannot say for certain what value this load will produce.
804 markOverdefined(IV, &I);
807 void SCCP::visitCallInst(CallInst &I) {
808 InstVal &IV = ValueState[&I];
809 if (IV.isOverdefined()) return;
811 Function *F = I.getCalledFunction();
812 if (F == 0 || !canConstantFoldCallTo(F)) {
813 markOverdefined(IV, &I);
817 std::vector<Constant*> Operands;
818 Operands.reserve(I.getNumOperands()-1);
820 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
821 InstVal &State = getValueState(I.getOperand(i));
822 if (State.isUndefined())
823 return; // Operands are not resolved yet...
824 else if (State.isOverdefined()) {
825 markOverdefined(IV, &I);
828 assert(State.isConstant() && "Unknown state!");
829 Operands.push_back(State.getConstant());
832 if (Constant *C = ConstantFoldCall(F, Operands))
833 markConstant(IV, &I, C);
835 markOverdefined(IV, &I);