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