This patch was contributed by Daniel Berlin!
[oota-llvm.git] / lib / Transforms / Scalar / SCCP.cpp
1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements sparse conditional constant propagation and merging:
11 //
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
17 //
18 // Notice that:
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.
21 //
22 //===----------------------------------------------------------------------===//
23
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 "Support/Debug.h"
34 #include "Support/hash_map"
35 #include "Support/Statistic.h"
36 #include "Support/STLExtras.h"
37 #include <algorithm>
38 #include <set>
39 using namespace llvm;
40
41 // InstVal class - This class represents the different lattice values that an 
42 // instruction may occupy.  It is a simple class with value semantics.
43 //
44 namespace {
45   Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
46
47 class InstVal {
48   enum { 
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
54 public:
55   inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
56
57   // markOverdefined - Return true if this is a new status to be in...
58   inline bool markOverdefined() {
59     if (LatticeValue != overdefined) {
60       LatticeValue = overdefined;
61       return true;
62     }
63     return false;
64   }
65
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;
70       ConstantVal = V;
71       return true;
72     } else {
73       assert(ConstantVal == V && "Marking constant with different value");
74     }
75     return false;
76   }
77
78   inline bool isUndefined()   const { return LatticeValue == undefined; }
79   inline bool isConstant()    const { return LatticeValue == constant; }
80   inline bool isOverdefined() const { return LatticeValue == overdefined; }
81
82   inline Constant *getConstant() const {
83     assert(isConstant() && "Cannot get the constant of a non-constant!");
84     return ConstantVal;
85   }
86 };
87
88 } // end anonymous namespace
89
90
91 //===----------------------------------------------------------------------===//
92 // SCCP Class
93 //
94 // This class does all of the work of Sparse Conditional Constant Propagation.
95 //
96 namespace {
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...
100
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
106   // point.
107   std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined 
108                                                     // instruction work list
109   std::vector<Instruction*> InstWorkList;// The instruction work list
110
111
112   std::vector<BasicBlock*>  BBWorkList;  // The BasicBlock work list
113
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;
117
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;
122 public:
123
124   // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
125   // and return true if the function was modified.
126   //
127   bool runOnFunction(Function &F);
128
129   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
130     AU.setPreservesCFG();
131   }
132
133
134   //===--------------------------------------------------------------------===//
135   // The implementation of this class
136   //
137 private:
138   friend class InstVisitor<SCCP>;        // Allow callbacks from visitor
139
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.
143   //
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);
148     }
149   }
150   inline void markConstant(Instruction *I, Constant *C) {
151     markConstant(ValueState[I], I, C);
152   }
153
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.
157   
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
162     }
163   }
164   inline void markOverdefined(Instruction *I) {
165     markOverdefined(ValueState[I], I);
166   }
167
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.
173   //
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
177       
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();
182     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
183       // The address of a global is a constant...
184       ValueState[V].markConstant(ConstantPointerRef::get(GV));
185     }
186     // All others are underdefined by default...
187     return ValueState[V];
188   }
189
190   // markEdgeExecutable - Mark a basic block as executable, adding it to the BB 
191   // work list if it is not already executable...
192   // 
193   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
194     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
195       return;  // This edge is already known to be executable!
196
197     if (BBExecutable.count(Dest)) {
198       DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
199                       << " -> " << Dest->getName() << "\n");
200
201       // The destination is already executable, but we just made an edge
202       // feasible that wasn't before.  Revisit the PHI nodes in the block
203       // because they have potentially new operands.
204       for (BasicBlock::iterator I = Dest->begin();
205            PHINode *PN = dyn_cast<PHINode>(I); ++I)
206         visitPHINode(*PN);
207
208     } else {
209       DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
210       BBExecutable.insert(Dest);   // Basic block is executable!
211       BBWorkList.push_back(Dest);  // Add the block to the work list!
212     }
213   }
214
215
216   // visit implementations - Something changed in this instruction... Either an 
217   // operand made a transition, or the instruction is newly executable.  Change
218   // the value type of I to reflect these changes if appropriate.
219   //
220   void visitPHINode(PHINode &I);
221
222   // Terminators
223   void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
224   void visitTerminatorInst(TerminatorInst &TI);
225
226   void visitCastInst(CastInst &I);
227   void visitSelectInst(SelectInst &I);
228   void visitBinaryOperator(Instruction &I);
229   void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
230
231   // Instructions that cannot be folded away...
232   void visitStoreInst     (Instruction &I) { /*returns void*/ }
233   void visitLoadInst      (LoadInst &I);
234   void visitGetElementPtrInst(GetElementPtrInst &I);
235   void visitCallInst      (CallInst &I);
236   void visitInvokeInst    (TerminatorInst &I) {
237     if (I.getType() != Type::VoidTy) markOverdefined(&I);
238     visitTerminatorInst(I);
239   }
240   void visitUnwindInst    (TerminatorInst &I) { /*returns void*/ }
241   void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
242   void visitVANextInst    (Instruction &I) { markOverdefined(&I); }
243   void visitVAArgInst     (Instruction &I) { markOverdefined(&I); }
244   void visitFreeInst      (Instruction &I) { /*returns void*/ }
245
246   void visitInstruction(Instruction &I) {
247     // If a new instruction is added to LLVM that we don't handle...
248     std::cerr << "SCCP: Don't know how to handle: " << I;
249     markOverdefined(&I);   // Just in case
250   }
251
252   // getFeasibleSuccessors - Return a vector of booleans to indicate which
253   // successors are reachable from a given terminator instruction.
254   //
255   void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
256
257   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
258   // block to the 'To' basic block is currently feasible...
259   //
260   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
261
262   // OperandChangedState - This method is invoked on all of the users of an
263   // instruction that was just changed state somehow....  Based on this
264   // information, we need to update the specified user of this instruction.
265   //
266   void OperandChangedState(User *U) {
267     // Only instructions use other variable values!
268     Instruction &I = cast<Instruction>(*U);
269     if (BBExecutable.count(I.getParent()))   // Inst is executable?
270       visit(I);
271   }
272 };
273
274   RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
275 } // end anonymous namespace
276
277
278 // createSCCPPass - This is the public interface to this file...
279 Pass *llvm::createSCCPPass() {
280   return new SCCP();
281 }
282
283
284 //===----------------------------------------------------------------------===//
285 // SCCP Class Implementation
286
287
288 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
289 // and return true if the function was modified.
290 //
291 bool SCCP::runOnFunction(Function &F) {
292   // Mark the first block of the function as being executable...
293   BBExecutable.insert(F.begin());   // Basic block is executable!
294   BBWorkList.push_back(F.begin());  // Add the block to the work list!
295
296   // Process the work lists until they are empty!
297   while (!BBWorkList.empty() || !InstWorkList.empty() || 
298          !OverdefinedInstWorkList.empty()) {
299     // Process the instruction work list...
300     while (!OverdefinedInstWorkList.empty()) {
301       Instruction *I = OverdefinedInstWorkList.back();
302       OverdefinedInstWorkList.pop_back();
303
304       DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
305       
306       // "I" got into the work list because it either made the transition from
307       // bottom to constant
308       //
309       // Anything on this worklist that is overdefined need not be visited
310       // since all of its users will have already been marked as overdefined
311       // Update all of the users of this instruction's value...
312       //
313       for_each(I->use_begin(), I->use_end(),
314                bind_obj(this, &SCCP::OperandChangedState));
315     }
316     // Process the instruction work list...
317     while (!InstWorkList.empty()) {
318       Instruction *I = InstWorkList.back();
319       InstWorkList.pop_back();
320
321       DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
322       
323       // "I" got into the work list because it either made the transition from
324       // bottom to constant
325       //
326       // Anything on this worklist that is overdefined need not be visited
327       // since all of its users will have already been marked as overdefined.
328       // Update all of the users of this instruction's value...
329       //
330       InstVal &Ival = getValueState (I);
331       if (!Ival.isOverdefined())
332         for_each(I->use_begin(), I->use_end(),
333                  bind_obj(this, &SCCP::OperandChangedState));
334     }
335
336     // Process the basic block work list...
337     while (!BBWorkList.empty()) {
338       BasicBlock *BB = BBWorkList.back();
339       BBWorkList.pop_back();
340
341       DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
342
343       // Notify all instructions in this basic block that they are newly
344       // executable.
345       visit(BB);
346     }
347   }
348
349   if (DebugFlag) {
350     for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
351       if (!BBExecutable.count(I))
352         std::cerr << "BasicBlock Dead:" << *I;
353   }
354
355   // Iterate over all of the instructions in a function, replacing them with
356   // constants if we have found them to be of constant values.
357   //
358   bool MadeChanges = false;
359   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
360     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
361       Instruction &Inst = *BI;
362       InstVal &IV = ValueState[&Inst];
363       if (IV.isConstant()) {
364         Constant *Const = IV.getConstant();
365         DEBUG(std::cerr << "Constant: " << *Const << " = " << Inst);
366
367         // Replaces all of the uses of a variable with uses of the constant.
368         Inst.replaceAllUsesWith(Const);
369
370         // Remove the operator from the list of definitions... and delete it.
371         BI = BB->getInstList().erase(BI);
372
373         // Hey, we just changed something!
374         MadeChanges = true;
375         ++NumInstRemoved;
376       } else {
377         ++BI;
378       }
379     }
380
381   // Reset state so that the next invocation will have empty data structures
382   BBExecutable.clear();
383   ValueState.clear();
384   std::vector<Instruction*>().swap(OverdefinedInstWorkList);
385   std::vector<Instruction*>().swap(InstWorkList);
386   std::vector<BasicBlock*>().swap(BBWorkList);
387
388   return MadeChanges;
389 }
390
391
392 // getFeasibleSuccessors - Return a vector of booleans to indicate which
393 // successors are reachable from a given terminator instruction.
394 //
395 void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
396   Succs.resize(TI.getNumSuccessors());
397   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
398     if (BI->isUnconditional()) {
399       Succs[0] = true;
400     } else {
401       InstVal &BCValue = getValueState(BI->getCondition());
402       if (BCValue.isOverdefined() ||
403           (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
404         // Overdefined condition variables, and branches on unfoldable constant
405         // conditions, mean the branch could go either way.
406         Succs[0] = Succs[1] = true;
407       } else if (BCValue.isConstant()) {
408         // Constant condition variables mean the branch can only go a single way
409         Succs[BCValue.getConstant() == ConstantBool::False] = true;
410       }
411     }
412   } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
413     // Invoke instructions successors are always executable.
414     Succs[0] = Succs[1] = true;
415   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
416     InstVal &SCValue = getValueState(SI->getCondition());
417     if (SCValue.isOverdefined() ||   // Overdefined condition?
418         (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
419       // All destinations are executable!
420       Succs.assign(TI.getNumSuccessors(), true);
421     } else if (SCValue.isConstant()) {
422       Constant *CPV = SCValue.getConstant();
423       // Make sure to skip the "default value" which isn't a value
424       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
425         if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
426           Succs[i] = true;
427           return;
428         }
429       }
430
431       // Constant value not equal to any of the branches... must execute
432       // default branch then...
433       Succs[0] = true;
434     }
435   } else {
436     std::cerr << "SCCP: Don't know how to handle: " << TI;
437     Succs.assign(TI.getNumSuccessors(), true);
438   }
439 }
440
441
442 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
443 // block to the 'To' basic block is currently feasible...
444 //
445 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
446   assert(BBExecutable.count(To) && "Dest should always be alive!");
447
448   // Make sure the source basic block is executable!!
449   if (!BBExecutable.count(From)) return false;
450   
451   // Check to make sure this edge itself is actually feasible now...
452   TerminatorInst *TI = From->getTerminator();
453   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
454     if (BI->isUnconditional())
455       return true;
456     else {
457       InstVal &BCValue = getValueState(BI->getCondition());
458       if (BCValue.isOverdefined()) {
459         // Overdefined condition variables mean the branch could go either way.
460         return true;
461       } else if (BCValue.isConstant()) {
462         // Not branching on an evaluatable constant?
463         if (!isa<ConstantBool>(BCValue.getConstant())) return true;
464
465         // Constant condition variables mean the branch can only go a single way
466         return BI->getSuccessor(BCValue.getConstant() == 
467                                        ConstantBool::False) == To;
468       }
469       return false;
470     }
471   } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
472     // Invoke instructions successors are always executable.
473     return true;
474   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
475     InstVal &SCValue = getValueState(SI->getCondition());
476     if (SCValue.isOverdefined()) {  // Overdefined condition?
477       // All destinations are executable!
478       return true;
479     } else if (SCValue.isConstant()) {
480       Constant *CPV = SCValue.getConstant();
481       if (!isa<ConstantInt>(CPV))
482         return true;  // not a foldable constant?
483
484       // Make sure to skip the "default value" which isn't a value
485       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
486         if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
487           return SI->getSuccessor(i) == To;
488
489       // Constant value not equal to any of the branches... must execute
490       // default branch then...
491       return SI->getDefaultDest() == To;
492     }
493     return false;
494   } else {
495     std::cerr << "Unknown terminator instruction: " << *TI;
496     abort();
497   }
498 }
499
500 // visit Implementations - Something changed in this instruction... Either an
501 // operand made a transition, or the instruction is newly executable.  Change
502 // the value type of I to reflect these changes if appropriate.  This method
503 // makes sure to do the following actions:
504 //
505 // 1. If a phi node merges two constants in, and has conflicting value coming
506 //    from different branches, or if the PHI node merges in an overdefined
507 //    value, then the PHI node becomes overdefined.
508 // 2. If a phi node merges only constants in, and they all agree on value, the
509 //    PHI node becomes a constant value equal to that.
510 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
511 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
512 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
513 // 6. If a conditional branch has a value that is constant, make the selected
514 //    destination executable
515 // 7. If a conditional branch has a value that is overdefined, make all
516 //    successors executable.
517 //
518 void SCCP::visitPHINode(PHINode &PN) {
519   InstVal &PNIV = getValueState(&PN);
520   if (PNIV.isOverdefined()) {
521     // There may be instructions using this PHI node that are not overdefined
522     // themselves.  If so, make sure that they know that the PHI node operand
523     // changed.
524     std::multimap<PHINode*, Instruction*>::iterator I, E;
525     tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
526     if (I != E) {
527       std::vector<Instruction*> Users;
528       Users.reserve(std::distance(I, E));
529       for (; I != E; ++I) Users.push_back(I->second);
530       while (!Users.empty()) {
531         visit(Users.back());
532         Users.pop_back();
533       }
534     }
535     return;  // Quick exit
536   }
537
538   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
539   // and slow us down a lot.  Just mark them overdefined.
540   if (PN.getNumIncomingValues() > 64) {
541     markOverdefined(PNIV, &PN);
542     return;
543   }
544
545   // Look at all of the executable operands of the PHI node.  If any of them
546   // are overdefined, the PHI becomes overdefined as well.  If they are all
547   // constant, and they agree with each other, the PHI becomes the identical
548   // constant.  If they are constant and don't agree, the PHI is overdefined.
549   // If there are no executable operands, the PHI remains undefined.
550   //
551   Constant *OperandVal = 0;
552   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
553     InstVal &IV = getValueState(PN.getIncomingValue(i));
554     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
555     
556     if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
557       if (IV.isOverdefined()) {   // PHI node becomes overdefined!
558         markOverdefined(PNIV, &PN);
559         return;
560       }
561
562       if (OperandVal == 0) {   // Grab the first value...
563         OperandVal = IV.getConstant();
564       } else {                // Another value is being merged in!
565         // There is already a reachable operand.  If we conflict with it,
566         // then the PHI node becomes overdefined.  If we agree with it, we
567         // can continue on.
568         
569         // Check to see if there are two different constants merging...
570         if (IV.getConstant() != OperandVal) {
571           // Yes there is.  This means the PHI node is not constant.
572           // You must be overdefined poor PHI.
573           //
574           markOverdefined(PNIV, &PN);    // The PHI node now becomes overdefined
575           return;    // I'm done analyzing you
576         }
577       }
578     }
579   }
580
581   // If we exited the loop, this means that the PHI node only has constant
582   // arguments that agree with each other(and OperandVal is the constant) or
583   // OperandVal is null because there are no defined incoming arguments.  If
584   // this is the case, the PHI remains undefined.
585   //
586   if (OperandVal)
587     markConstant(PNIV, &PN, OperandVal);      // Acquire operand value
588 }
589
590 void SCCP::visitTerminatorInst(TerminatorInst &TI) {
591   std::vector<bool> SuccFeasible;
592   getFeasibleSuccessors(TI, SuccFeasible);
593
594   BasicBlock *BB = TI.getParent();
595
596   // Mark all feasible successors executable...
597   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
598     if (SuccFeasible[i])
599       markEdgeExecutable(BB, TI.getSuccessor(i));
600 }
601
602 void SCCP::visitCastInst(CastInst &I) {
603   Value *V = I.getOperand(0);
604   InstVal &VState = getValueState(V);
605   if (VState.isOverdefined())          // Inherit overdefinedness of operand
606     markOverdefined(&I);
607   else if (VState.isConstant())        // Propagate constant value
608     markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
609 }
610
611 void SCCP::visitSelectInst(SelectInst &I) {
612   InstVal &CondValue = getValueState(I.getCondition());
613   if (CondValue.isOverdefined())
614     markOverdefined(&I);
615   else if (CondValue.isConstant()) {
616     if (CondValue.getConstant() == ConstantBool::True) {
617       InstVal &Val = getValueState(I.getTrueValue());
618       if (Val.isOverdefined())
619         markOverdefined(&I);
620       else if (Val.isConstant())
621         markConstant(&I, Val.getConstant());
622     } else if (CondValue.getConstant() == ConstantBool::False) {
623       InstVal &Val = getValueState(I.getFalseValue());
624       if (Val.isOverdefined())
625         markOverdefined(&I);
626       else if (Val.isConstant())
627         markConstant(&I, Val.getConstant());
628     } else
629       markOverdefined(&I);
630   }
631 }
632
633 // Handle BinaryOperators and Shift Instructions...
634 void SCCP::visitBinaryOperator(Instruction &I) {
635   InstVal &IV = ValueState[&I];
636   if (IV.isOverdefined()) return;
637
638   InstVal &V1State = getValueState(I.getOperand(0));
639   InstVal &V2State = getValueState(I.getOperand(1));
640
641   if (V1State.isOverdefined() || V2State.isOverdefined()) {
642     // If both operands are PHI nodes, it is possible that this instruction has
643     // a constant value, despite the fact that the PHI node doesn't.  Check for
644     // this condition now.
645     if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
646       if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
647         if (PN1->getParent() == PN2->getParent()) {
648           // Since the two PHI nodes are in the same basic block, they must have
649           // entries for the same predecessors.  Walk the predecessor list, and
650           // if all of the incoming values are constants, and the result of
651           // evaluating this expression with all incoming value pairs is the
652           // same, then this expression is a constant even though the PHI node
653           // is not a constant!
654           InstVal Result;
655           for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
656             InstVal &In1 = getValueState(PN1->getIncomingValue(i));
657             BasicBlock *InBlock = PN1->getIncomingBlock(i);
658             InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
659
660             if (In1.isOverdefined() || In2.isOverdefined()) {
661               Result.markOverdefined();
662               break;  // Cannot fold this operation over the PHI nodes!
663             } else if (In1.isConstant() && In2.isConstant()) {
664               Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
665                                               In2.getConstant());
666               if (Result.isUndefined())
667                 Result.markConstant(V);
668               else if (Result.isConstant() && Result.getConstant() != V) {
669                 Result.markOverdefined();
670                 break;
671               }
672             }
673           }
674
675           // If we found a constant value here, then we know the instruction is
676           // constant despite the fact that the PHI nodes are overdefined.
677           if (Result.isConstant()) {
678             markConstant(IV, &I, Result.getConstant());
679             // Remember that this instruction is virtually using the PHI node
680             // operands.
681             UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
682             UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
683             return;
684           } else if (Result.isUndefined()) {
685             return;
686           }
687
688           // Okay, this really is overdefined now.  Since we might have
689           // speculatively thought that this was not overdefined before, and
690           // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
691           // make sure to clean out any entries that we put there, for
692           // efficiency.
693           std::multimap<PHINode*, Instruction*>::iterator It, E;
694           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
695           while (It != E) {
696             if (It->second == &I) {
697               UsersOfOverdefinedPHIs.erase(It++);
698             } else
699               ++It;
700           }
701           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
702           while (It != E) {
703             if (It->second == &I) {
704               UsersOfOverdefinedPHIs.erase(It++);
705             } else
706               ++It;
707           }
708         }
709
710     markOverdefined(IV, &I);
711   } else if (V1State.isConstant() && V2State.isConstant()) {
712     markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
713                                            V2State.getConstant()));
714   }
715 }
716
717 // Handle getelementptr instructions... if all operands are constants then we
718 // can turn this into a getelementptr ConstantExpr.
719 //
720 void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
721   InstVal &IV = ValueState[&I];
722   if (IV.isOverdefined()) return;
723
724   std::vector<Constant*> Operands;
725   Operands.reserve(I.getNumOperands());
726
727   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
728     InstVal &State = getValueState(I.getOperand(i));
729     if (State.isUndefined())
730       return;  // Operands are not resolved yet...
731     else if (State.isOverdefined()) {
732       markOverdefined(IV, &I);
733       return;
734     }
735     assert(State.isConstant() && "Unknown state!");
736     Operands.push_back(State.getConstant());
737   }
738
739   Constant *Ptr = Operands[0];
740   Operands.erase(Operands.begin());  // Erase the pointer from idx list...
741
742   markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));  
743 }
744
745 /// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
746 /// return the constant value being addressed by the constant expression, or
747 /// null if something is funny.
748 ///
749 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
750   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
751     return 0;  // Do not allow stepping over the value!
752
753   // Loop over all of the operands, tracking down which value we are
754   // addressing...
755   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
756     if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
757       ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
758       if (CS == 0) return 0;
759       if (CU->getValue() >= CS->getValues().size()) return 0;
760       C = cast<Constant>(CS->getValues()[CU->getValue()]);
761     } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
762       ConstantArray *CA = dyn_cast<ConstantArray>(C);
763       if (CA == 0) return 0;
764       if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
765       C = cast<Constant>(CA->getValues()[CS->getValue()]);
766     } else
767       return 0;
768   return C;
769 }
770
771 // Handle load instructions.  If the operand is a constant pointer to a constant
772 // global, we can replace the load with the loaded constant value!
773 void SCCP::visitLoadInst(LoadInst &I) {
774   InstVal &IV = ValueState[&I];
775   if (IV.isOverdefined()) return;
776
777   InstVal &PtrVal = getValueState(I.getOperand(0));
778   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
779   if (PtrVal.isConstant() && !I.isVolatile()) {
780     Value *Ptr = PtrVal.getConstant();
781     if (isa<ConstantPointerNull>(Ptr)) {
782       // load null -> null
783       markConstant(IV, &I, Constant::getNullValue(I.getType()));
784       return;
785     }
786       
787     if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr))
788       Ptr = CPR->getValue();
789
790     // Transform load (constant global) into the value loaded.
791     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
792       if (GV->isConstant() && !GV->isExternal()) {
793         markConstant(IV, &I, GV->getInitializer());
794         return;
795       }
796
797     // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
798     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
799       if (CE->getOpcode() == Instruction::GetElementPtr)
800         if (ConstantPointerRef *G
801             = dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
802           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
803             if (GV->isConstant() && !GV->isExternal())
804               if (Constant *V =
805                   GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
806                 markConstant(IV, &I, V);
807                 return;
808               }
809   }
810
811   // Otherwise we cannot say for certain what value this load will produce.
812   // Bail out.
813   markOverdefined(IV, &I);
814 }
815
816 void SCCP::visitCallInst(CallInst &I) {
817   InstVal &IV = ValueState[&I];
818   if (IV.isOverdefined()) return;
819
820   Function *F = I.getCalledFunction();
821   if (F == 0 || !canConstantFoldCallTo(F)) {
822     markOverdefined(IV, &I);
823     return;
824   }
825
826   std::vector<Constant*> Operands;
827   Operands.reserve(I.getNumOperands()-1);
828
829   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
830     InstVal &State = getValueState(I.getOperand(i));
831     if (State.isUndefined())
832       return;  // Operands are not resolved yet...
833     else if (State.isOverdefined()) {
834       markOverdefined(IV, &I);
835       return;
836     }
837     assert(State.isConstant() && "Unknown state!");
838     Operands.push_back(State.getConstant());
839   }
840
841   if (Constant *C = ConstantFoldCall(F, Operands))
842     markConstant(IV, &I, C);
843   else
844     markOverdefined(IV, &I);
845 }