621508f7a8924144861eca0c4ef2d93e693aca10
[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 is distributed under the University of Illinois Open Source
6 // 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 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "sccp"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/InstVisitor.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include <algorithm>
44 #include <map>
45 using namespace llvm;
46
47 STATISTIC(NumInstRemoved, "Number of instructions removed");
48 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
50 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
51 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
54 namespace {
55 /// LatticeVal class - This class represents the different lattice values that
56 /// an LLVM value may occupy.  It is a simple class with value semantics.
57 ///
58 class LatticeVal {
59   enum LatticeValueTy {
60     /// undefined - This LLVM Value has no known value yet.
61     undefined,
62     
63     /// constant - This LLVM Value has a specific constant value.
64     constant,
65
66     /// forcedconstant - This LLVM Value was thought to be undef until
67     /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
68     /// with another (different) constant, it goes to overdefined, instead of
69     /// asserting.
70     forcedconstant,
71     
72     /// overdefined - This instruction is not known to be constant, and we know
73     /// it has a value.
74     overdefined
75   };
76
77   /// Val: This stores the current lattice value along with the Constant* for
78   /// the constant if this is a 'constant' or 'forcedconstant' value.
79   PointerIntPair<Constant *, 2, LatticeValueTy> Val;
80   
81   LatticeValueTy getLatticeValue() const {
82     return Val.getInt();
83   }
84   
85 public:
86   LatticeVal() : Val(0, undefined) {}
87   
88   bool isUndefined() const { return getLatticeValue() == undefined; }
89   bool isConstant() const {
90     return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91   }
92   bool isOverdefined() const { return getLatticeValue() == overdefined; }
93   
94   Constant *getConstant() const {
95     assert(isConstant() && "Cannot get the constant of a non-constant!");
96     return Val.getPointer();
97   }
98   
99   /// markOverdefined - Return true if this is a change in status.
100   bool markOverdefined() {
101     if (isOverdefined())
102       return false;
103     
104     Val.setInt(overdefined);
105     return true;
106   }
107
108   /// markConstant - Return true if this is a change in status.
109   bool markConstant(Constant *V) {
110     if (getLatticeValue() == constant) { // Constant but not forcedconstant.
111       assert(getConstant() == V && "Marking constant with different value");
112       return false;
113     }
114     
115     if (isUndefined()) {
116       Val.setInt(constant);
117       assert(V && "Marking constant with NULL");
118       Val.setPointer(V);
119     } else {
120       assert(getLatticeValue() == forcedconstant && 
121              "Cannot move from overdefined to constant!");
122       // Stay at forcedconstant if the constant is the same.
123       if (V == getConstant()) return false;
124       
125       // Otherwise, we go to overdefined.  Assumptions made based on the
126       // forced value are possibly wrong.  Assuming this is another constant
127       // could expose a contradiction.
128       Val.setInt(overdefined);
129     }
130     return true;
131   }
132
133   /// getConstantInt - If this is a constant with a ConstantInt value, return it
134   /// otherwise return null.
135   ConstantInt *getConstantInt() const {
136     if (isConstant())
137       return dyn_cast<ConstantInt>(getConstant());
138     return 0;
139   }
140   
141   void markForcedConstant(Constant *V) {
142     assert(isUndefined() && "Can't force a defined value!");
143     Val.setInt(forcedconstant);
144     Val.setPointer(V);
145   }
146 };
147 } // end anonymous namespace.
148
149
150 namespace {
151
152 //===----------------------------------------------------------------------===//
153 //
154 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155 /// Constant Propagation.
156 ///
157 class SCCPSolver : public InstVisitor<SCCPSolver> {
158   const TargetData *TD;
159   SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
160   DenseMap<Value*, LatticeVal> ValueState;  // The state each value is in.
161
162   /// StructValueState - This maintains ValueState for values that have
163   /// StructType, for example for formal arguments, calls, insertelement, etc.
164   ///
165   DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
166   
167   /// GlobalValue - If we are tracking any values for the contents of a global
168   /// variable, we keep a mapping from the constant accessor to the element of
169   /// the global, to the currently known value.  If the value becomes
170   /// overdefined, it's entry is simply removed from this map.
171   DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
172
173   /// TrackedRetVals - If we are tracking arguments into and the return
174   /// value out of a function, it will have an entry in this map, indicating
175   /// what the known return value for the function is.
176   DenseMap<Function*, LatticeVal> TrackedRetVals;
177
178   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179   /// that return multiple values.
180   DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
181   
182   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183   /// represented here for efficient lookup.
184   SmallPtrSet<Function*, 16> MRVFunctionsTracked;
185
186   /// TrackingIncomingArguments - This is the set of functions for whose
187   /// arguments we make optimistic assumptions about and try to prove as
188   /// constants.
189   SmallPtrSet<Function*, 16> TrackingIncomingArguments;
190   
191   /// The reason for two worklists is that overdefined is the lowest state
192   /// on the lattice, and moving things to overdefined as fast as possible
193   /// makes SCCP converge much faster.
194   ///
195   /// By having a separate worklist, we accomplish this because everything
196   /// possibly overdefined will become overdefined at the soonest possible
197   /// point.
198   SmallVector<Value*, 64> OverdefinedInstWorkList;
199   SmallVector<Value*, 64> InstWorkList;
200
201
202   SmallVector<BasicBlock*, 64>  BBWorkList;  // The BasicBlock work list
203
204   /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
205   /// overdefined, despite the fact that the PHI node is overdefined.
206   std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
207
208   /// KnownFeasibleEdges - Entries in this set are edges which have already had
209   /// PHI nodes retriggered.
210   typedef std::pair<BasicBlock*, BasicBlock*> Edge;
211   DenseSet<Edge> KnownFeasibleEdges;
212 public:
213   SCCPSolver(const TargetData *td) : TD(td) {}
214
215   /// MarkBlockExecutable - This method can be used by clients to mark all of
216   /// the blocks that are known to be intrinsically live in the processed unit.
217   ///
218   /// This returns true if the block was not considered live before.
219   bool MarkBlockExecutable(BasicBlock *BB) {
220     if (!BBExecutable.insert(BB)) return false;
221     DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
222     BBWorkList.push_back(BB);  // Add the block to the work list!
223     return true;
224   }
225
226   /// TrackValueOfGlobalVariable - Clients can use this method to
227   /// inform the SCCPSolver that it should track loads and stores to the
228   /// specified global variable if it can.  This is only legal to call if
229   /// performing Interprocedural SCCP.
230   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
231     // We only track the contents of scalar globals.
232     if (GV->getType()->getElementType()->isSingleValueType()) {
233       LatticeVal &IV = TrackedGlobals[GV];
234       if (!isa<UndefValue>(GV->getInitializer()))
235         IV.markConstant(GV->getInitializer());
236     }
237   }
238
239   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
240   /// and out of the specified function (which cannot have its address taken),
241   /// this method must be called.
242   void AddTrackedFunction(Function *F) {
243     // Add an entry, F -> undef.
244     if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
245       MRVFunctionsTracked.insert(F);
246       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
247         TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
248                                                      LatticeVal()));
249     } else
250       TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
251   }
252
253   void AddArgumentTrackedFunction(Function *F) {
254     TrackingIncomingArguments.insert(F);
255   }
256   
257   /// Solve - Solve for constants and executable blocks.
258   ///
259   void Solve();
260
261   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
262   /// that branches on undef values cannot reach any of their successors.
263   /// However, this is not a safe assumption.  After we solve dataflow, this
264   /// method should be use to handle this.  If this returns true, the solver
265   /// should be rerun.
266   bool ResolvedUndefsIn(Function &F);
267
268   bool isBlockExecutable(BasicBlock *BB) const {
269     return BBExecutable.count(BB);
270   }
271
272   LatticeVal getLatticeValueFor(Value *V) const {
273     DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
274     assert(I != ValueState.end() && "V is not in valuemap!");
275     return I->second;
276   }
277   
278   /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
279     DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I = 
280       StructValueState.find(std::make_pair(V, i));
281     assert(I != StructValueState.end() && "V is not in valuemap!");
282     return I->second;
283   }*/
284
285   /// getTrackedRetVals - Get the inferred return value map.
286   ///
287   const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
288     return TrackedRetVals;
289   }
290
291   /// getTrackedGlobals - Get and return the set of inferred initializers for
292   /// global variables.
293   const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
294     return TrackedGlobals;
295   }
296
297   void markOverdefined(Value *V) {
298     assert(!V->getType()->isStructTy() && "Should use other method");
299     markOverdefined(ValueState[V], V);
300   }
301
302   /// markAnythingOverdefined - Mark the specified value overdefined.  This
303   /// works with both scalars and structs.
304   void markAnythingOverdefined(Value *V) {
305     if (const StructType *STy = dyn_cast<StructType>(V->getType()))
306       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
307         markOverdefined(getStructValueState(V, i), V);
308     else
309       markOverdefined(V);
310   }
311   
312 private:
313   // markConstant - Make a value be marked as "constant".  If the value
314   // is not already a constant, add it to the instruction work list so that
315   // the users of the instruction are updated later.
316   //
317   void markConstant(LatticeVal &IV, Value *V, Constant *C) {
318     if (!IV.markConstant(C)) return;
319     DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
320     if (IV.isOverdefined())
321       OverdefinedInstWorkList.push_back(V);
322     else
323       InstWorkList.push_back(V);
324   }
325   
326   void markConstant(Value *V, Constant *C) {
327     assert(!V->getType()->isStructTy() && "Should use other method");
328     markConstant(ValueState[V], V, C);
329   }
330
331   void markForcedConstant(Value *V, Constant *C) {
332     assert(!V->getType()->isStructTy() && "Should use other method");
333     LatticeVal &IV = ValueState[V];
334     IV.markForcedConstant(C);
335     DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
336     if (IV.isOverdefined())
337       OverdefinedInstWorkList.push_back(V);
338     else
339       InstWorkList.push_back(V);
340   }
341   
342   
343   // markOverdefined - Make a value be marked as "overdefined". If the
344   // value is not already overdefined, add it to the overdefined instruction
345   // work list so that the users of the instruction are updated later.
346   void markOverdefined(LatticeVal &IV, Value *V) {
347     if (!IV.markOverdefined()) return;
348     
349     DEBUG(dbgs() << "markOverdefined: ";
350           if (Function *F = dyn_cast<Function>(V))
351             dbgs() << "Function '" << F->getName() << "'\n";
352           else
353             dbgs() << *V << '\n');
354     // Only instructions go on the work list
355     OverdefinedInstWorkList.push_back(V);
356   }
357
358   void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
359     if (IV.isOverdefined() || MergeWithV.isUndefined())
360       return;  // Noop.
361     if (MergeWithV.isOverdefined())
362       markOverdefined(IV, V);
363     else if (IV.isUndefined())
364       markConstant(IV, V, MergeWithV.getConstant());
365     else if (IV.getConstant() != MergeWithV.getConstant())
366       markOverdefined(IV, V);
367   }
368   
369   void mergeInValue(Value *V, LatticeVal MergeWithV) {
370     assert(!V->getType()->isStructTy() && "Should use other method");
371     mergeInValue(ValueState[V], V, MergeWithV);
372   }
373
374
375   /// getValueState - Return the LatticeVal object that corresponds to the
376   /// value.  This function handles the case when the value hasn't been seen yet
377   /// by properly seeding constants etc.
378   LatticeVal &getValueState(Value *V) {
379     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
380
381     std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
382       ValueState.insert(std::make_pair(V, LatticeVal()));
383     LatticeVal &LV = I.first->second;
384
385     if (!I.second)
386       return LV;  // Common case, already in the map.
387
388     if (Constant *C = dyn_cast<Constant>(V)) {
389       // Undef values remain undefined.
390       if (!isa<UndefValue>(V))
391         LV.markConstant(C);          // Constants are constant
392     }
393     
394     // All others are underdefined by default.
395     return LV;
396   }
397
398   /// getStructValueState - Return the LatticeVal object that corresponds to the
399   /// value/field pair.  This function handles the case when the value hasn't
400   /// been seen yet by properly seeding constants etc.
401   LatticeVal &getStructValueState(Value *V, unsigned i) {
402     assert(V->getType()->isStructTy() && "Should use getValueState");
403     assert(i < cast<StructType>(V->getType())->getNumElements() &&
404            "Invalid element #");
405
406     std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
407               bool> I = StructValueState.insert(
408                         std::make_pair(std::make_pair(V, i), LatticeVal()));
409     LatticeVal &LV = I.first->second;
410
411     if (!I.second)
412       return LV;  // Common case, already in the map.
413
414     if (Constant *C = dyn_cast<Constant>(V)) {
415       if (isa<UndefValue>(C))
416         ; // Undef values remain undefined.
417       else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
418         LV.markConstant(CS->getOperand(i));      // Constants are constant.
419       else if (isa<ConstantAggregateZero>(C)) {
420         const Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
421         LV.markConstant(Constant::getNullValue(FieldTy));
422       } else
423         LV.markOverdefined();      // Unknown sort of constant.
424     }
425     
426     // All others are underdefined by default.
427     return LV;
428   }
429   
430
431   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
432   /// work list if it is not already executable.
433   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
434     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
435       return;  // This edge is already known to be executable!
436
437     if (!MarkBlockExecutable(Dest)) {
438       // If the destination is already executable, we just made an *edge*
439       // feasible that wasn't before.  Revisit the PHI nodes in the block
440       // because they have potentially new operands.
441       DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
442             << " -> " << Dest->getName() << "\n");
443
444       PHINode *PN;
445       for (BasicBlock::iterator I = Dest->begin();
446            (PN = dyn_cast<PHINode>(I)); ++I)
447         visitPHINode(*PN);
448     }
449   }
450
451   // getFeasibleSuccessors - Return a vector of booleans to indicate which
452   // successors are reachable from a given terminator instruction.
453   //
454   void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
455
456   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
457   // block to the 'To' basic block is currently feasible.
458   //
459   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
460
461   // OperandChangedState - This method is invoked on all of the users of an
462   // instruction that was just changed state somehow.  Based on this
463   // information, we need to update the specified user of this instruction.
464   //
465   void OperandChangedState(Instruction *I) {
466     if (BBExecutable.count(I->getParent()))   // Inst is executable?
467       visit(*I);
468   }
469   
470   /// RemoveFromOverdefinedPHIs - If I has any entries in the
471   /// UsersOfOverdefinedPHIs map for PN, remove them now.
472   void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
473     if (UsersOfOverdefinedPHIs.empty()) return;
474     std::multimap<PHINode*, Instruction*>::iterator It, E;
475     tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
476     while (It != E) {
477       if (It->second == I)
478         UsersOfOverdefinedPHIs.erase(It++);
479       else
480         ++It;
481     }
482   }
483
484 private:
485   friend class InstVisitor<SCCPSolver>;
486
487   // visit implementations - Something changed in this instruction.  Either an
488   // operand made a transition, or the instruction is newly executable.  Change
489   // the value type of I to reflect these changes if appropriate.
490   void visitPHINode(PHINode &I);
491
492   // Terminators
493   void visitReturnInst(ReturnInst &I);
494   void visitTerminatorInst(TerminatorInst &TI);
495
496   void visitCastInst(CastInst &I);
497   void visitSelectInst(SelectInst &I);
498   void visitBinaryOperator(Instruction &I);
499   void visitCmpInst(CmpInst &I);
500   void visitExtractElementInst(ExtractElementInst &I);
501   void visitInsertElementInst(InsertElementInst &I);
502   void visitShuffleVectorInst(ShuffleVectorInst &I);
503   void visitExtractValueInst(ExtractValueInst &EVI);
504   void visitInsertValueInst(InsertValueInst &IVI);
505
506   // Instructions that cannot be folded away.
507   void visitStoreInst     (StoreInst &I);
508   void visitLoadInst      (LoadInst &I);
509   void visitGetElementPtrInst(GetElementPtrInst &I);
510   void visitCallInst      (CallInst &I) {
511     visitCallSite(&I);
512   }
513   void visitInvokeInst    (InvokeInst &II) {
514     visitCallSite(&II);
515     visitTerminatorInst(II);
516   }
517   void visitCallSite      (CallSite CS);
518   void visitUnwindInst    (TerminatorInst &I) { /*returns void*/ }
519   void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
520   void visitAllocaInst    (Instruction &I) { markOverdefined(&I); }
521   void visitVAArgInst     (Instruction &I) { markAnythingOverdefined(&I); }
522
523   void visitInstruction(Instruction &I) {
524     // If a new instruction is added to LLVM that we don't handle.
525     dbgs() << "SCCP: Don't know how to handle: " << I;
526     markAnythingOverdefined(&I);   // Just in case
527   }
528 };
529
530 } // end anonymous namespace
531
532
533 // getFeasibleSuccessors - Return a vector of booleans to indicate which
534 // successors are reachable from a given terminator instruction.
535 //
536 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
537                                        SmallVector<bool, 16> &Succs) {
538   Succs.resize(TI.getNumSuccessors());
539   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
540     if (BI->isUnconditional()) {
541       Succs[0] = true;
542       return;
543     }
544     
545     LatticeVal BCValue = getValueState(BI->getCondition());
546     ConstantInt *CI = BCValue.getConstantInt();
547     if (CI == 0) {
548       // Overdefined condition variables, and branches on unfoldable constant
549       // conditions, mean the branch could go either way.
550       if (!BCValue.isUndefined())
551         Succs[0] = Succs[1] = true;
552       return;
553     }
554     
555     // Constant condition variables mean the branch can only go a single way.
556     Succs[CI->isZero()] = true;
557     return;
558   }
559   
560   if (isa<InvokeInst>(TI)) {
561     // Invoke instructions successors are always executable.
562     Succs[0] = Succs[1] = true;
563     return;
564   }
565   
566   if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
567     LatticeVal SCValue = getValueState(SI->getCondition());
568     ConstantInt *CI = SCValue.getConstantInt();
569     
570     if (CI == 0) {   // Overdefined or undefined condition?
571       // All destinations are executable!
572       if (!SCValue.isUndefined())
573         Succs.assign(TI.getNumSuccessors(), true);
574       return;
575     }
576       
577     Succs[SI->findCaseValue(CI)] = true;
578     return;
579   }
580   
581   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
582   if (isa<IndirectBrInst>(&TI)) {
583     // Just mark all destinations executable!
584     Succs.assign(TI.getNumSuccessors(), true);
585     return;
586   }
587   
588 #ifndef NDEBUG
589   dbgs() << "Unknown terminator instruction: " << TI << '\n';
590 #endif
591   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
592 }
593
594
595 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
596 // block to the 'To' basic block is currently feasible.
597 //
598 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
599   assert(BBExecutable.count(To) && "Dest should always be alive!");
600
601   // Make sure the source basic block is executable!!
602   if (!BBExecutable.count(From)) return false;
603
604   // Check to make sure this edge itself is actually feasible now.
605   TerminatorInst *TI = From->getTerminator();
606   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
607     if (BI->isUnconditional())
608       return true;
609     
610     LatticeVal BCValue = getValueState(BI->getCondition());
611
612     // Overdefined condition variables mean the branch could go either way,
613     // undef conditions mean that neither edge is feasible yet.
614     ConstantInt *CI = BCValue.getConstantInt();
615     if (CI == 0)
616       return !BCValue.isUndefined();
617     
618     // Constant condition variables mean the branch can only go a single way.
619     return BI->getSuccessor(CI->isZero()) == To;
620   }
621   
622   // Invoke instructions successors are always executable.
623   if (isa<InvokeInst>(TI))
624     return true;
625   
626   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
627     LatticeVal SCValue = getValueState(SI->getCondition());
628     ConstantInt *CI = SCValue.getConstantInt();
629     
630     if (CI == 0)
631       return !SCValue.isUndefined();
632
633     // Make sure to skip the "default value" which isn't a value
634     for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
635       if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
636         return SI->getSuccessor(i) == To;
637
638     // If the constant value is not equal to any of the branches, we must
639     // execute default branch.
640     return SI->getDefaultDest() == To;
641   }
642   
643   // Just mark all destinations executable!
644   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
645   if (isa<IndirectBrInst>(&TI))
646     return true;
647   
648 #ifndef NDEBUG
649   dbgs() << "Unknown terminator instruction: " << *TI << '\n';
650 #endif
651   llvm_unreachable(0);
652 }
653
654 // visit Implementations - Something changed in this instruction, either an
655 // operand made a transition, or the instruction is newly executable.  Change
656 // the value type of I to reflect these changes if appropriate.  This method
657 // makes sure to do the following actions:
658 //
659 // 1. If a phi node merges two constants in, and has conflicting value coming
660 //    from different branches, or if the PHI node merges in an overdefined
661 //    value, then the PHI node becomes overdefined.
662 // 2. If a phi node merges only constants in, and they all agree on value, the
663 //    PHI node becomes a constant value equal to that.
664 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
665 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
666 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
667 // 6. If a conditional branch has a value that is constant, make the selected
668 //    destination executable
669 // 7. If a conditional branch has a value that is overdefined, make all
670 //    successors executable.
671 //
672 void SCCPSolver::visitPHINode(PHINode &PN) {
673   // If this PN returns a struct, just mark the result overdefined.
674   // TODO: We could do a lot better than this if code actually uses this.
675   if (PN.getType()->isStructTy())
676     return markAnythingOverdefined(&PN);
677   
678   if (getValueState(&PN).isOverdefined()) {
679     // There may be instructions using this PHI node that are not overdefined
680     // themselves.  If so, make sure that they know that the PHI node operand
681     // changed.
682     std::multimap<PHINode*, Instruction*>::iterator I, E;
683     tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
684     if (I == E)
685       return;
686     
687     SmallVector<Instruction*, 16> Users;
688     for (; I != E; ++I)
689       Users.push_back(I->second);
690     while (!Users.empty())
691       visit(Users.pop_back_val());
692     return;  // Quick exit
693   }
694
695   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
696   // and slow us down a lot.  Just mark them overdefined.
697   if (PN.getNumIncomingValues() > 64)
698     return markOverdefined(&PN);
699   
700   // Look at all of the executable operands of the PHI node.  If any of them
701   // are overdefined, the PHI becomes overdefined as well.  If they are all
702   // constant, and they agree with each other, the PHI becomes the identical
703   // constant.  If they are constant and don't agree, the PHI is overdefined.
704   // If there are no executable operands, the PHI remains undefined.
705   //
706   Constant *OperandVal = 0;
707   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
708     LatticeVal IV = getValueState(PN.getIncomingValue(i));
709     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
710
711     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
712       continue;
713     
714     if (IV.isOverdefined())    // PHI node becomes overdefined!
715       return markOverdefined(&PN);
716
717     if (OperandVal == 0) {   // Grab the first value.
718       OperandVal = IV.getConstant();
719       continue;
720     }
721     
722     // There is already a reachable operand.  If we conflict with it,
723     // then the PHI node becomes overdefined.  If we agree with it, we
724     // can continue on.
725     
726     // Check to see if there are two different constants merging, if so, the PHI
727     // node is overdefined.
728     if (IV.getConstant() != OperandVal)
729       return markOverdefined(&PN);
730   }
731
732   // If we exited the loop, this means that the PHI node only has constant
733   // arguments that agree with each other(and OperandVal is the constant) or
734   // OperandVal is null because there are no defined incoming arguments.  If
735   // this is the case, the PHI remains undefined.
736   //
737   if (OperandVal)
738     markConstant(&PN, OperandVal);      // Acquire operand value
739 }
740
741
742
743
744 void SCCPSolver::visitReturnInst(ReturnInst &I) {
745   if (I.getNumOperands() == 0) return;  // ret void
746
747   Function *F = I.getParent()->getParent();
748   Value *ResultOp = I.getOperand(0);
749   
750   // If we are tracking the return value of this function, merge it in.
751   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
752     DenseMap<Function*, LatticeVal>::iterator TFRVI =
753       TrackedRetVals.find(F);
754     if (TFRVI != TrackedRetVals.end()) {
755       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
756       return;
757     }
758   }
759   
760   // Handle functions that return multiple values.
761   if (!TrackedMultipleRetVals.empty()) {
762     if (const StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
763       if (MRVFunctionsTracked.count(F))
764         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
765           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
766                        getStructValueState(ResultOp, i));
767     
768   }
769 }
770
771 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
772   SmallVector<bool, 16> SuccFeasible;
773   getFeasibleSuccessors(TI, SuccFeasible);
774
775   BasicBlock *BB = TI.getParent();
776
777   // Mark all feasible successors executable.
778   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
779     if (SuccFeasible[i])
780       markEdgeExecutable(BB, TI.getSuccessor(i));
781 }
782
783 void SCCPSolver::visitCastInst(CastInst &I) {
784   LatticeVal OpSt = getValueState(I.getOperand(0));
785   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
786     markOverdefined(&I);
787   else if (OpSt.isConstant())        // Propagate constant value
788     markConstant(&I, ConstantExpr::getCast(I.getOpcode(), 
789                                            OpSt.getConstant(), I.getType()));
790 }
791
792
793 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
794   // If this returns a struct, mark all elements over defined, we don't track
795   // structs in structs.
796   if (EVI.getType()->isStructTy())
797     return markAnythingOverdefined(&EVI);
798     
799   // If this is extracting from more than one level of struct, we don't know.
800   if (EVI.getNumIndices() != 1)
801     return markOverdefined(&EVI);
802
803   Value *AggVal = EVI.getAggregateOperand();
804   if (AggVal->getType()->isStructTy()) {
805     unsigned i = *EVI.idx_begin();
806     LatticeVal EltVal = getStructValueState(AggVal, i);
807     mergeInValue(getValueState(&EVI), &EVI, EltVal);
808   } else {
809     // Otherwise, must be extracting from an array.
810     return markOverdefined(&EVI);
811   }
812 }
813
814 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
815   const StructType *STy = dyn_cast<StructType>(IVI.getType());
816   if (STy == 0)
817     return markOverdefined(&IVI);
818   
819   // If this has more than one index, we can't handle it, drive all results to
820   // undef.
821   if (IVI.getNumIndices() != 1)
822     return markAnythingOverdefined(&IVI);
823   
824   Value *Aggr = IVI.getAggregateOperand();
825   unsigned Idx = *IVI.idx_begin();
826   
827   // Compute the result based on what we're inserting.
828   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
829     // This passes through all values that aren't the inserted element.
830     if (i != Idx) {
831       LatticeVal EltVal = getStructValueState(Aggr, i);
832       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
833       continue;
834     }
835     
836     Value *Val = IVI.getInsertedValueOperand();
837     if (Val->getType()->isStructTy())
838       // We don't track structs in structs.
839       markOverdefined(getStructValueState(&IVI, i), &IVI);
840     else {
841       LatticeVal InVal = getValueState(Val);
842       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
843     }
844   }
845 }
846
847 void SCCPSolver::visitSelectInst(SelectInst &I) {
848   // If this select returns a struct, just mark the result overdefined.
849   // TODO: We could do a lot better than this if code actually uses this.
850   if (I.getType()->isStructTy())
851     return markAnythingOverdefined(&I);
852   
853   LatticeVal CondValue = getValueState(I.getCondition());
854   if (CondValue.isUndefined())
855     return;
856   
857   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
858     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
859     mergeInValue(&I, getValueState(OpVal));
860     return;
861   }
862   
863   // Otherwise, the condition is overdefined or a constant we can't evaluate.
864   // See if we can produce something better than overdefined based on the T/F
865   // value.
866   LatticeVal TVal = getValueState(I.getTrueValue());
867   LatticeVal FVal = getValueState(I.getFalseValue());
868   
869   // select ?, C, C -> C.
870   if (TVal.isConstant() && FVal.isConstant() && 
871       TVal.getConstant() == FVal.getConstant())
872     return markConstant(&I, FVal.getConstant());
873
874   if (TVal.isUndefined())   // select ?, undef, X -> X.
875     return mergeInValue(&I, FVal);
876   if (FVal.isUndefined())   // select ?, X, undef -> X.
877     return mergeInValue(&I, TVal);
878   markOverdefined(&I);
879 }
880
881 // Handle Binary Operators.
882 void SCCPSolver::visitBinaryOperator(Instruction &I) {
883   LatticeVal V1State = getValueState(I.getOperand(0));
884   LatticeVal V2State = getValueState(I.getOperand(1));
885   
886   LatticeVal &IV = ValueState[&I];
887   if (IV.isOverdefined()) return;
888
889   if (V1State.isConstant() && V2State.isConstant())
890     return markConstant(IV, &I,
891                         ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
892                                           V2State.getConstant()));
893   
894   // If something is undef, wait for it to resolve.
895   if (!V1State.isOverdefined() && !V2State.isOverdefined())
896     return;
897   
898   // Otherwise, one of our operands is overdefined.  Try to produce something
899   // better than overdefined with some tricks.
900   
901   // If this is an AND or OR with 0 or -1, it doesn't matter that the other
902   // operand is overdefined.
903   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
904     LatticeVal *NonOverdefVal = 0;
905     if (!V1State.isOverdefined())
906       NonOverdefVal = &V1State;
907     else if (!V2State.isOverdefined())
908       NonOverdefVal = &V2State;
909
910     if (NonOverdefVal) {
911       if (NonOverdefVal->isUndefined()) {
912         // Could annihilate value.
913         if (I.getOpcode() == Instruction::And)
914           markConstant(IV, &I, Constant::getNullValue(I.getType()));
915         else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
916           markConstant(IV, &I, Constant::getAllOnesValue(PT));
917         else
918           markConstant(IV, &I,
919                        Constant::getAllOnesValue(I.getType()));
920         return;
921       }
922       
923       if (I.getOpcode() == Instruction::And) {
924         // X and 0 = 0
925         if (NonOverdefVal->getConstant()->isNullValue())
926           return markConstant(IV, &I, NonOverdefVal->getConstant());
927       } else {
928         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
929           if (CI->isAllOnesValue())     // X or -1 = -1
930             return markConstant(IV, &I, NonOverdefVal->getConstant());
931       }
932     }
933   }
934
935
936   // If both operands are PHI nodes, it is possible that this instruction has
937   // a constant value, despite the fact that the PHI node doesn't.  Check for
938   // this condition now.
939   if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
940     if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
941       if (PN1->getParent() == PN2->getParent()) {
942         // Since the two PHI nodes are in the same basic block, they must have
943         // entries for the same predecessors.  Walk the predecessor list, and
944         // if all of the incoming values are constants, and the result of
945         // evaluating this expression with all incoming value pairs is the
946         // same, then this expression is a constant even though the PHI node
947         // is not a constant!
948         LatticeVal Result;
949         for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
950           LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
951           BasicBlock *InBlock = PN1->getIncomingBlock(i);
952           LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
953
954           if (In1.isOverdefined() || In2.isOverdefined()) {
955             Result.markOverdefined();
956             break;  // Cannot fold this operation over the PHI nodes!
957           }
958           
959           if (In1.isConstant() && In2.isConstant()) {
960             Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
961                                             In2.getConstant());
962             if (Result.isUndefined())
963               Result.markConstant(V);
964             else if (Result.isConstant() && Result.getConstant() != V) {
965               Result.markOverdefined();
966               break;
967             }
968           }
969         }
970
971         // If we found a constant value here, then we know the instruction is
972         // constant despite the fact that the PHI nodes are overdefined.
973         if (Result.isConstant()) {
974           markConstant(IV, &I, Result.getConstant());
975           // Remember that this instruction is virtually using the PHI node
976           // operands.
977           UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
978           UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
979           return;
980         }
981         
982         if (Result.isUndefined())
983           return;
984
985         // Okay, this really is overdefined now.  Since we might have
986         // speculatively thought that this was not overdefined before, and
987         // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
988         // make sure to clean out any entries that we put there, for
989         // efficiency.
990         RemoveFromOverdefinedPHIs(&I, PN1);
991         RemoveFromOverdefinedPHIs(&I, PN2);
992       }
993
994   markOverdefined(&I);
995 }
996
997 // Handle ICmpInst instruction.
998 void SCCPSolver::visitCmpInst(CmpInst &I) {
999   LatticeVal V1State = getValueState(I.getOperand(0));
1000   LatticeVal V2State = getValueState(I.getOperand(1));
1001
1002   LatticeVal &IV = ValueState[&I];
1003   if (IV.isOverdefined()) return;
1004
1005   if (V1State.isConstant() && V2State.isConstant())
1006     return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(), 
1007                                                          V1State.getConstant(), 
1008                                                         V2State.getConstant()));
1009   
1010   // If operands are still undefined, wait for it to resolve.
1011   if (!V1State.isOverdefined() && !V2State.isOverdefined())
1012     return;
1013   
1014   // If something is overdefined, use some tricks to avoid ending up and over
1015   // defined if we can.
1016   
1017   // If both operands are PHI nodes, it is possible that this instruction has
1018   // a constant value, despite the fact that the PHI node doesn't.  Check for
1019   // this condition now.
1020   if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
1021     if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
1022       if (PN1->getParent() == PN2->getParent()) {
1023         // Since the two PHI nodes are in the same basic block, they must have
1024         // entries for the same predecessors.  Walk the predecessor list, and
1025         // if all of the incoming values are constants, and the result of
1026         // evaluating this expression with all incoming value pairs is the
1027         // same, then this expression is a constant even though the PHI node
1028         // is not a constant!
1029         LatticeVal Result;
1030         for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
1031           LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
1032           BasicBlock *InBlock = PN1->getIncomingBlock(i);
1033           LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
1034
1035           if (In1.isOverdefined() || In2.isOverdefined()) {
1036             Result.markOverdefined();
1037             break;  // Cannot fold this operation over the PHI nodes!
1038           }
1039           
1040           if (In1.isConstant() && In2.isConstant()) {
1041             Constant *V = ConstantExpr::getCompare(I.getPredicate(), 
1042                                                    In1.getConstant(), 
1043                                                    In2.getConstant());
1044             if (Result.isUndefined())
1045               Result.markConstant(V);
1046             else if (Result.isConstant() && Result.getConstant() != V) {
1047               Result.markOverdefined();
1048               break;
1049             }
1050           }
1051         }
1052
1053         // If we found a constant value here, then we know the instruction is
1054         // constant despite the fact that the PHI nodes are overdefined.
1055         if (Result.isConstant()) {
1056           markConstant(&I, Result.getConstant());
1057           // Remember that this instruction is virtually using the PHI node
1058           // operands.
1059           UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1060           UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1061           return;
1062         }
1063         
1064         if (Result.isUndefined())
1065           return;
1066
1067         // Okay, this really is overdefined now.  Since we might have
1068         // speculatively thought that this was not overdefined before, and
1069         // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1070         // make sure to clean out any entries that we put there, for
1071         // efficiency.
1072         RemoveFromOverdefinedPHIs(&I, PN1);
1073         RemoveFromOverdefinedPHIs(&I, PN2);
1074       }
1075
1076   markOverdefined(&I);
1077 }
1078
1079 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1080   // TODO : SCCP does not handle vectors properly.
1081   return markOverdefined(&I);
1082
1083 #if 0
1084   LatticeVal &ValState = getValueState(I.getOperand(0));
1085   LatticeVal &IdxState = getValueState(I.getOperand(1));
1086
1087   if (ValState.isOverdefined() || IdxState.isOverdefined())
1088     markOverdefined(&I);
1089   else if(ValState.isConstant() && IdxState.isConstant())
1090     markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1091                                                      IdxState.getConstant()));
1092 #endif
1093 }
1094
1095 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1096   // TODO : SCCP does not handle vectors properly.
1097   return markOverdefined(&I);
1098 #if 0
1099   LatticeVal &ValState = getValueState(I.getOperand(0));
1100   LatticeVal &EltState = getValueState(I.getOperand(1));
1101   LatticeVal &IdxState = getValueState(I.getOperand(2));
1102
1103   if (ValState.isOverdefined() || EltState.isOverdefined() ||
1104       IdxState.isOverdefined())
1105     markOverdefined(&I);
1106   else if(ValState.isConstant() && EltState.isConstant() &&
1107           IdxState.isConstant())
1108     markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1109                                                     EltState.getConstant(),
1110                                                     IdxState.getConstant()));
1111   else if (ValState.isUndefined() && EltState.isConstant() &&
1112            IdxState.isConstant()) 
1113     markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1114                                                    EltState.getConstant(),
1115                                                    IdxState.getConstant()));
1116 #endif
1117 }
1118
1119 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1120   // TODO : SCCP does not handle vectors properly.
1121   return markOverdefined(&I);
1122 #if 0
1123   LatticeVal &V1State   = getValueState(I.getOperand(0));
1124   LatticeVal &V2State   = getValueState(I.getOperand(1));
1125   LatticeVal &MaskState = getValueState(I.getOperand(2));
1126
1127   if (MaskState.isUndefined() ||
1128       (V1State.isUndefined() && V2State.isUndefined()))
1129     return;  // Undefined output if mask or both inputs undefined.
1130   
1131   if (V1State.isOverdefined() || V2State.isOverdefined() ||
1132       MaskState.isOverdefined()) {
1133     markOverdefined(&I);
1134   } else {
1135     // A mix of constant/undef inputs.
1136     Constant *V1 = V1State.isConstant() ? 
1137         V1State.getConstant() : UndefValue::get(I.getType());
1138     Constant *V2 = V2State.isConstant() ? 
1139         V2State.getConstant() : UndefValue::get(I.getType());
1140     Constant *Mask = MaskState.isConstant() ? 
1141       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1142     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1143   }
1144 #endif
1145 }
1146
1147 // Handle getelementptr instructions.  If all operands are constants then we
1148 // can turn this into a getelementptr ConstantExpr.
1149 //
1150 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1151   if (ValueState[&I].isOverdefined()) return;
1152
1153   SmallVector<Constant*, 8> Operands;
1154   Operands.reserve(I.getNumOperands());
1155
1156   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1157     LatticeVal State = getValueState(I.getOperand(i));
1158     if (State.isUndefined())
1159       return;  // Operands are not resolved yet.
1160     
1161     if (State.isOverdefined())
1162       return markOverdefined(&I);
1163
1164     assert(State.isConstant() && "Unknown state!");
1165     Operands.push_back(State.getConstant());
1166   }
1167
1168   Constant *Ptr = Operands[0];
1169   markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1170                                                   Operands.size()-1));
1171 }
1172
1173 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1174   // If this store is of a struct, ignore it.
1175   if (SI.getOperand(0)->getType()->isStructTy())
1176     return;
1177   
1178   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1179     return;
1180   
1181   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1182   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1183   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1184
1185   // Get the value we are storing into the global, then merge it.
1186   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1187   if (I->second.isOverdefined())
1188     TrackedGlobals.erase(I);      // No need to keep tracking this!
1189 }
1190
1191
1192 // Handle load instructions.  If the operand is a constant pointer to a constant
1193 // global, we can replace the load with the loaded constant value!
1194 void SCCPSolver::visitLoadInst(LoadInst &I) {
1195   // If this load is of a struct, just mark the result overdefined.
1196   if (I.getType()->isStructTy())
1197     return markAnythingOverdefined(&I);
1198   
1199   LatticeVal PtrVal = getValueState(I.getOperand(0));
1200   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
1201   
1202   LatticeVal &IV = ValueState[&I];
1203   if (IV.isOverdefined()) return;
1204
1205   if (!PtrVal.isConstant() || I.isVolatile())
1206     return markOverdefined(IV, &I);
1207     
1208   Constant *Ptr = PtrVal.getConstant();
1209
1210   // load null -> null
1211   if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1212     return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1213   
1214   // Transform load (constant global) into the value loaded.
1215   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1216     if (!TrackedGlobals.empty()) {
1217       // If we are tracking this global, merge in the known value for it.
1218       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1219         TrackedGlobals.find(GV);
1220       if (It != TrackedGlobals.end()) {
1221         mergeInValue(IV, &I, It->second);
1222         return;
1223       }
1224     }
1225   }
1226
1227   // Transform load from a constant into a constant if possible.
1228   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1229     return markConstant(IV, &I, C);
1230
1231   // Otherwise we cannot say for certain what value this load will produce.
1232   // Bail out.
1233   markOverdefined(IV, &I);
1234 }
1235
1236 void SCCPSolver::visitCallSite(CallSite CS) {
1237   Function *F = CS.getCalledFunction();
1238   Instruction *I = CS.getInstruction();
1239   
1240   // The common case is that we aren't tracking the callee, either because we
1241   // are not doing interprocedural analysis or the callee is indirect, or is
1242   // external.  Handle these cases first.
1243   if (F == 0 || F->isDeclaration()) {
1244 CallOverdefined:
1245     // Void return and not tracking callee, just bail.
1246     if (I->getType()->isVoidTy()) return;
1247     
1248     // Otherwise, if we have a single return value case, and if the function is
1249     // a declaration, maybe we can constant fold it.
1250     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1251         canConstantFoldCallTo(F)) {
1252       
1253       SmallVector<Constant*, 8> Operands;
1254       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1255            AI != E; ++AI) {
1256         LatticeVal State = getValueState(*AI);
1257         
1258         if (State.isUndefined())
1259           return;  // Operands are not resolved yet.
1260         if (State.isOverdefined())
1261           return markOverdefined(I);
1262         assert(State.isConstant() && "Unknown state!");
1263         Operands.push_back(State.getConstant());
1264       }
1265      
1266       // If we can constant fold this, mark the result of the call as a
1267       // constant.
1268       if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1269         return markConstant(I, C);
1270     }
1271
1272     // Otherwise, we don't know anything about this call, mark it overdefined.
1273     return markAnythingOverdefined(I);
1274   }
1275
1276   // If this is a local function that doesn't have its address taken, mark its
1277   // entry block executable and merge in the actual arguments to the call into
1278   // the formal arguments of the function.
1279   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1280     MarkBlockExecutable(F->begin());
1281     
1282     // Propagate information from this call site into the callee.
1283     CallSite::arg_iterator CAI = CS.arg_begin();
1284     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1285          AI != E; ++AI, ++CAI) {
1286       // If this argument is byval, and if the function is not readonly, there
1287       // will be an implicit copy formed of the input aggregate.
1288       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1289         markOverdefined(AI);
1290         continue;
1291       }
1292       
1293       if (const StructType *STy = dyn_cast<StructType>(AI->getType())) {
1294         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1295           LatticeVal CallArg = getStructValueState(*CAI, i);
1296           mergeInValue(getStructValueState(AI, i), AI, CallArg);
1297         }
1298       } else {
1299         mergeInValue(AI, getValueState(*CAI));
1300       }
1301     }
1302   }
1303   
1304   // If this is a single/zero retval case, see if we're tracking the function.
1305   if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1306     if (!MRVFunctionsTracked.count(F))
1307       goto CallOverdefined;  // Not tracking this callee.
1308     
1309     // If we are tracking this callee, propagate the result of the function
1310     // into this call site.
1311     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1312       mergeInValue(getStructValueState(I, i), I, 
1313                    TrackedMultipleRetVals[std::make_pair(F, i)]);
1314   } else {
1315     DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1316     if (TFRVI == TrackedRetVals.end())
1317       goto CallOverdefined;  // Not tracking this callee.
1318       
1319     // If so, propagate the return value of the callee into this call result.
1320     mergeInValue(I, TFRVI->second);
1321   }
1322 }
1323
1324 void SCCPSolver::Solve() {
1325   // Process the work lists until they are empty!
1326   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1327          !OverdefinedInstWorkList.empty()) {
1328     // Process the overdefined instruction's work list first, which drives other
1329     // things to overdefined more quickly.
1330     while (!OverdefinedInstWorkList.empty()) {
1331       Value *I = OverdefinedInstWorkList.pop_back_val();
1332
1333       DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1334
1335       // "I" got into the work list because it either made the transition from
1336       // bottom to constant
1337       //
1338       // Anything on this worklist that is overdefined need not be visited
1339       // since all of its users will have already been marked as overdefined
1340       // Update all of the users of this instruction's value.
1341       //
1342       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1343            UI != E; ++UI)
1344         if (Instruction *I = dyn_cast<Instruction>(*UI))
1345           OperandChangedState(I);
1346     }
1347     
1348     // Process the instruction work list.
1349     while (!InstWorkList.empty()) {
1350       Value *I = InstWorkList.pop_back_val();
1351
1352       DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1353
1354       // "I" got into the work list because it made the transition from undef to
1355       // constant.
1356       //
1357       // Anything on this worklist that is overdefined need not be visited
1358       // since all of its users will have already been marked as overdefined.
1359       // Update all of the users of this instruction's value.
1360       //
1361       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1362         for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1363              UI != E; ++UI)
1364           if (Instruction *I = dyn_cast<Instruction>(*UI))
1365             OperandChangedState(I);
1366     }
1367
1368     // Process the basic block work list.
1369     while (!BBWorkList.empty()) {
1370       BasicBlock *BB = BBWorkList.back();
1371       BBWorkList.pop_back();
1372
1373       DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1374
1375       // Notify all instructions in this basic block that they are newly
1376       // executable.
1377       visit(BB);
1378     }
1379   }
1380 }
1381
1382 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1383 /// that branches on undef values cannot reach any of their successors.
1384 /// However, this is not a safe assumption.  After we solve dataflow, this
1385 /// method should be use to handle this.  If this returns true, the solver
1386 /// should be rerun.
1387 ///
1388 /// This method handles this by finding an unresolved branch and marking it one
1389 /// of the edges from the block as being feasible, even though the condition
1390 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1391 /// CFG and only slightly pessimizes the analysis results (by marking one,
1392 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1393 /// constraints on the condition of the branch, as that would impact other users
1394 /// of the value.
1395 ///
1396 /// This scan also checks for values that use undefs, whose results are actually
1397 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
1398 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1399 /// even if X isn't defined.
1400 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1401   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1402     if (!BBExecutable.count(BB))
1403       continue;
1404     
1405     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1406       // Look for instructions which produce undef values.
1407       if (I->getType()->isVoidTy()) continue;
1408       
1409       if (const StructType *STy = dyn_cast<StructType>(I->getType())) {
1410         // Only a few things that can be structs matter for undef.  Just send
1411         // all their results to overdefined.  We could be more precise than this
1412         // but it isn't worth bothering.
1413         if (isa<CallInst>(I) || isa<SelectInst>(I)) {
1414           for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1415             LatticeVal &LV = getStructValueState(I, i);
1416             if (LV.isUndefined())
1417               markOverdefined(LV, I);
1418           }
1419         }
1420         continue;
1421       }
1422       
1423       LatticeVal &LV = getValueState(I);
1424       if (!LV.isUndefined()) continue;
1425
1426       // No instructions using structs need disambiguation.
1427       if (I->getOperand(0)->getType()->isStructTy())
1428         continue;
1429
1430       // Get the lattice values of the first two operands for use below.
1431       LatticeVal Op0LV = getValueState(I->getOperand(0));
1432       LatticeVal Op1LV;
1433       if (I->getNumOperands() == 2) {
1434         // No instructions using structs need disambiguation.
1435         if (I->getOperand(1)->getType()->isStructTy())
1436           continue;
1437         
1438         // If this is a two-operand instruction, and if both operands are
1439         // undefs, the result stays undef.
1440         Op1LV = getValueState(I->getOperand(1));
1441         if (Op0LV.isUndefined() && Op1LV.isUndefined())
1442           continue;
1443       }
1444       
1445       // If this is an instructions whose result is defined even if the input is
1446       // not fully defined, propagate the information.
1447       const Type *ITy = I->getType();
1448       switch (I->getOpcode()) {
1449       default: break;          // Leave the instruction as an undef.
1450       case Instruction::ZExt:
1451         // After a zero extend, we know the top part is zero.  SExt doesn't have
1452         // to be handled here, because we don't know whether the top part is 1's
1453         // or 0's.
1454       case Instruction::SIToFP:  // some FP values are not possible, just use 0.
1455       case Instruction::UIToFP:  // some FP values are not possible, just use 0.
1456         markForcedConstant(I, Constant::getNullValue(ITy));
1457         return true;
1458       case Instruction::Mul:
1459       case Instruction::And:
1460         // undef * X -> 0.   X could be zero.
1461         // undef & X -> 0.   X could be zero.
1462         markForcedConstant(I, Constant::getNullValue(ITy));
1463         return true;
1464
1465       case Instruction::Or:
1466         // undef | X -> -1.   X could be -1.
1467         markForcedConstant(I, Constant::getAllOnesValue(ITy));
1468         return true;
1469
1470       case Instruction::SDiv:
1471       case Instruction::UDiv:
1472       case Instruction::SRem:
1473       case Instruction::URem:
1474         // X / undef -> undef.  No change.
1475         // X % undef -> undef.  No change.
1476         if (Op1LV.isUndefined()) break;
1477         
1478         // undef / X -> 0.   X could be maxint.
1479         // undef % X -> 0.   X could be 1.
1480         markForcedConstant(I, Constant::getNullValue(ITy));
1481         return true;
1482         
1483       case Instruction::AShr:
1484         // undef >>s X -> undef.  No change.
1485         if (Op0LV.isUndefined()) break;
1486         
1487         // X >>s undef -> X.  X could be 0, X could have the high-bit known set.
1488         if (Op0LV.isConstant())
1489           markForcedConstant(I, Op0LV.getConstant());
1490         else
1491           markOverdefined(I);
1492         return true;
1493       case Instruction::LShr:
1494       case Instruction::Shl:
1495         // undef >> X -> undef.  No change.
1496         // undef << X -> undef.  No change.
1497         if (Op0LV.isUndefined()) break;
1498         
1499         // X >> undef -> 0.  X could be 0.
1500         // X << undef -> 0.  X could be 0.
1501         markForcedConstant(I, Constant::getNullValue(ITy));
1502         return true;
1503       case Instruction::Select:
1504         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
1505         if (Op0LV.isUndefined()) {
1506           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
1507             Op1LV = getValueState(I->getOperand(2));
1508         } else if (Op1LV.isUndefined()) {
1509           // c ? undef : undef -> undef.  No change.
1510           Op1LV = getValueState(I->getOperand(2));
1511           if (Op1LV.isUndefined())
1512             break;
1513           // Otherwise, c ? undef : x -> x.
1514         } else {
1515           // Leave Op1LV as Operand(1)'s LatticeValue.
1516         }
1517         
1518         if (Op1LV.isConstant())
1519           markForcedConstant(I, Op1LV.getConstant());
1520         else
1521           markOverdefined(I);
1522         return true;
1523       case Instruction::Call:
1524         // If a call has an undef result, it is because it is constant foldable
1525         // but one of the inputs was undef.  Just force the result to
1526         // overdefined.
1527         markOverdefined(I);
1528         return true;
1529       }
1530     }
1531   
1532     // Check to see if we have a branch or switch on an undefined value.  If so
1533     // we force the branch to go one way or the other to make the successor
1534     // values live.  It doesn't really matter which way we force it.
1535     TerminatorInst *TI = BB->getTerminator();
1536     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1537       if (!BI->isConditional()) continue;
1538       if (!getValueState(BI->getCondition()).isUndefined())
1539         continue;
1540     
1541       // If the input to SCCP is actually branch on undef, fix the undef to
1542       // false.
1543       if (isa<UndefValue>(BI->getCondition())) {
1544         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1545         markEdgeExecutable(BB, TI->getSuccessor(1));
1546         return true;
1547       }
1548       
1549       // Otherwise, it is a branch on a symbolic value which is currently
1550       // considered to be undef.  Handle this by forcing the input value to the
1551       // branch to false.
1552       markForcedConstant(BI->getCondition(),
1553                          ConstantInt::getFalse(TI->getContext()));
1554       return true;
1555     }
1556     
1557     if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1558       if (SI->getNumSuccessors() < 2)   // no cases
1559         continue;
1560       if (!getValueState(SI->getCondition()).isUndefined())
1561         continue;
1562       
1563       // If the input to SCCP is actually switch on undef, fix the undef to
1564       // the first constant.
1565       if (isa<UndefValue>(SI->getCondition())) {
1566         SI->setCondition(SI->getCaseValue(1));
1567         markEdgeExecutable(BB, TI->getSuccessor(1));
1568         return true;
1569       }
1570       
1571       markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1572       return true;
1573     }
1574   }
1575
1576   return false;
1577 }
1578
1579
1580 namespace {
1581   //===--------------------------------------------------------------------===//
1582   //
1583   /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1584   /// Sparse Conditional Constant Propagator.
1585   ///
1586   struct SCCP : public FunctionPass {
1587     static char ID; // Pass identification, replacement for typeid
1588     SCCP() : FunctionPass(ID) {
1589       initializeSCCPPass(*PassRegistry::getPassRegistry());
1590     }
1591
1592     // runOnFunction - Run the Sparse Conditional Constant Propagation
1593     // algorithm, and return true if the function was modified.
1594     //
1595     bool runOnFunction(Function &F);
1596
1597     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1598       AU.setPreservesCFG();
1599     }
1600   };
1601 } // end anonymous namespace
1602
1603 char SCCP::ID = 0;
1604 INITIALIZE_PASS(SCCP, "sccp",
1605                 "Sparse Conditional Constant Propagation", false, false)
1606
1607 // createSCCPPass - This is the public interface to this file.
1608 FunctionPass *llvm::createSCCPPass() {
1609   return new SCCP();
1610 }
1611
1612 static void DeleteInstructionInBlock(BasicBlock *BB) {
1613   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
1614   ++NumDeadBlocks;
1615   
1616   // Delete the instructions backwards, as it has a reduced likelihood of
1617   // having to update as many def-use and use-def chains.
1618   while (!isa<TerminatorInst>(BB->begin())) {
1619     Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1620     
1621     if (!I->use_empty())
1622       I->replaceAllUsesWith(UndefValue::get(I->getType()));
1623     BB->getInstList().erase(I);
1624     ++NumInstRemoved;
1625   }
1626 }
1627
1628 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1629 // and return true if the function was modified.
1630 //
1631 bool SCCP::runOnFunction(Function &F) {
1632   DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1633   SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1634
1635   // Mark the first block of the function as being executable.
1636   Solver.MarkBlockExecutable(F.begin());
1637
1638   // Mark all arguments to the function as being overdefined.
1639   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1640     Solver.markAnythingOverdefined(AI);
1641
1642   // Solve for constants.
1643   bool ResolvedUndefs = true;
1644   while (ResolvedUndefs) {
1645     Solver.Solve();
1646     DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1647     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1648   }
1649
1650   bool MadeChanges = false;
1651
1652   // If we decided that there are basic blocks that are dead in this function,
1653   // delete their contents now.  Note that we cannot actually delete the blocks,
1654   // as we cannot modify the CFG of the function.
1655
1656   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1657     if (!Solver.isBlockExecutable(BB)) {
1658       DeleteInstructionInBlock(BB);
1659       MadeChanges = true;
1660       continue;
1661     }
1662   
1663     // Iterate over all of the instructions in a function, replacing them with
1664     // constants if we have found them to be of constant values.
1665     //
1666     for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1667       Instruction *Inst = BI++;
1668       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1669         continue;
1670       
1671       // TODO: Reconstruct structs from their elements.
1672       if (Inst->getType()->isStructTy())
1673         continue;
1674       
1675       LatticeVal IV = Solver.getLatticeValueFor(Inst);
1676       if (IV.isOverdefined())
1677         continue;
1678       
1679       Constant *Const = IV.isConstant()
1680         ? IV.getConstant() : UndefValue::get(Inst->getType());
1681       DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst);
1682
1683       // Replaces all of the uses of a variable with uses of the constant.
1684       Inst->replaceAllUsesWith(Const);
1685       
1686       // Delete the instruction.
1687       Inst->eraseFromParent();
1688       
1689       // Hey, we just changed something!
1690       MadeChanges = true;
1691       ++NumInstRemoved;
1692     }
1693   }
1694
1695   return MadeChanges;
1696 }
1697
1698 namespace {
1699   //===--------------------------------------------------------------------===//
1700   //
1701   /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1702   /// Constant Propagation.
1703   ///
1704   struct IPSCCP : public ModulePass {
1705     static char ID;
1706     IPSCCP() : ModulePass(ID) {
1707       initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1708     }
1709     bool runOnModule(Module &M);
1710   };
1711 } // end anonymous namespace
1712
1713 char IPSCCP::ID = 0;
1714 INITIALIZE_PASS(IPSCCP, "ipsccp",
1715                 "Interprocedural Sparse Conditional Constant Propagation",
1716                 false, false)
1717
1718 // createIPSCCPPass - This is the public interface to this file.
1719 ModulePass *llvm::createIPSCCPPass() {
1720   return new IPSCCP();
1721 }
1722
1723
1724 static bool AddressIsTaken(const GlobalValue *GV) {
1725   // Delete any dead constantexpr klingons.
1726   GV->removeDeadConstantUsers();
1727
1728   for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1729        UI != E; ++UI) {
1730     const User *U = *UI;
1731     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
1732       if (SI->getOperand(0) == GV || SI->isVolatile())
1733         return true;  // Storing addr of GV.
1734     } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
1735       // Make sure we are calling the function, not passing the address.
1736       ImmutableCallSite CS(cast<Instruction>(U));
1737       if (!CS.isCallee(UI))
1738         return true;
1739     } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1740       if (LI->isVolatile())
1741         return true;
1742     } else if (isa<BlockAddress>(U)) {
1743       // blockaddress doesn't take the address of the function, it takes addr
1744       // of label.
1745     } else {
1746       return true;
1747     }
1748   }
1749   return false;
1750 }
1751
1752 bool IPSCCP::runOnModule(Module &M) {
1753   SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1754
1755   // AddressTakenFunctions - This set keeps track of the address-taken functions
1756   // that are in the input.  As IPSCCP runs through and simplifies code,
1757   // functions that were address taken can end up losing their
1758   // address-taken-ness.  Because of this, we keep track of their addresses from
1759   // the first pass so we can use them for the later simplification pass.
1760   SmallPtrSet<Function*, 32> AddressTakenFunctions;
1761   
1762   // Loop over all functions, marking arguments to those with their addresses
1763   // taken or that are external as overdefined.
1764   //
1765   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1766     if (F->isDeclaration())
1767       continue;
1768     
1769     // If this is a strong or ODR definition of this function, then we can
1770     // propagate information about its result into callsites of it.
1771     if (!F->mayBeOverridden())
1772       Solver.AddTrackedFunction(F);
1773     
1774     // If this function only has direct calls that we can see, we can track its
1775     // arguments and return value aggressively, and can assume it is not called
1776     // unless we see evidence to the contrary.
1777     if (F->hasLocalLinkage()) {
1778       if (AddressIsTaken(F))
1779         AddressTakenFunctions.insert(F);
1780       else {
1781         Solver.AddArgumentTrackedFunction(F);
1782         continue;
1783       }
1784     }
1785
1786     // Assume the function is called.
1787     Solver.MarkBlockExecutable(F->begin());
1788     
1789     // Assume nothing about the incoming arguments.
1790     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1791          AI != E; ++AI)
1792       Solver.markAnythingOverdefined(AI);
1793   }
1794
1795   // Loop over global variables.  We inform the solver about any internal global
1796   // variables that do not have their 'addresses taken'.  If they don't have
1797   // their addresses taken, we can propagate constants through them.
1798   for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1799        G != E; ++G)
1800     if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1801       Solver.TrackValueOfGlobalVariable(G);
1802
1803   // Solve for constants.
1804   bool ResolvedUndefs = true;
1805   while (ResolvedUndefs) {
1806     Solver.Solve();
1807
1808     DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1809     ResolvedUndefs = false;
1810     for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1811       ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1812   }
1813
1814   bool MadeChanges = false;
1815
1816   // Iterate over all of the instructions in the module, replacing them with
1817   // constants if we have found them to be of constant values.
1818   //
1819   SmallVector<BasicBlock*, 512> BlocksToErase;
1820
1821   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1822     if (Solver.isBlockExecutable(F->begin())) {
1823       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1824            AI != E; ++AI) {
1825         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1826         
1827         // TODO: Could use getStructLatticeValueFor to find out if the entire
1828         // result is a constant and replace it entirely if so.
1829
1830         LatticeVal IV = Solver.getLatticeValueFor(AI);
1831         if (IV.isOverdefined()) continue;
1832         
1833         Constant *CST = IV.isConstant() ?
1834         IV.getConstant() : UndefValue::get(AI->getType());
1835         DEBUG(dbgs() << "***  Arg " << *AI << " = " << *CST <<"\n");
1836         
1837         // Replaces all of the uses of a variable with uses of the
1838         // constant.
1839         AI->replaceAllUsesWith(CST);
1840         ++IPNumArgsElimed;
1841       }
1842     }
1843
1844     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1845       if (!Solver.isBlockExecutable(BB)) {
1846         DeleteInstructionInBlock(BB);
1847         MadeChanges = true;
1848
1849         TerminatorInst *TI = BB->getTerminator();
1850         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1851           BasicBlock *Succ = TI->getSuccessor(i);
1852           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1853             TI->getSuccessor(i)->removePredecessor(BB);
1854         }
1855         if (!TI->use_empty())
1856           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1857         TI->eraseFromParent();
1858
1859         if (&*BB != &F->front())
1860           BlocksToErase.push_back(BB);
1861         else
1862           new UnreachableInst(M.getContext(), BB);
1863         continue;
1864       }
1865       
1866       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1867         Instruction *Inst = BI++;
1868         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1869           continue;
1870         
1871         // TODO: Could use getStructLatticeValueFor to find out if the entire
1872         // result is a constant and replace it entirely if so.
1873         
1874         LatticeVal IV = Solver.getLatticeValueFor(Inst);
1875         if (IV.isOverdefined())
1876           continue;
1877         
1878         Constant *Const = IV.isConstant()
1879           ? IV.getConstant() : UndefValue::get(Inst->getType());
1880         DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst);
1881
1882         // Replaces all of the uses of a variable with uses of the
1883         // constant.
1884         Inst->replaceAllUsesWith(Const);
1885         
1886         // Delete the instruction.
1887         if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1888           Inst->eraseFromParent();
1889
1890         // Hey, we just changed something!
1891         MadeChanges = true;
1892         ++IPNumInstRemoved;
1893       }
1894     }
1895
1896     // Now that all instructions in the function are constant folded, erase dead
1897     // blocks, because we can now use ConstantFoldTerminator to get rid of
1898     // in-edges.
1899     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1900       // If there are any PHI nodes in this successor, drop entries for BB now.
1901       BasicBlock *DeadBB = BlocksToErase[i];
1902       for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1903            UI != UE; ) {
1904         // Grab the user and then increment the iterator early, as the user
1905         // will be deleted. Step past all adjacent uses from the same user.
1906         Instruction *I = dyn_cast<Instruction>(*UI);
1907         do { ++UI; } while (UI != UE && *UI == I);
1908
1909         // Ignore blockaddress users; BasicBlock's dtor will handle them.
1910         if (!I) continue;
1911
1912         bool Folded = ConstantFoldTerminator(I->getParent());
1913         if (!Folded) {
1914           // The constant folder may not have been able to fold the terminator
1915           // if this is a branch or switch on undef.  Fold it manually as a
1916           // branch to the first successor.
1917 #ifndef NDEBUG
1918           if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1919             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1920                    "Branch should be foldable!");
1921           } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1922             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1923           } else {
1924             llvm_unreachable("Didn't fold away reference to block!");
1925           }
1926 #endif
1927           
1928           // Make this an uncond branch to the first successor.
1929           TerminatorInst *TI = I->getParent()->getTerminator();
1930           BranchInst::Create(TI->getSuccessor(0), TI);
1931           
1932           // Remove entries in successor phi nodes to remove edges.
1933           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1934             TI->getSuccessor(i)->removePredecessor(TI->getParent());
1935           
1936           // Remove the old terminator.
1937           TI->eraseFromParent();
1938         }
1939       }
1940
1941       // Finally, delete the basic block.
1942       F->getBasicBlockList().erase(DeadBB);
1943     }
1944     BlocksToErase.clear();
1945   }
1946
1947   // If we inferred constant or undef return values for a function, we replaced
1948   // all call uses with the inferred value.  This means we don't need to bother
1949   // actually returning anything from the function.  Replace all return
1950   // instructions with return undef.
1951   //
1952   // Do this in two stages: first identify the functions we should process, then
1953   // actually zap their returns.  This is important because we can only do this
1954   // if the address of the function isn't taken.  In cases where a return is the
1955   // last use of a function, the order of processing functions would affect
1956   // whether other functions are optimizable.
1957   SmallVector<ReturnInst*, 8> ReturnsToZap;
1958   
1959   // TODO: Process multiple value ret instructions also.
1960   const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1961   for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1962        E = RV.end(); I != E; ++I) {
1963     Function *F = I->first;
1964     if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1965       continue;
1966   
1967     // We can only do this if we know that nothing else can call the function.
1968     if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1969       continue;
1970     
1971     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1972       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1973         if (!isa<UndefValue>(RI->getOperand(0)))
1974           ReturnsToZap.push_back(RI);
1975   }
1976
1977   // Zap all returns which we've identified as zap to change.
1978   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1979     Function *F = ReturnsToZap[i]->getParent()->getParent();
1980     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1981   }
1982     
1983   // If we infered constant or undef values for globals variables, we can delete
1984   // the global and any stores that remain to it.
1985   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1986   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1987          E = TG.end(); I != E; ++I) {
1988     GlobalVariable *GV = I->first;
1989     assert(!I->second.isOverdefined() &&
1990            "Overdefined values should have been taken out of the map!");
1991     DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1992     while (!GV->use_empty()) {
1993       StoreInst *SI = cast<StoreInst>(GV->use_back());
1994       SI->eraseFromParent();
1995     }
1996     M.getGlobalList().erase(GV);
1997     ++IPNumGlobalConst;
1998   }
1999
2000   return MadeChanges;
2001 }