For PR950:
[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 #define DEBUG_TYPE "sccp"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/IPO.h"
27 #include "llvm/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/InstVisitor.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/ADT/hash_map"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include <algorithm>
39 #include <set>
40 using namespace llvm;
41
42 STATISTIC(NumInstRemoved, "Number of instructions removed");
43 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
44
45 STATISTIC(IPNumInstRemoved, "Number ofinstructions removed by IPSCCP");
46 STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
47 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
48 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
49
50 namespace {
51 /// LatticeVal class - This class represents the different lattice values that
52 /// an LLVM value may occupy.  It is a simple class with value semantics.
53 ///
54 class LatticeVal {
55   enum {
56     /// undefined - This LLVM Value has no known value yet.
57     undefined,
58     
59     /// constant - This LLVM Value has a specific constant value.
60     constant,
61
62     /// forcedconstant - This LLVM Value was thought to be undef until
63     /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
64     /// with another (different) constant, it goes to overdefined, instead of
65     /// asserting.
66     forcedconstant,
67     
68     /// overdefined - This instruction is not known to be constant, and we know
69     /// it has a value.
70     overdefined
71   } LatticeValue;    // The current lattice position
72   
73   Constant *ConstantVal; // If Constant value, the current value
74 public:
75   inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
76   
77   // markOverdefined - Return true if this is a new status to be in...
78   inline bool markOverdefined() {
79     if (LatticeValue != overdefined) {
80       LatticeValue = overdefined;
81       return true;
82     }
83     return false;
84   }
85
86   // markConstant - Return true if this is a new status for us.
87   inline bool markConstant(Constant *V) {
88     if (LatticeValue != constant) {
89       if (LatticeValue == undefined) {
90         LatticeValue = constant;
91         ConstantVal = V;
92       } else {
93         assert(LatticeValue == forcedconstant && 
94                "Cannot move from overdefined to constant!");
95         // Stay at forcedconstant if the constant is the same.
96         if (V == ConstantVal) return false;
97         
98         // Otherwise, we go to overdefined.  Assumptions made based on the
99         // forced value are possibly wrong.  Assuming this is another constant
100         // could expose a contradiction.
101         LatticeValue = overdefined;
102       }
103       return true;
104     } else {
105       assert(ConstantVal == V && "Marking constant with different value");
106     }
107     return false;
108   }
109
110   inline void markForcedConstant(Constant *V) {
111     assert(LatticeValue == undefined && "Can't force a defined value!");
112     LatticeValue = forcedconstant;
113     ConstantVal = V;
114   }
115   
116   inline bool isUndefined() const { return LatticeValue == undefined; }
117   inline bool isConstant() const {
118     return LatticeValue == constant || LatticeValue == forcedconstant;
119   }
120   inline bool isOverdefined() const { return LatticeValue == overdefined; }
121
122   inline Constant *getConstant() const {
123     assert(isConstant() && "Cannot get the constant of a non-constant!");
124     return ConstantVal;
125   }
126 };
127
128 } // end anonymous namespace
129
130
131 //===----------------------------------------------------------------------===//
132 //
133 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
134 /// Constant Propagation.
135 ///
136 class SCCPSolver : public InstVisitor<SCCPSolver> {
137   std::set<BasicBlock*>     BBExecutable;// The basic blocks that are executable
138   hash_map<Value*, LatticeVal> ValueState;  // The state each value is in...
139
140   /// GlobalValue - If we are tracking any values for the contents of a global
141   /// variable, we keep a mapping from the constant accessor to the element of
142   /// the global, to the currently known value.  If the value becomes
143   /// overdefined, it's entry is simply removed from this map.
144   hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
145
146   /// TrackedFunctionRetVals - If we are tracking arguments into and the return
147   /// value out of a function, it will have an entry in this map, indicating
148   /// what the known return value for the function is.
149   hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
150
151   // The reason for two worklists is that overdefined is the lowest state
152   // on the lattice, and moving things to overdefined as fast as possible
153   // makes SCCP converge much faster.
154   // By having a separate worklist, we accomplish this because everything
155   // possibly overdefined will become overdefined at the soonest possible
156   // point.
157   std::vector<Value*> OverdefinedInstWorkList;
158   std::vector<Value*> InstWorkList;
159
160
161   std::vector<BasicBlock*>  BBWorkList;  // The BasicBlock work list
162
163   /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
164   /// overdefined, despite the fact that the PHI node is overdefined.
165   std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
166
167   /// KnownFeasibleEdges - Entries in this set are edges which have already had
168   /// PHI nodes retriggered.
169   typedef std::pair<BasicBlock*,BasicBlock*> Edge;
170   std::set<Edge> KnownFeasibleEdges;
171 public:
172
173   /// MarkBlockExecutable - This method can be used by clients to mark all of
174   /// the blocks that are known to be intrinsically live in the processed unit.
175   void MarkBlockExecutable(BasicBlock *BB) {
176     DOUT << "Marking Block Executable: " << BB->getName() << "\n";
177     BBExecutable.insert(BB);   // Basic block is executable!
178     BBWorkList.push_back(BB);  // Add the block to the work list!
179   }
180
181   /// TrackValueOfGlobalVariable - Clients can use this method to
182   /// inform the SCCPSolver that it should track loads and stores to the
183   /// specified global variable if it can.  This is only legal to call if
184   /// performing Interprocedural SCCP.
185   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
186     const Type *ElTy = GV->getType()->getElementType();
187     if (ElTy->isFirstClassType()) {
188       LatticeVal &IV = TrackedGlobals[GV];
189       if (!isa<UndefValue>(GV->getInitializer()))
190         IV.markConstant(GV->getInitializer());
191     }
192   }
193
194   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
195   /// and out of the specified function (which cannot have its address taken),
196   /// this method must be called.
197   void AddTrackedFunction(Function *F) {
198     assert(F->hasInternalLinkage() && "Can only track internal functions!");
199     // Add an entry, F -> undef.
200     TrackedFunctionRetVals[F];
201   }
202
203   /// Solve - Solve for constants and executable blocks.
204   ///
205   void Solve();
206
207   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
208   /// that branches on undef values cannot reach any of their successors.
209   /// However, this is not a safe assumption.  After we solve dataflow, this
210   /// method should be use to handle this.  If this returns true, the solver
211   /// should be rerun.
212   bool ResolvedUndefsIn(Function &F);
213
214   /// getExecutableBlocks - Once we have solved for constants, return the set of
215   /// blocks that is known to be executable.
216   std::set<BasicBlock*> &getExecutableBlocks() {
217     return BBExecutable;
218   }
219
220   /// getValueMapping - Once we have solved for constants, return the mapping of
221   /// LLVM values to LatticeVals.
222   hash_map<Value*, LatticeVal> &getValueMapping() {
223     return ValueState;
224   }
225
226   /// getTrackedFunctionRetVals - Get the inferred return value map.
227   ///
228   const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
229     return TrackedFunctionRetVals;
230   }
231
232   /// getTrackedGlobals - Get and return the set of inferred initializers for
233   /// global variables.
234   const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
235     return TrackedGlobals;
236   }
237
238
239 private:
240   // markConstant - Make a value be marked as "constant".  If the value
241   // is not already a constant, add it to the instruction work list so that
242   // the users of the instruction are updated later.
243   //
244   inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
245     if (IV.markConstant(C)) {
246       DOUT << "markConstant: " << *C << ": " << *V;
247       InstWorkList.push_back(V);
248     }
249   }
250   
251   inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
252     IV.markForcedConstant(C);
253     DOUT << "markForcedConstant: " << *C << ": " << *V;
254     InstWorkList.push_back(V);
255   }
256   
257   inline void markConstant(Value *V, Constant *C) {
258     markConstant(ValueState[V], V, C);
259   }
260
261   // markOverdefined - Make a value be marked as "overdefined". If the
262   // value is not already overdefined, add it to the overdefined instruction
263   // work list so that the users of the instruction are updated later.
264
265   inline void markOverdefined(LatticeVal &IV, Value *V) {
266     if (IV.markOverdefined()) {
267       DEBUG(DOUT << "markOverdefined: ";
268             if (Function *F = dyn_cast<Function>(V))
269               DOUT << "Function '" << F->getName() << "'\n";
270             else
271               DOUT << *V);
272       // Only instructions go on the work list
273       OverdefinedInstWorkList.push_back(V);
274     }
275   }
276   inline void markOverdefined(Value *V) {
277     markOverdefined(ValueState[V], V);
278   }
279
280   inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
281     if (IV.isOverdefined() || MergeWithV.isUndefined())
282       return;  // Noop.
283     if (MergeWithV.isOverdefined())
284       markOverdefined(IV, V);
285     else if (IV.isUndefined())
286       markConstant(IV, V, MergeWithV.getConstant());
287     else if (IV.getConstant() != MergeWithV.getConstant())
288       markOverdefined(IV, V);
289   }
290   
291   inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
292     return mergeInValue(ValueState[V], V, MergeWithV);
293   }
294
295
296   // getValueState - Return the LatticeVal object that corresponds to the value.
297   // This function is necessary because not all values should start out in the
298   // underdefined state... Argument's should be overdefined, and
299   // constants should be marked as constants.  If a value is not known to be an
300   // Instruction object, then use this accessor to get its value from the map.
301   //
302   inline LatticeVal &getValueState(Value *V) {
303     hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
304     if (I != ValueState.end()) return I->second;  // Common case, in the map
305
306     if (Constant *C = dyn_cast<Constant>(V)) {
307       if (isa<UndefValue>(V)) {
308         // Nothing to do, remain undefined.
309       } else {
310         ValueState[C].markConstant(C);          // Constants are constant
311       }
312     }
313     // All others are underdefined by default...
314     return ValueState[V];
315   }
316
317   // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
318   // work list if it is not already executable...
319   //
320   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
321     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
322       return;  // This edge is already known to be executable!
323
324     if (BBExecutable.count(Dest)) {
325       DOUT << "Marking Edge Executable: " << Source->getName()
326            << " -> " << Dest->getName() << "\n";
327
328       // The destination is already executable, but we just made an edge
329       // feasible that wasn't before.  Revisit the PHI nodes in the block
330       // because they have potentially new operands.
331       for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
332         visitPHINode(*cast<PHINode>(I));
333
334     } else {
335       MarkBlockExecutable(Dest);
336     }
337   }
338
339   // getFeasibleSuccessors - Return a vector of booleans to indicate which
340   // successors are reachable from a given terminator instruction.
341   //
342   void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
343
344   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
345   // block to the 'To' basic block is currently feasible...
346   //
347   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
348
349   // OperandChangedState - This method is invoked on all of the users of an
350   // instruction that was just changed state somehow....  Based on this
351   // information, we need to update the specified user of this instruction.
352   //
353   void OperandChangedState(User *U) {
354     // Only instructions use other variable values!
355     Instruction &I = cast<Instruction>(*U);
356     if (BBExecutable.count(I.getParent()))   // Inst is executable?
357       visit(I);
358   }
359
360 private:
361   friend class InstVisitor<SCCPSolver>;
362
363   // visit implementations - Something changed in this instruction... Either an
364   // operand made a transition, or the instruction is newly executable.  Change
365   // the value type of I to reflect these changes if appropriate.
366   //
367   void visitPHINode(PHINode &I);
368
369   // Terminators
370   void visitReturnInst(ReturnInst &I);
371   void visitTerminatorInst(TerminatorInst &TI);
372
373   void visitCastInst(CastInst &I);
374   void visitSelectInst(SelectInst &I);
375   void visitBinaryOperator(Instruction &I);
376   void visitCmpInst(CmpInst &I);
377   void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
378   void visitExtractElementInst(ExtractElementInst &I);
379   void visitInsertElementInst(InsertElementInst &I);
380   void visitShuffleVectorInst(ShuffleVectorInst &I);
381
382   // Instructions that cannot be folded away...
383   void visitStoreInst     (Instruction &I);
384   void visitLoadInst      (LoadInst &I);
385   void visitGetElementPtrInst(GetElementPtrInst &I);
386   void visitCallInst      (CallInst &I) { visitCallSite(CallSite::get(&I)); }
387   void visitInvokeInst    (InvokeInst &II) {
388     visitCallSite(CallSite::get(&II));
389     visitTerminatorInst(II);
390   }
391   void visitCallSite      (CallSite CS);
392   void visitUnwindInst    (TerminatorInst &I) { /*returns void*/ }
393   void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
394   void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
395   void visitVANextInst    (Instruction &I) { markOverdefined(&I); }
396   void visitVAArgInst     (Instruction &I) { markOverdefined(&I); }
397   void visitFreeInst      (Instruction &I) { /*returns void*/ }
398
399   void visitInstruction(Instruction &I) {
400     // If a new instruction is added to LLVM that we don't handle...
401     cerr << "SCCP: Don't know how to handle: " << I;
402     markOverdefined(&I);   // Just in case
403   }
404 };
405
406 // getFeasibleSuccessors - Return a vector of booleans to indicate which
407 // successors are reachable from a given terminator instruction.
408 //
409 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
410                                        std::vector<bool> &Succs) {
411   Succs.resize(TI.getNumSuccessors());
412   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
413     if (BI->isUnconditional()) {
414       Succs[0] = true;
415     } else {
416       LatticeVal &BCValue = getValueState(BI->getCondition());
417       if (BCValue.isOverdefined() ||
418           (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
419         // Overdefined condition variables, and branches on unfoldable constant
420         // conditions, mean the branch could go either way.
421         Succs[0] = Succs[1] = true;
422       } else if (BCValue.isConstant()) {
423         // Constant condition variables mean the branch can only go a single way
424         Succs[BCValue.getConstant() == ConstantBool::getFalse()] = true;
425       }
426     }
427   } else if (isa<InvokeInst>(&TI)) {
428     // Invoke instructions successors are always executable.
429     Succs[0] = Succs[1] = true;
430   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
431     LatticeVal &SCValue = getValueState(SI->getCondition());
432     if (SCValue.isOverdefined() ||   // Overdefined condition?
433         (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
434       // All destinations are executable!
435       Succs.assign(TI.getNumSuccessors(), true);
436     } else if (SCValue.isConstant()) {
437       Constant *CPV = SCValue.getConstant();
438       // Make sure to skip the "default value" which isn't a value
439       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
440         if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
441           Succs[i] = true;
442           return;
443         }
444       }
445
446       // Constant value not equal to any of the branches... must execute
447       // default branch then...
448       Succs[0] = true;
449     }
450   } else {
451     cerr << "SCCP: Don't know how to handle: " << TI;
452     Succs.assign(TI.getNumSuccessors(), true);
453   }
454 }
455
456
457 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
458 // block to the 'To' basic block is currently feasible...
459 //
460 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
461   assert(BBExecutable.count(To) && "Dest should always be alive!");
462
463   // Make sure the source basic block is executable!!
464   if (!BBExecutable.count(From)) return false;
465
466   // Check to make sure this edge itself is actually feasible now...
467   TerminatorInst *TI = From->getTerminator();
468   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
469     if (BI->isUnconditional())
470       return true;
471     else {
472       LatticeVal &BCValue = getValueState(BI->getCondition());
473       if (BCValue.isOverdefined()) {
474         // Overdefined condition variables mean the branch could go either way.
475         return true;
476       } else if (BCValue.isConstant()) {
477         // Not branching on an evaluatable constant?
478         if (!isa<ConstantBool>(BCValue.getConstant())) return true;
479
480         // Constant condition variables mean the branch can only go a single way
481         return BI->getSuccessor(BCValue.getConstant() ==
482                                        ConstantBool::getFalse()) == To;
483       }
484       return false;
485     }
486   } else if (isa<InvokeInst>(TI)) {
487     // Invoke instructions successors are always executable.
488     return true;
489   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
490     LatticeVal &SCValue = getValueState(SI->getCondition());
491     if (SCValue.isOverdefined()) {  // Overdefined condition?
492       // All destinations are executable!
493       return true;
494     } else if (SCValue.isConstant()) {
495       Constant *CPV = SCValue.getConstant();
496       if (!isa<ConstantInt>(CPV))
497         return true;  // not a foldable constant?
498
499       // Make sure to skip the "default value" which isn't a value
500       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
501         if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
502           return SI->getSuccessor(i) == To;
503
504       // Constant value not equal to any of the branches... must execute
505       // default branch then...
506       return SI->getDefaultDest() == To;
507     }
508     return false;
509   } else {
510     cerr << "Unknown terminator instruction: " << *TI;
511     abort();
512   }
513 }
514
515 // visit Implementations - Something changed in this instruction... Either an
516 // operand made a transition, or the instruction is newly executable.  Change
517 // the value type of I to reflect these changes if appropriate.  This method
518 // makes sure to do the following actions:
519 //
520 // 1. If a phi node merges two constants in, and has conflicting value coming
521 //    from different branches, or if the PHI node merges in an overdefined
522 //    value, then the PHI node becomes overdefined.
523 // 2. If a phi node merges only constants in, and they all agree on value, the
524 //    PHI node becomes a constant value equal to that.
525 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
526 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
527 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
528 // 6. If a conditional branch has a value that is constant, make the selected
529 //    destination executable
530 // 7. If a conditional branch has a value that is overdefined, make all
531 //    successors executable.
532 //
533 void SCCPSolver::visitPHINode(PHINode &PN) {
534   LatticeVal &PNIV = getValueState(&PN);
535   if (PNIV.isOverdefined()) {
536     // There may be instructions using this PHI node that are not overdefined
537     // themselves.  If so, make sure that they know that the PHI node operand
538     // changed.
539     std::multimap<PHINode*, Instruction*>::iterator I, E;
540     tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
541     if (I != E) {
542       std::vector<Instruction*> Users;
543       Users.reserve(std::distance(I, E));
544       for (; I != E; ++I) Users.push_back(I->second);
545       while (!Users.empty()) {
546         visit(Users.back());
547         Users.pop_back();
548       }
549     }
550     return;  // Quick exit
551   }
552
553   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
554   // and slow us down a lot.  Just mark them overdefined.
555   if (PN.getNumIncomingValues() > 64) {
556     markOverdefined(PNIV, &PN);
557     return;
558   }
559
560   // Look at all of the executable operands of the PHI node.  If any of them
561   // are overdefined, the PHI becomes overdefined as well.  If they are all
562   // constant, and they agree with each other, the PHI becomes the identical
563   // constant.  If they are constant and don't agree, the PHI is overdefined.
564   // If there are no executable operands, the PHI remains undefined.
565   //
566   Constant *OperandVal = 0;
567   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
568     LatticeVal &IV = getValueState(PN.getIncomingValue(i));
569     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
570
571     if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
572       if (IV.isOverdefined()) {   // PHI node becomes overdefined!
573         markOverdefined(PNIV, &PN);
574         return;
575       }
576
577       if (OperandVal == 0) {   // Grab the first value...
578         OperandVal = IV.getConstant();
579       } else {                // Another value is being merged in!
580         // There is already a reachable operand.  If we conflict with it,
581         // then the PHI node becomes overdefined.  If we agree with it, we
582         // can continue on.
583
584         // Check to see if there are two different constants merging...
585         if (IV.getConstant() != OperandVal) {
586           // Yes there is.  This means the PHI node is not constant.
587           // You must be overdefined poor PHI.
588           //
589           markOverdefined(PNIV, &PN);    // The PHI node now becomes overdefined
590           return;    // I'm done analyzing you
591         }
592       }
593     }
594   }
595
596   // If we exited the loop, this means that the PHI node only has constant
597   // arguments that agree with each other(and OperandVal is the constant) or
598   // OperandVal is null because there are no defined incoming arguments.  If
599   // this is the case, the PHI remains undefined.
600   //
601   if (OperandVal)
602     markConstant(PNIV, &PN, OperandVal);      // Acquire operand value
603 }
604
605 void SCCPSolver::visitReturnInst(ReturnInst &I) {
606   if (I.getNumOperands() == 0) return;  // Ret void
607
608   // If we are tracking the return value of this function, merge it in.
609   Function *F = I.getParent()->getParent();
610   if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
611     hash_map<Function*, LatticeVal>::iterator TFRVI =
612       TrackedFunctionRetVals.find(F);
613     if (TFRVI != TrackedFunctionRetVals.end() &&
614         !TFRVI->second.isOverdefined()) {
615       LatticeVal &IV = getValueState(I.getOperand(0));
616       mergeInValue(TFRVI->second, F, IV);
617     }
618   }
619 }
620
621
622 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
623   std::vector<bool> SuccFeasible;
624   getFeasibleSuccessors(TI, SuccFeasible);
625
626   BasicBlock *BB = TI.getParent();
627
628   // Mark all feasible successors executable...
629   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
630     if (SuccFeasible[i])
631       markEdgeExecutable(BB, TI.getSuccessor(i));
632 }
633
634 void SCCPSolver::visitCastInst(CastInst &I) {
635   Value *V = I.getOperand(0);
636   LatticeVal &VState = getValueState(V);
637   if (VState.isOverdefined())          // Inherit overdefinedness of operand
638     markOverdefined(&I);
639   else if (VState.isConstant())        // Propagate constant value
640     markConstant(&I, ConstantExpr::getCast(I.getOpcode(), 
641                                            VState.getConstant(), I.getType()));
642 }
643
644 void SCCPSolver::visitSelectInst(SelectInst &I) {
645   LatticeVal &CondValue = getValueState(I.getCondition());
646   if (CondValue.isUndefined())
647     return;
648   if (CondValue.isConstant()) {
649     if (ConstantBool *CondCB = dyn_cast<ConstantBool>(CondValue.getConstant())){
650       mergeInValue(&I, getValueState(CondCB->getValue() ? I.getTrueValue()
651                                                         : I.getFalseValue()));
652       return;
653     }
654   }
655   
656   // Otherwise, the condition is overdefined or a constant we can't evaluate.
657   // See if we can produce something better than overdefined based on the T/F
658   // value.
659   LatticeVal &TVal = getValueState(I.getTrueValue());
660   LatticeVal &FVal = getValueState(I.getFalseValue());
661   
662   // select ?, C, C -> C.
663   if (TVal.isConstant() && FVal.isConstant() && 
664       TVal.getConstant() == FVal.getConstant()) {
665     markConstant(&I, FVal.getConstant());
666     return;
667   }
668
669   if (TVal.isUndefined()) {  // select ?, undef, X -> X.
670     mergeInValue(&I, FVal);
671   } else if (FVal.isUndefined()) {  // select ?, X, undef -> X.
672     mergeInValue(&I, TVal);
673   } else {
674     markOverdefined(&I);
675   }
676 }
677
678 // Handle BinaryOperators and Shift Instructions...
679 void SCCPSolver::visitBinaryOperator(Instruction &I) {
680   LatticeVal &IV = ValueState[&I];
681   if (IV.isOverdefined()) return;
682
683   LatticeVal &V1State = getValueState(I.getOperand(0));
684   LatticeVal &V2State = getValueState(I.getOperand(1));
685
686   if (V1State.isOverdefined() || V2State.isOverdefined()) {
687     // If this is an AND or OR with 0 or -1, it doesn't matter that the other
688     // operand is overdefined.
689     if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
690       LatticeVal *NonOverdefVal = 0;
691       if (!V1State.isOverdefined()) {
692         NonOverdefVal = &V1State;
693       } else if (!V2State.isOverdefined()) {
694         NonOverdefVal = &V2State;
695       }
696
697       if (NonOverdefVal) {
698         if (NonOverdefVal->isUndefined()) {
699           // Could annihilate value.
700           if (I.getOpcode() == Instruction::And)
701             markConstant(IV, &I, Constant::getNullValue(I.getType()));
702           else
703             markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
704           return;
705         } else {
706           if (I.getOpcode() == Instruction::And) {
707             if (NonOverdefVal->getConstant()->isNullValue()) {
708               markConstant(IV, &I, NonOverdefVal->getConstant());
709               return;      // X or 0 = -1
710             }
711           } else {
712             if (ConstantIntegral *CI =
713                      dyn_cast<ConstantIntegral>(NonOverdefVal->getConstant()))
714               if (CI->isAllOnesValue()) {
715                 markConstant(IV, &I, NonOverdefVal->getConstant());
716                 return;    // X or -1 = -1
717               }
718           }
719         }
720       }
721     }
722
723
724     // If both operands are PHI nodes, it is possible that this instruction has
725     // a constant value, despite the fact that the PHI node doesn't.  Check for
726     // this condition now.
727     if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
728       if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
729         if (PN1->getParent() == PN2->getParent()) {
730           // Since the two PHI nodes are in the same basic block, they must have
731           // entries for the same predecessors.  Walk the predecessor list, and
732           // if all of the incoming values are constants, and the result of
733           // evaluating this expression with all incoming value pairs is the
734           // same, then this expression is a constant even though the PHI node
735           // is not a constant!
736           LatticeVal Result;
737           for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
738             LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
739             BasicBlock *InBlock = PN1->getIncomingBlock(i);
740             LatticeVal &In2 =
741               getValueState(PN2->getIncomingValueForBlock(InBlock));
742
743             if (In1.isOverdefined() || In2.isOverdefined()) {
744               Result.markOverdefined();
745               break;  // Cannot fold this operation over the PHI nodes!
746             } else if (In1.isConstant() && In2.isConstant()) {
747               Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
748                                               In2.getConstant());
749               if (Result.isUndefined())
750                 Result.markConstant(V);
751               else if (Result.isConstant() && Result.getConstant() != V) {
752                 Result.markOverdefined();
753                 break;
754               }
755             }
756           }
757
758           // If we found a constant value here, then we know the instruction is
759           // constant despite the fact that the PHI nodes are overdefined.
760           if (Result.isConstant()) {
761             markConstant(IV, &I, Result.getConstant());
762             // Remember that this instruction is virtually using the PHI node
763             // operands.
764             UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
765             UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
766             return;
767           } else if (Result.isUndefined()) {
768             return;
769           }
770
771           // Okay, this really is overdefined now.  Since we might have
772           // speculatively thought that this was not overdefined before, and
773           // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
774           // make sure to clean out any entries that we put there, for
775           // efficiency.
776           std::multimap<PHINode*, Instruction*>::iterator It, E;
777           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
778           while (It != E) {
779             if (It->second == &I) {
780               UsersOfOverdefinedPHIs.erase(It++);
781             } else
782               ++It;
783           }
784           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
785           while (It != E) {
786             if (It->second == &I) {
787               UsersOfOverdefinedPHIs.erase(It++);
788             } else
789               ++It;
790           }
791         }
792
793     markOverdefined(IV, &I);
794   } else if (V1State.isConstant() && V2State.isConstant()) {
795     markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
796                                            V2State.getConstant()));
797   }
798 }
799
800 // Handle ICmpInst instruction...
801 void SCCPSolver::visitCmpInst(CmpInst &I) {
802   LatticeVal &IV = ValueState[&I];
803   if (IV.isOverdefined()) return;
804
805   LatticeVal &V1State = getValueState(I.getOperand(0));
806   LatticeVal &V2State = getValueState(I.getOperand(1));
807
808   if (V1State.isOverdefined() || V2State.isOverdefined()) {
809     // If both operands are PHI nodes, it is possible that this instruction has
810     // a constant value, despite the fact that the PHI node doesn't.  Check for
811     // this condition now.
812     if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
813       if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
814         if (PN1->getParent() == PN2->getParent()) {
815           // Since the two PHI nodes are in the same basic block, they must have
816           // entries for the same predecessors.  Walk the predecessor list, and
817           // if all of the incoming values are constants, and the result of
818           // evaluating this expression with all incoming value pairs is the
819           // same, then this expression is a constant even though the PHI node
820           // is not a constant!
821           LatticeVal Result;
822           for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
823             LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
824             BasicBlock *InBlock = PN1->getIncomingBlock(i);
825             LatticeVal &In2 =
826               getValueState(PN2->getIncomingValueForBlock(InBlock));
827
828             if (In1.isOverdefined() || In2.isOverdefined()) {
829               Result.markOverdefined();
830               break;  // Cannot fold this operation over the PHI nodes!
831             } else if (In1.isConstant() && In2.isConstant()) {
832               Constant *V = ConstantExpr::getCompare(I.getPredicate(), 
833                                                      In1.getConstant(), 
834                                                      In2.getConstant());
835               if (Result.isUndefined())
836                 Result.markConstant(V);
837               else if (Result.isConstant() && Result.getConstant() != V) {
838                 Result.markOverdefined();
839                 break;
840               }
841             }
842           }
843
844           // If we found a constant value here, then we know the instruction is
845           // constant despite the fact that the PHI nodes are overdefined.
846           if (Result.isConstant()) {
847             markConstant(IV, &I, Result.getConstant());
848             // Remember that this instruction is virtually using the PHI node
849             // operands.
850             UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
851             UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
852             return;
853           } else if (Result.isUndefined()) {
854             return;
855           }
856
857           // Okay, this really is overdefined now.  Since we might have
858           // speculatively thought that this was not overdefined before, and
859           // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
860           // make sure to clean out any entries that we put there, for
861           // efficiency.
862           std::multimap<PHINode*, Instruction*>::iterator It, E;
863           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
864           while (It != E) {
865             if (It->second == &I) {
866               UsersOfOverdefinedPHIs.erase(It++);
867             } else
868               ++It;
869           }
870           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
871           while (It != E) {
872             if (It->second == &I) {
873               UsersOfOverdefinedPHIs.erase(It++);
874             } else
875               ++It;
876           }
877         }
878
879     markOverdefined(IV, &I);
880   } else if (V1State.isConstant() && V2State.isConstant()) {
881     markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(), 
882                                                   V1State.getConstant(), 
883                                                   V2State.getConstant()));
884   }
885 }
886
887 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
888   // FIXME : SCCP does not handle vectors properly.
889   markOverdefined(&I);
890   return;
891
892 #if 0
893   LatticeVal &ValState = getValueState(I.getOperand(0));
894   LatticeVal &IdxState = getValueState(I.getOperand(1));
895
896   if (ValState.isOverdefined() || IdxState.isOverdefined())
897     markOverdefined(&I);
898   else if(ValState.isConstant() && IdxState.isConstant())
899     markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
900                                                      IdxState.getConstant()));
901 #endif
902 }
903
904 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
905   // FIXME : SCCP does not handle vectors properly.
906   markOverdefined(&I);
907   return;
908 #if 0
909   LatticeVal &ValState = getValueState(I.getOperand(0));
910   LatticeVal &EltState = getValueState(I.getOperand(1));
911   LatticeVal &IdxState = getValueState(I.getOperand(2));
912
913   if (ValState.isOverdefined() || EltState.isOverdefined() ||
914       IdxState.isOverdefined())
915     markOverdefined(&I);
916   else if(ValState.isConstant() && EltState.isConstant() &&
917           IdxState.isConstant())
918     markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
919                                                     EltState.getConstant(),
920                                                     IdxState.getConstant()));
921   else if (ValState.isUndefined() && EltState.isConstant() &&
922            IdxState.isConstant()) 
923     markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
924                                                     EltState.getConstant(),
925                                                     IdxState.getConstant()));
926 #endif
927 }
928
929 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
930   // FIXME : SCCP does not handle vectors properly.
931   markOverdefined(&I);
932   return;
933 #if 0
934   LatticeVal &V1State   = getValueState(I.getOperand(0));
935   LatticeVal &V2State   = getValueState(I.getOperand(1));
936   LatticeVal &MaskState = getValueState(I.getOperand(2));
937
938   if (MaskState.isUndefined() ||
939       (V1State.isUndefined() && V2State.isUndefined()))
940     return;  // Undefined output if mask or both inputs undefined.
941   
942   if (V1State.isOverdefined() || V2State.isOverdefined() ||
943       MaskState.isOverdefined()) {
944     markOverdefined(&I);
945   } else {
946     // A mix of constant/undef inputs.
947     Constant *V1 = V1State.isConstant() ? 
948         V1State.getConstant() : UndefValue::get(I.getType());
949     Constant *V2 = V2State.isConstant() ? 
950         V2State.getConstant() : UndefValue::get(I.getType());
951     Constant *Mask = MaskState.isConstant() ? 
952       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
953     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
954   }
955 #endif
956 }
957
958 // Handle getelementptr instructions... if all operands are constants then we
959 // can turn this into a getelementptr ConstantExpr.
960 //
961 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
962   LatticeVal &IV = ValueState[&I];
963   if (IV.isOverdefined()) return;
964
965   std::vector<Constant*> Operands;
966   Operands.reserve(I.getNumOperands());
967
968   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
969     LatticeVal &State = getValueState(I.getOperand(i));
970     if (State.isUndefined())
971       return;  // Operands are not resolved yet...
972     else if (State.isOverdefined()) {
973       markOverdefined(IV, &I);
974       return;
975     }
976     assert(State.isConstant() && "Unknown state!");
977     Operands.push_back(State.getConstant());
978   }
979
980   Constant *Ptr = Operands[0];
981   Operands.erase(Operands.begin());  // Erase the pointer from idx list...
982
983   markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
984 }
985
986 void SCCPSolver::visitStoreInst(Instruction &SI) {
987   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
988     return;
989   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
990   hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
991   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
992
993   // Get the value we are storing into the global.
994   LatticeVal &PtrVal = getValueState(SI.getOperand(0));
995
996   mergeInValue(I->second, GV, PtrVal);
997   if (I->second.isOverdefined())
998     TrackedGlobals.erase(I);      // No need to keep tracking this!
999 }
1000
1001
1002 // Handle load instructions.  If the operand is a constant pointer to a constant
1003 // global, we can replace the load with the loaded constant value!
1004 void SCCPSolver::visitLoadInst(LoadInst &I) {
1005   LatticeVal &IV = ValueState[&I];
1006   if (IV.isOverdefined()) return;
1007
1008   LatticeVal &PtrVal = getValueState(I.getOperand(0));
1009   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
1010   if (PtrVal.isConstant() && !I.isVolatile()) {
1011     Value *Ptr = PtrVal.getConstant();
1012     if (isa<ConstantPointerNull>(Ptr)) {
1013       // load null -> null
1014       markConstant(IV, &I, Constant::getNullValue(I.getType()));
1015       return;
1016     }
1017
1018     // Transform load (constant global) into the value loaded.
1019     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1020       if (GV->isConstant()) {
1021         if (!GV->isExternal()) {
1022           markConstant(IV, &I, GV->getInitializer());
1023           return;
1024         }
1025       } else if (!TrackedGlobals.empty()) {
1026         // If we are tracking this global, merge in the known value for it.
1027         hash_map<GlobalVariable*, LatticeVal>::iterator It =
1028           TrackedGlobals.find(GV);
1029         if (It != TrackedGlobals.end()) {
1030           mergeInValue(IV, &I, It->second);
1031           return;
1032         }
1033       }
1034     }
1035
1036     // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1037     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1038       if (CE->getOpcode() == Instruction::GetElementPtr)
1039     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1040       if (GV->isConstant() && !GV->isExternal())
1041         if (Constant *V =
1042              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1043           markConstant(IV, &I, V);
1044           return;
1045         }
1046   }
1047
1048   // Otherwise we cannot say for certain what value this load will produce.
1049   // Bail out.
1050   markOverdefined(IV, &I);
1051 }
1052
1053 void SCCPSolver::visitCallSite(CallSite CS) {
1054   Function *F = CS.getCalledFunction();
1055
1056   // If we are tracking this function, we must make sure to bind arguments as
1057   // appropriate.
1058   hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
1059   if (F && F->hasInternalLinkage())
1060     TFRVI = TrackedFunctionRetVals.find(F);
1061
1062   if (TFRVI != TrackedFunctionRetVals.end()) {
1063     // If this is the first call to the function hit, mark its entry block
1064     // executable.
1065     if (!BBExecutable.count(F->begin()))
1066       MarkBlockExecutable(F->begin());
1067
1068     CallSite::arg_iterator CAI = CS.arg_begin();
1069     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1070          AI != E; ++AI, ++CAI) {
1071       LatticeVal &IV = ValueState[AI];
1072       if (!IV.isOverdefined())
1073         mergeInValue(IV, AI, getValueState(*CAI));
1074     }
1075   }
1076   Instruction *I = CS.getInstruction();
1077   if (I->getType() == Type::VoidTy) return;
1078
1079   LatticeVal &IV = ValueState[I];
1080   if (IV.isOverdefined()) return;
1081
1082   // Propagate the return value of the function to the value of the instruction.
1083   if (TFRVI != TrackedFunctionRetVals.end()) {
1084     mergeInValue(IV, I, TFRVI->second);
1085     return;
1086   }
1087
1088   if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
1089     markOverdefined(IV, I);
1090     return;
1091   }
1092
1093   std::vector<Constant*> Operands;
1094   Operands.reserve(I->getNumOperands()-1);
1095
1096   for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1097        AI != E; ++AI) {
1098     LatticeVal &State = getValueState(*AI);
1099     if (State.isUndefined())
1100       return;  // Operands are not resolved yet...
1101     else if (State.isOverdefined()) {
1102       markOverdefined(IV, I);
1103       return;
1104     }
1105     assert(State.isConstant() && "Unknown state!");
1106     Operands.push_back(State.getConstant());
1107   }
1108
1109   if (Constant *C = ConstantFoldCall(F, Operands))
1110     markConstant(IV, I, C);
1111   else
1112     markOverdefined(IV, I);
1113 }
1114
1115
1116 void SCCPSolver::Solve() {
1117   // Process the work lists until they are empty!
1118   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1119          !OverdefinedInstWorkList.empty()) {
1120     // Process the instruction work list...
1121     while (!OverdefinedInstWorkList.empty()) {
1122       Value *I = OverdefinedInstWorkList.back();
1123       OverdefinedInstWorkList.pop_back();
1124
1125       DOUT << "\nPopped off OI-WL: " << *I;
1126
1127       // "I" got into the work list because it either made the transition from
1128       // bottom to constant
1129       //
1130       // Anything on this worklist that is overdefined need not be visited
1131       // since all of its users will have already been marked as overdefined
1132       // Update all of the users of this instruction's value...
1133       //
1134       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1135            UI != E; ++UI)
1136         OperandChangedState(*UI);
1137     }
1138     // Process the instruction work list...
1139     while (!InstWorkList.empty()) {
1140       Value *I = InstWorkList.back();
1141       InstWorkList.pop_back();
1142
1143       DOUT << "\nPopped off I-WL: " << *I;
1144
1145       // "I" got into the work list because it either made the transition from
1146       // bottom to constant
1147       //
1148       // Anything on this worklist that is overdefined need not be visited
1149       // since all of its users will have already been marked as overdefined.
1150       // Update all of the users of this instruction's value...
1151       //
1152       if (!getValueState(I).isOverdefined())
1153         for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1154              UI != E; ++UI)
1155           OperandChangedState(*UI);
1156     }
1157
1158     // Process the basic block work list...
1159     while (!BBWorkList.empty()) {
1160       BasicBlock *BB = BBWorkList.back();
1161       BBWorkList.pop_back();
1162
1163       DOUT << "\nPopped off BBWL: " << *BB;
1164
1165       // Notify all instructions in this basic block that they are newly
1166       // executable.
1167       visit(BB);
1168     }
1169   }
1170 }
1171
1172 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1173 /// that branches on undef values cannot reach any of their successors.
1174 /// However, this is not a safe assumption.  After we solve dataflow, this
1175 /// method should be use to handle this.  If this returns true, the solver
1176 /// should be rerun.
1177 ///
1178 /// This method handles this by finding an unresolved branch and marking it one
1179 /// of the edges from the block as being feasible, even though the condition
1180 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1181 /// CFG and only slightly pessimizes the analysis results (by marking one,
1182 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1183 /// constraints on the condition of the branch, as that would impact other users
1184 /// of the value.
1185 ///
1186 /// This scan also checks for values that use undefs, whose results are actually
1187 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
1188 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1189 /// even if X isn't defined.
1190 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1191   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1192     if (!BBExecutable.count(BB))
1193       continue;
1194     
1195     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1196       // Look for instructions which produce undef values.
1197       if (I->getType() == Type::VoidTy) continue;
1198       
1199       LatticeVal &LV = getValueState(I);
1200       if (!LV.isUndefined()) continue;
1201
1202       // Get the lattice values of the first two operands for use below.
1203       LatticeVal &Op0LV = getValueState(I->getOperand(0));
1204       LatticeVal Op1LV;
1205       if (I->getNumOperands() == 2) {
1206         // If this is a two-operand instruction, and if both operands are
1207         // undefs, the result stays undef.
1208         Op1LV = getValueState(I->getOperand(1));
1209         if (Op0LV.isUndefined() && Op1LV.isUndefined())
1210           continue;
1211       }
1212       
1213       // If this is an instructions whose result is defined even if the input is
1214       // not fully defined, propagate the information.
1215       const Type *ITy = I->getType();
1216       switch (I->getOpcode()) {
1217       default: break;          // Leave the instruction as an undef.
1218       case Instruction::ZExt:
1219         // After a zero extend, we know the top part is zero.  SExt doesn't have
1220         // to be handled here, because we don't know whether the top part is 1's
1221         // or 0's.
1222         assert(Op0LV.isUndefined());
1223         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1224         return true;
1225       case Instruction::Mul:
1226       case Instruction::And:
1227         // undef * X -> 0.   X could be zero.
1228         // undef & X -> 0.   X could be zero.
1229         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1230         return true;
1231
1232       case Instruction::Or:
1233         // undef | X -> -1.   X could be -1.
1234         markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1235         return true;
1236
1237       case Instruction::SDiv:
1238       case Instruction::UDiv:
1239       case Instruction::SRem:
1240       case Instruction::URem:
1241         // X / undef -> undef.  No change.
1242         // X % undef -> undef.  No change.
1243         if (Op1LV.isUndefined()) break;
1244         
1245         // undef / X -> 0.   X could be maxint.
1246         // undef % X -> 0.   X could be 1.
1247         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1248         return true;
1249         
1250       case Instruction::AShr:
1251         // undef >>s X -> undef.  No change.
1252         if (Op0LV.isUndefined()) break;
1253         
1254         // X >>s undef -> X.  X could be 0, X could have the high-bit known set.
1255         if (Op0LV.isConstant())
1256           markForcedConstant(LV, I, Op0LV.getConstant());
1257         else
1258           markOverdefined(LV, I);
1259         return true;
1260       case Instruction::LShr:
1261       case Instruction::Shl:
1262         // undef >> X -> undef.  No change.
1263         // undef << X -> undef.  No change.
1264         if (Op0LV.isUndefined()) break;
1265         
1266         // X >> undef -> 0.  X could be 0.
1267         // X << undef -> 0.  X could be 0.
1268         markForcedConstant(LV, I, Constant::getNullValue(ITy));
1269         return true;
1270       case Instruction::Select:
1271         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
1272         if (Op0LV.isUndefined()) {
1273           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
1274             Op1LV = getValueState(I->getOperand(2));
1275         } else if (Op1LV.isUndefined()) {
1276           // c ? undef : undef -> undef.  No change.
1277           Op1LV = getValueState(I->getOperand(2));
1278           if (Op1LV.isUndefined())
1279             break;
1280           // Otherwise, c ? undef : x -> x.
1281         } else {
1282           // Leave Op1LV as Operand(1)'s LatticeValue.
1283         }
1284         
1285         if (Op1LV.isConstant())
1286           markForcedConstant(LV, I, Op1LV.getConstant());
1287         else
1288           markOverdefined(LV, I);
1289         return true;
1290       }
1291     }
1292   
1293     TerminatorInst *TI = BB->getTerminator();
1294     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1295       if (!BI->isConditional()) continue;
1296       if (!getValueState(BI->getCondition()).isUndefined())
1297         continue;
1298     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1299       if (!getValueState(SI->getCondition()).isUndefined())
1300         continue;
1301     } else {
1302       continue;
1303     }
1304     
1305     // If the edge to the first successor isn't thought to be feasible yet, mark
1306     // it so now.
1307     if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(0))))
1308       continue;
1309     
1310     // Otherwise, it isn't already thought to be feasible.  Mark it as such now
1311     // and return.  This will make other blocks reachable, which will allow new
1312     // values to be discovered and existing ones to be moved in the lattice.
1313     markEdgeExecutable(BB, TI->getSuccessor(0));
1314     return true;
1315   }
1316
1317   return false;
1318 }
1319
1320
1321 namespace {
1322   //===--------------------------------------------------------------------===//
1323   //
1324   /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1325   /// Sparse Conditional COnstant Propagator.
1326   ///
1327   struct SCCP : public FunctionPass {
1328     // runOnFunction - Run the Sparse Conditional Constant Propagation
1329     // algorithm, and return true if the function was modified.
1330     //
1331     bool runOnFunction(Function &F);
1332
1333     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1334       AU.setPreservesCFG();
1335     }
1336   };
1337
1338   RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
1339 } // end anonymous namespace
1340
1341
1342 // createSCCPPass - This is the public interface to this file...
1343 FunctionPass *llvm::createSCCPPass() {
1344   return new SCCP();
1345 }
1346
1347
1348 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1349 // and return true if the function was modified.
1350 //
1351 bool SCCP::runOnFunction(Function &F) {
1352   DOUT << "SCCP on function '" << F.getName() << "'\n";
1353   SCCPSolver Solver;
1354
1355   // Mark the first block of the function as being executable.
1356   Solver.MarkBlockExecutable(F.begin());
1357
1358   // Mark all arguments to the function as being overdefined.
1359   hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1360   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
1361     Values[AI].markOverdefined();
1362
1363   // Solve for constants.
1364   bool ResolvedUndefs = true;
1365   while (ResolvedUndefs) {
1366     Solver.Solve();
1367     DOUT << "RESOLVING UNDEFs\n";
1368     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1369   }
1370
1371   bool MadeChanges = false;
1372
1373   // If we decided that there are basic blocks that are dead in this function,
1374   // delete their contents now.  Note that we cannot actually delete the blocks,
1375   // as we cannot modify the CFG of the function.
1376   //
1377   std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1378   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1379     if (!ExecutableBBs.count(BB)) {
1380       DOUT << "  BasicBlock Dead:" << *BB;
1381       ++NumDeadBlocks;
1382
1383       // Delete the instructions backwards, as it has a reduced likelihood of
1384       // having to update as many def-use and use-def chains.
1385       std::vector<Instruction*> Insts;
1386       for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1387            I != E; ++I)
1388         Insts.push_back(I);
1389       while (!Insts.empty()) {
1390         Instruction *I = Insts.back();
1391         Insts.pop_back();
1392         if (!I->use_empty())
1393           I->replaceAllUsesWith(UndefValue::get(I->getType()));
1394         BB->getInstList().erase(I);
1395         MadeChanges = true;
1396         ++NumInstRemoved;
1397       }
1398     } else {
1399       // Iterate over all of the instructions in a function, replacing them with
1400       // constants if we have found them to be of constant values.
1401       //
1402       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1403         Instruction *Inst = BI++;
1404         if (Inst->getType() != Type::VoidTy) {
1405           LatticeVal &IV = Values[Inst];
1406           if (IV.isConstant() || IV.isUndefined() &&
1407               !isa<TerminatorInst>(Inst)) {
1408             Constant *Const = IV.isConstant()
1409               ? IV.getConstant() : UndefValue::get(Inst->getType());
1410             DOUT << "  Constant: " << *Const << " = " << *Inst;
1411
1412             // Replaces all of the uses of a variable with uses of the constant.
1413             Inst->replaceAllUsesWith(Const);
1414
1415             // Delete the instruction.
1416             BB->getInstList().erase(Inst);
1417
1418             // Hey, we just changed something!
1419             MadeChanges = true;
1420             ++NumInstRemoved;
1421           }
1422         }
1423       }
1424     }
1425
1426   return MadeChanges;
1427 }
1428
1429 namespace {
1430   //===--------------------------------------------------------------------===//
1431   //
1432   /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1433   /// Constant Propagation.
1434   ///
1435   struct IPSCCP : public ModulePass {
1436     bool runOnModule(Module &M);
1437   };
1438
1439   RegisterPass<IPSCCP>
1440   Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1441 } // end anonymous namespace
1442
1443 // createIPSCCPPass - This is the public interface to this file...
1444 ModulePass *llvm::createIPSCCPPass() {
1445   return new IPSCCP();
1446 }
1447
1448
1449 static bool AddressIsTaken(GlobalValue *GV) {
1450   // Delete any dead constantexpr klingons.
1451   GV->removeDeadConstantUsers();
1452
1453   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1454        UI != E; ++UI)
1455     if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1456       if (SI->getOperand(0) == GV || SI->isVolatile())
1457         return true;  // Storing addr of GV.
1458     } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1459       // Make sure we are calling the function, not passing the address.
1460       CallSite CS = CallSite::get(cast<Instruction>(*UI));
1461       for (CallSite::arg_iterator AI = CS.arg_begin(),
1462              E = CS.arg_end(); AI != E; ++AI)
1463         if (*AI == GV)
1464           return true;
1465     } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1466       if (LI->isVolatile())
1467         return true;
1468     } else {
1469       return true;
1470     }
1471   return false;
1472 }
1473
1474 bool IPSCCP::runOnModule(Module &M) {
1475   SCCPSolver Solver;
1476
1477   // Loop over all functions, marking arguments to those with their addresses
1478   // taken or that are external as overdefined.
1479   //
1480   hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1481   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1482     if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1483       if (!F->isExternal())
1484         Solver.MarkBlockExecutable(F->begin());
1485       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1486            AI != E; ++AI)
1487         Values[AI].markOverdefined();
1488     } else {
1489       Solver.AddTrackedFunction(F);
1490     }
1491
1492   // Loop over global variables.  We inform the solver about any internal global
1493   // variables that do not have their 'addresses taken'.  If they don't have
1494   // their addresses taken, we can propagate constants through them.
1495   for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1496        G != E; ++G)
1497     if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1498       Solver.TrackValueOfGlobalVariable(G);
1499
1500   // Solve for constants.
1501   bool ResolvedUndefs = true;
1502   while (ResolvedUndefs) {
1503     Solver.Solve();
1504
1505     DOUT << "RESOLVING UNDEFS\n";
1506     ResolvedUndefs = false;
1507     for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1508       ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1509   }
1510
1511   bool MadeChanges = false;
1512
1513   // Iterate over all of the instructions in the module, replacing them with
1514   // constants if we have found them to be of constant values.
1515   //
1516   std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1517   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1518     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1519          AI != E; ++AI)
1520       if (!AI->use_empty()) {
1521         LatticeVal &IV = Values[AI];
1522         if (IV.isConstant() || IV.isUndefined()) {
1523           Constant *CST = IV.isConstant() ?
1524             IV.getConstant() : UndefValue::get(AI->getType());
1525           DOUT << "***  Arg " << *AI << " = " << *CST <<"\n";
1526
1527           // Replaces all of the uses of a variable with uses of the
1528           // constant.
1529           AI->replaceAllUsesWith(CST);
1530           ++IPNumArgsElimed;
1531         }
1532       }
1533
1534     std::vector<BasicBlock*> BlocksToErase;
1535     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1536       if (!ExecutableBBs.count(BB)) {
1537         DOUT << "  BasicBlock Dead:" << *BB;
1538         ++IPNumDeadBlocks;
1539
1540         // Delete the instructions backwards, as it has a reduced likelihood of
1541         // having to update as many def-use and use-def chains.
1542         std::vector<Instruction*> Insts;
1543         TerminatorInst *TI = BB->getTerminator();
1544         for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1545           Insts.push_back(I);
1546
1547         while (!Insts.empty()) {
1548           Instruction *I = Insts.back();
1549           Insts.pop_back();
1550           if (!I->use_empty())
1551             I->replaceAllUsesWith(UndefValue::get(I->getType()));
1552           BB->getInstList().erase(I);
1553           MadeChanges = true;
1554           ++IPNumInstRemoved;
1555         }
1556
1557         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1558           BasicBlock *Succ = TI->getSuccessor(i);
1559           if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1560             TI->getSuccessor(i)->removePredecessor(BB);
1561         }
1562         if (!TI->use_empty())
1563           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1564         BB->getInstList().erase(TI);
1565
1566         if (&*BB != &F->front())
1567           BlocksToErase.push_back(BB);
1568         else
1569           new UnreachableInst(BB);
1570
1571       } else {
1572         for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1573           Instruction *Inst = BI++;
1574           if (Inst->getType() != Type::VoidTy) {
1575             LatticeVal &IV = Values[Inst];
1576             if (IV.isConstant() || IV.isUndefined() &&
1577                 !isa<TerminatorInst>(Inst)) {
1578               Constant *Const = IV.isConstant()
1579                 ? IV.getConstant() : UndefValue::get(Inst->getType());
1580               DOUT << "  Constant: " << *Const << " = " << *Inst;
1581
1582               // Replaces all of the uses of a variable with uses of the
1583               // constant.
1584               Inst->replaceAllUsesWith(Const);
1585
1586               // Delete the instruction.
1587               if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1588                 BB->getInstList().erase(Inst);
1589
1590               // Hey, we just changed something!
1591               MadeChanges = true;
1592               ++IPNumInstRemoved;
1593             }
1594           }
1595         }
1596       }
1597
1598     // Now that all instructions in the function are constant folded, erase dead
1599     // blocks, because we can now use ConstantFoldTerminator to get rid of
1600     // in-edges.
1601     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1602       // If there are any PHI nodes in this successor, drop entries for BB now.
1603       BasicBlock *DeadBB = BlocksToErase[i];
1604       while (!DeadBB->use_empty()) {
1605         Instruction *I = cast<Instruction>(DeadBB->use_back());
1606         bool Folded = ConstantFoldTerminator(I->getParent());
1607         if (!Folded) {
1608           // The constant folder may not have been able to fold the termiantor
1609           // if this is a branch or switch on undef.  Fold it manually as a
1610           // branch to the first successor.
1611           if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1612             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1613                    "Branch should be foldable!");
1614           } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1615             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1616           } else {
1617             assert(0 && "Didn't fold away reference to block!");
1618           }
1619           
1620           // Make this an uncond branch to the first successor.
1621           TerminatorInst *TI = I->getParent()->getTerminator();
1622           new BranchInst(TI->getSuccessor(0), TI);
1623           
1624           // Remove entries in successor phi nodes to remove edges.
1625           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1626             TI->getSuccessor(i)->removePredecessor(TI->getParent());
1627           
1628           // Remove the old terminator.
1629           TI->eraseFromParent();
1630         }
1631       }
1632
1633       // Finally, delete the basic block.
1634       F->getBasicBlockList().erase(DeadBB);
1635     }
1636   }
1637
1638   // If we inferred constant or undef return values for a function, we replaced
1639   // all call uses with the inferred value.  This means we don't need to bother
1640   // actually returning anything from the function.  Replace all return
1641   // instructions with return undef.
1642   const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1643   for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1644          E = RV.end(); I != E; ++I)
1645     if (!I->second.isOverdefined() &&
1646         I->first->getReturnType() != Type::VoidTy) {
1647       Function *F = I->first;
1648       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1649         if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1650           if (!isa<UndefValue>(RI->getOperand(0)))
1651             RI->setOperand(0, UndefValue::get(F->getReturnType()));
1652     }
1653
1654   // If we infered constant or undef values for globals variables, we can delete
1655   // the global and any stores that remain to it.
1656   const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1657   for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1658          E = TG.end(); I != E; ++I) {
1659     GlobalVariable *GV = I->first;
1660     assert(!I->second.isOverdefined() &&
1661            "Overdefined values should have been taken out of the map!");
1662     DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
1663     while (!GV->use_empty()) {
1664       StoreInst *SI = cast<StoreInst>(GV->use_back());
1665       SI->eraseFromParent();
1666     }
1667     M.getGlobalList().erase(GV);
1668     ++IPNumGlobalConst;
1669   }
1670
1671   return MadeChanges;
1672 }