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