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