blob: b15df2acaa7dd8d55a25c3793e9166aa029e90cc [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018//===----------------------------------------------------------------------===//
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"
Dan Gohman856193b2008-06-20 01:15:44 +000028#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0148bb22009-11-02 06:06:14 +000030#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattner1eb405b2009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Chris Lattnera5ffa7c2009-11-02 06:11:23 +000039#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
43#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000044#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045using namespace llvm;
46
47STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
54namespace {
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///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattner1eb405b2009-11-02 02:20:32 +000059 enum LatticeValueTy {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060 /// 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
Chris Lattner1eb405b2009-11-02 02:20:32 +000075 };
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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080
Chris Lattner1eb405b2009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085public:
Chris Lattnerb52f7002009-11-02 03:03:42 +000086 LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087
Chris Lattnerb52f7002009-11-02 03:03:42 +000088 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000090 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
Chris Lattnerb52f7002009-11-02 03:03:42 +000092 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner1eb405b2009-11-02 02:20:32 +000093
Chris Lattnerb52f7002009-11-02 03:03:42 +000094 Constant *getConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000095 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.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000100 bool markOverdefined() {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 }
107
Chris Lattner1eb405b2009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000109 bool markConstant(Constant *V) {
Chris Lattner8d2a9ca2009-11-03 16:50:11 +0000110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattner1eb405b2009-11-02 02:20:32 +0000111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 }
Chris Lattner1eb405b2009-11-02 02:20:32 +0000114
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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 }
132
Chris Lattner220571c2009-11-02 03:21:36 +0000133 /// 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
Chris Lattnerb52f7002009-11-02 03:03:42 +0000141 void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
144 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 }
146};
Chris Lattner14513dc2009-11-02 02:47:51 +0000147} // end anonymous namespace.
148
149
150namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152//===----------------------------------------------------------------------===//
153//
154/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155/// Constant Propagation.
156///
157class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner0148bb22009-11-02 06:06:14 +0000158 const TargetData *TD;
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000159 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000162 /// 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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 /// 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
Devang Pateladd320d2008-03-11 05:46:42 +0000173 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 /// value out of a function, it will have an entry in this map, indicating
175 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000176 DenseMap<Function*, LatticeVal> TrackedRetVals;
177
178 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000181
182 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183 /// represented here for efficient lookup.
184 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185
Chris Lattnera5b4c332009-11-03 20:52:57 +0000186 /// TrackingIncomingArguments - This is the set of functions for whose
187 /// arguments we make optimistic assumptions about and try to prove as
188 /// constants.
Chris Lattner59dc8e62009-11-03 19:24:51 +0000189 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
190
Chris Lattnerb52f7002009-11-02 03:03:42 +0000191 /// 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.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000198 SmallVector<Value*, 64> OverdefinedInstWorkList;
199 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200
201
Chris Lattnerd3123a72008-08-23 23:36:38 +0000202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203
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.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000210 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
211 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212public:
Chris Lattner0148bb22009-11-02 06:06:14 +0000213 SCCPSolver(const TargetData *td) : TD(td) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214
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.
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000217 ///
218 /// This returns true if the block was not considered live before.
219 bool MarkBlockExecutable(BasicBlock *BB) {
220 if (!BBExecutable.insert(BB)) return false;
David Greenedbf1d5a2010-01-05 01:27:15 +0000221 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000223 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 }
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) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000231 // We only track the contents of scalar globals.
232 if (GV->getType()->getElementType()->isSingleValueType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 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) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000244 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000245 MRVFunctionsTracked.insert(F);
Devang Pateladd320d2008-03-11 05:46:42 +0000246 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000247 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
248 LatticeVal()));
249 } else
250 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 }
252
Chris Lattner59dc8e62009-11-03 19:24:51 +0000253 void AddArgumentTrackedFunction(Function *F) {
254 TrackingIncomingArguments.insert(F);
255 }
256
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 /// 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
Chris Lattner317e6b62008-08-23 23:39:31 +0000268 bool isBlockExecutable(BasicBlock *BB) const {
269 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 }
271
Chris Lattnerc9edab82009-11-02 02:54:24 +0000272 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000273 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerc9edab82009-11-02 02:54:24 +0000274 assert(I != ValueState.end() && "V is not in valuemap!");
275 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 }
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000277
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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284
Devang Pateladd320d2008-03-11 05:46:42 +0000285 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000287 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
288 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 }
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
Chris Lattner220571c2009-11-02 03:21:36 +0000297 void markOverdefined(Value *V) {
Duncan Sands10343d92010-02-16 11:11:14 +0000298 assert(!V->getType()->isStructTy() && "Should use other method");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 markOverdefined(ValueState[V], V);
300 }
301
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000302 /// 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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312private:
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 //
Chris Lattnerb52f7002009-11-02 03:03:42 +0000317 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
318 if (!IV.markConstant(C)) return;
David Greenedbf1d5a2010-01-05 01:27:15 +0000319 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattnerb52f7002009-11-02 03:03:42 +0000320 InstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 }
322
Chris Lattnerb52f7002009-11-02 03:03:42 +0000323 void markConstant(Value *V, Constant *C) {
Duncan Sands10343d92010-02-16 11:11:14 +0000324 assert(!V->getType()->isStructTy() && "Should use other method");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 markConstant(ValueState[V], V, C);
326 }
327
Chris Lattner6367c3f2009-11-02 05:55:40 +0000328 void markForcedConstant(Value *V, Constant *C) {
Duncan Sands10343d92010-02-16 11:11:14 +0000329 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner6367c3f2009-11-02 05:55:40 +0000330 ValueState[V].markForcedConstant(C);
David Greenedbf1d5a2010-01-05 01:27:15 +0000331 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner6367c3f2009-11-02 05:55:40 +0000332 InstWorkList.push_back(V);
333 }
334
335
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 // markOverdefined - Make a value be marked as "overdefined". If the
337 // value is not already overdefined, add it to the overdefined instruction
338 // work list so that the users of the instruction are updated later.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000339 void markOverdefined(LatticeVal &IV, Value *V) {
340 if (!IV.markOverdefined()) return;
341
David Greenedbf1d5a2010-01-05 01:27:15 +0000342 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattnerb52f7002009-11-02 03:03:42 +0000343 if (Function *F = dyn_cast<Function>(V))
David Greenedbf1d5a2010-01-05 01:27:15 +0000344 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattnerb52f7002009-11-02 03:03:42 +0000345 else
David Greenedbf1d5a2010-01-05 01:27:15 +0000346 dbgs() << *V << '\n');
Chris Lattnerb52f7002009-11-02 03:03:42 +0000347 // Only instructions go on the work list
348 OverdefinedInstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 }
350
Chris Lattner6367c3f2009-11-02 05:55:40 +0000351 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 if (IV.isOverdefined() || MergeWithV.isUndefined())
353 return; // Noop.
354 if (MergeWithV.isOverdefined())
355 markOverdefined(IV, V);
356 else if (IV.isUndefined())
357 markConstant(IV, V, MergeWithV.getConstant());
358 else if (IV.getConstant() != MergeWithV.getConstant())
359 markOverdefined(IV, V);
360 }
361
Chris Lattner6367c3f2009-11-02 05:55:40 +0000362 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Duncan Sands10343d92010-02-16 11:11:14 +0000363 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner220571c2009-11-02 03:21:36 +0000364 mergeInValue(ValueState[V], V, MergeWithV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 }
366
367
Chris Lattner6367c3f2009-11-02 05:55:40 +0000368 /// getValueState - Return the LatticeVal object that corresponds to the
369 /// value. This function handles the case when the value hasn't been seen yet
370 /// by properly seeding constants etc.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000371 LatticeVal &getValueState(Value *V) {
Duncan Sands10343d92010-02-16 11:11:14 +0000372 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373
Benjamin Kramer329f7ba2009-11-05 14:33:27 +0000374 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
375 ValueState.insert(std::make_pair(V, LatticeVal()));
376 LatticeVal &LV = I.first->second;
377
378 if (!I.second)
379 return LV; // Common case, already in the map.
Chris Lattner220571c2009-11-02 03:21:36 +0000380
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner220571c2009-11-02 03:21:36 +0000382 // Undef values remain undefined.
383 if (!isa<UndefValue>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 LV.markConstant(C); // Constants are constant
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 }
Chris Lattner220571c2009-11-02 03:21:36 +0000386
Chris Lattnerc8798002009-11-02 02:33:50 +0000387 // All others are underdefined by default.
Chris Lattner220571c2009-11-02 03:21:36 +0000388 return LV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 }
390
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000391 /// getStructValueState - Return the LatticeVal object that corresponds to the
392 /// value/field pair. This function handles the case when the value hasn't
393 /// been seen yet by properly seeding constants etc.
394 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands10343d92010-02-16 11:11:14 +0000395 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000396 assert(i < cast<StructType>(V->getType())->getNumElements() &&
397 "Invalid element #");
Benjamin Kramer329f7ba2009-11-05 14:33:27 +0000398
399 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
400 bool> I = StructValueState.insert(
401 std::make_pair(std::make_pair(V, i), LatticeVal()));
402 LatticeVal &LV = I.first->second;
403
404 if (!I.second)
405 return LV; // Common case, already in the map.
406
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000407 if (Constant *C = dyn_cast<Constant>(V)) {
408 if (isa<UndefValue>(C))
409 ; // Undef values remain undefined.
410 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
411 LV.markConstant(CS->getOperand(i)); // Constants are constant.
412 else if (isa<ConstantAggregateZero>(C)) {
413 const Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
414 LV.markConstant(Constant::getNullValue(FieldTy));
415 } else
416 LV.markOverdefined(); // Unknown sort of constant.
417 }
418
419 // All others are underdefined by default.
420 return LV;
421 }
422
423
Chris Lattner6367c3f2009-11-02 05:55:40 +0000424 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
425 /// work list if it is not already executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
427 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
428 return; // This edge is already known to be executable!
429
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000430 if (!MarkBlockExecutable(Dest)) {
431 // If the destination is already executable, we just made an *edge*
432 // feasible that wasn't before. Revisit the PHI nodes in the block
433 // because they have potentially new operands.
David Greenedbf1d5a2010-01-05 01:27:15 +0000434 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000435 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000437 PHINode *PN;
438 for (BasicBlock::iterator I = Dest->begin();
439 (PN = dyn_cast<PHINode>(I)); ++I)
440 visitPHINode(*PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 }
442 }
443
444 // getFeasibleSuccessors - Return a vector of booleans to indicate which
445 // successors are reachable from a given terminator instruction.
446 //
447 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
448
449 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000450 // block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451 //
452 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
453
454 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnerc8798002009-11-02 02:33:50 +0000455 // instruction that was just changed state somehow. Based on this
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000456 // information, we need to update the specified user of this instruction.
457 //
Chris Lattner3a2499a2009-11-03 03:42:51 +0000458 void OperandChangedState(Instruction *I) {
459 if (BBExecutable.count(I->getParent())) // Inst is executable?
460 visit(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 }
Chris Lattnere84f1232009-11-02 06:28:16 +0000462
463 /// RemoveFromOverdefinedPHIs - If I has any entries in the
464 /// UsersOfOverdefinedPHIs map for PN, remove them now.
465 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
466 if (UsersOfOverdefinedPHIs.empty()) return;
467 std::multimap<PHINode*, Instruction*>::iterator It, E;
468 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
469 while (It != E) {
470 if (It->second == I)
471 UsersOfOverdefinedPHIs.erase(It++);
472 else
473 ++It;
474 }
475 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476
477private:
478 friend class InstVisitor<SCCPSolver>;
479
Chris Lattnerc8798002009-11-02 02:33:50 +0000480 // visit implementations - Something changed in this instruction. Either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481 // operand made a transition, or the instruction is newly executable. Change
482 // the value type of I to reflect these changes if appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 void visitPHINode(PHINode &I);
484
485 // Terminators
486 void visitReturnInst(ReturnInst &I);
487 void visitTerminatorInst(TerminatorInst &TI);
488
489 void visitCastInst(CastInst &I);
490 void visitSelectInst(SelectInst &I);
491 void visitBinaryOperator(Instruction &I);
492 void visitCmpInst(CmpInst &I);
493 void visitExtractElementInst(ExtractElementInst &I);
494 void visitInsertElementInst(InsertElementInst &I);
495 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000496 void visitExtractValueInst(ExtractValueInst &EVI);
497 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498
Chris Lattnerc8798002009-11-02 02:33:50 +0000499 // Instructions that cannot be folded away.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000500 void visitStoreInst (StoreInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 void visitLoadInst (LoadInst &I);
502 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000503 void visitCallInst (CallInst &I) {
Chris Lattner6ad04a02009-09-27 21:35:11 +0000504 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000505 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 void visitInvokeInst (InvokeInst &II) {
507 visitCallSite(CallSite::get(&II));
508 visitTerminatorInst(II);
509 }
510 void visitCallSite (CallSite CS);
511 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
512 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000513 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000515 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516
517 void visitInstruction(Instruction &I) {
Chris Lattnerc8798002009-11-02 02:33:50 +0000518 // If a new instruction is added to LLVM that we don't handle.
David Greenedbf1d5a2010-01-05 01:27:15 +0000519 dbgs() << "SCCP: Don't know how to handle: " << I;
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000520 markAnythingOverdefined(&I); // Just in case
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 }
522};
523
Duncan Sands40f67972007-07-20 08:56:21 +0000524} // end anonymous namespace
525
526
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527// getFeasibleSuccessors - Return a vector of booleans to indicate which
528// successors are reachable from a given terminator instruction.
529//
530void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
531 SmallVector<bool, 16> &Succs) {
532 Succs.resize(TI.getNumSuccessors());
533 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
534 if (BI->isUnconditional()) {
535 Succs[0] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000536 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 }
Chris Lattneradaf7332009-11-02 02:30:06 +0000538
Chris Lattner6367c3f2009-11-02 05:55:40 +0000539 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000540 ConstantInt *CI = BCValue.getConstantInt();
541 if (CI == 0) {
Chris Lattneradaf7332009-11-02 02:30:06 +0000542 // Overdefined condition variables, and branches on unfoldable constant
543 // conditions, mean the branch could go either way.
Chris Lattner220571c2009-11-02 03:21:36 +0000544 if (!BCValue.isUndefined())
545 Succs[0] = Succs[1] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000546 return;
547 }
548
549 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000550 Succs[CI->isZero()] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000551 return;
552 }
553
Chris Lattner220571c2009-11-02 03:21:36 +0000554 if (isa<InvokeInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555 // Invoke instructions successors are always executable.
556 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000557 return;
558 }
559
560 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000561 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000562 ConstantInt *CI = SCValue.getConstantInt();
563
564 if (CI == 0) { // Overdefined or undefined condition?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 // All destinations are executable!
Chris Lattner220571c2009-11-02 03:21:36 +0000566 if (!SCValue.isUndefined())
567 Succs.assign(TI.getNumSuccessors(), true);
568 return;
569 }
570
571 Succs[SI->findCaseValue(CI)] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000572 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000574
575 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
576 if (isa<IndirectBrInst>(&TI)) {
577 // Just mark all destinations executable!
578 Succs.assign(TI.getNumSuccessors(), true);
579 return;
580 }
581
582#ifndef NDEBUG
David Greenedbf1d5a2010-01-05 01:27:15 +0000583 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000584#endif
585 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586}
587
588
589// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000590// block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591//
592bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
593 assert(BBExecutable.count(To) && "Dest should always be alive!");
594
595 // Make sure the source basic block is executable!!
596 if (!BBExecutable.count(From)) return false;
597
Chris Lattnerc8798002009-11-02 02:33:50 +0000598 // Check to make sure this edge itself is actually feasible now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599 TerminatorInst *TI = From->getTerminator();
600 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
601 if (BI->isUnconditional())
602 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000603
Chris Lattner6367c3f2009-11-02 05:55:40 +0000604 LatticeVal BCValue = getValueState(BI->getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605
Chris Lattneradaf7332009-11-02 02:30:06 +0000606 // Overdefined condition variables mean the branch could go either way,
607 // undef conditions mean that neither edge is feasible yet.
Chris Lattner220571c2009-11-02 03:21:36 +0000608 ConstantInt *CI = BCValue.getConstantInt();
609 if (CI == 0)
610 return !BCValue.isUndefined();
Chris Lattneradaf7332009-11-02 02:30:06 +0000611
Chris Lattneradaf7332009-11-02 02:30:06 +0000612 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000613 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000614 }
615
616 // Invoke instructions successors are always executable.
617 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000619
620 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000621 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000622 ConstantInt *CI = SCValue.getConstantInt();
623
624 if (CI == 0)
625 return !SCValue.isUndefined();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626
Chris Lattner220571c2009-11-02 03:21:36 +0000627 // Make sure to skip the "default value" which isn't a value
628 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
629 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
630 return SI->getSuccessor(i) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631
Chris Lattner220571c2009-11-02 03:21:36 +0000632 // If the constant value is not equal to any of the branches, we must
633 // execute default branch.
634 return SI->getDefaultDest() == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000636
637 // Just mark all destinations executable!
638 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
639 if (isa<IndirectBrInst>(&TI))
640 return true;
641
642#ifndef NDEBUG
David Greenedbf1d5a2010-01-05 01:27:15 +0000643 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000644#endif
645 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646}
647
Chris Lattnerc8798002009-11-02 02:33:50 +0000648// visit Implementations - Something changed in this instruction, either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649// operand made a transition, or the instruction is newly executable. Change
650// the value type of I to reflect these changes if appropriate. This method
651// makes sure to do the following actions:
652//
653// 1. If a phi node merges two constants in, and has conflicting value coming
654// from different branches, or if the PHI node merges in an overdefined
655// value, then the PHI node becomes overdefined.
656// 2. If a phi node merges only constants in, and they all agree on value, the
657// PHI node becomes a constant value equal to that.
658// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
659// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
660// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
661// 6. If a conditional branch has a value that is constant, make the selected
662// destination executable
663// 7. If a conditional branch has a value that is overdefined, make all
664// successors executable.
665//
666void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000667 // If this PN returns a struct, just mark the result overdefined.
668 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands10343d92010-02-16 11:11:14 +0000669 if (PN.getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000670 return markAnythingOverdefined(&PN);
671
Chris Lattner6367c3f2009-11-02 05:55:40 +0000672 if (getValueState(&PN).isOverdefined()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 // There may be instructions using this PHI node that are not overdefined
674 // themselves. If so, make sure that they know that the PHI node operand
675 // changed.
676 std::multimap<PHINode*, Instruction*>::iterator I, E;
677 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000678 if (I == E)
679 return;
680
681 SmallVector<Instruction*, 16> Users;
682 for (; I != E; ++I)
683 Users.push_back(I->second);
684 while (!Users.empty())
685 visit(Users.pop_back_val());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 return; // Quick exit
687 }
688
689 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
690 // and slow us down a lot. Just mark them overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000691 if (PN.getNumIncomingValues() > 64)
Chris Lattner6367c3f2009-11-02 05:55:40 +0000692 return markOverdefined(&PN);
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000693
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 // Look at all of the executable operands of the PHI node. If any of them
695 // are overdefined, the PHI becomes overdefined as well. If they are all
696 // constant, and they agree with each other, the PHI becomes the identical
697 // constant. If they are constant and don't agree, the PHI is overdefined.
698 // If there are no executable operands, the PHI remains undefined.
699 //
700 Constant *OperandVal = 0;
701 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000702 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
704
Chris Lattnerb52f7002009-11-02 03:03:42 +0000705 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
706 continue;
707
708 if (IV.isOverdefined()) // PHI node becomes overdefined!
709 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710
Chris Lattnerb52f7002009-11-02 03:03:42 +0000711 if (OperandVal == 0) { // Grab the first value.
712 OperandVal = IV.getConstant();
713 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 }
Chris Lattnerb52f7002009-11-02 03:03:42 +0000715
716 // There is already a reachable operand. If we conflict with it,
717 // then the PHI node becomes overdefined. If we agree with it, we
718 // can continue on.
719
720 // Check to see if there are two different constants merging, if so, the PHI
721 // node is overdefined.
722 if (IV.getConstant() != OperandVal)
723 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 }
725
726 // If we exited the loop, this means that the PHI node only has constant
727 // arguments that agree with each other(and OperandVal is the constant) or
728 // OperandVal is null because there are no defined incoming arguments. If
729 // this is the case, the PHI remains undefined.
730 //
731 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000732 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733}
734
Chris Lattner3a2499a2009-11-03 03:42:51 +0000735
736
737
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000739 if (I.getNumOperands() == 0) return; // ret void
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 Function *F = I.getParent()->getParent();
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000742 Value *ResultOp = I.getOperand(0);
Chris Lattner3a2499a2009-11-03 03:42:51 +0000743
Devang Pateladd320d2008-03-11 05:46:42 +0000744 // If we are tracking the return value of this function, merge it in.
Duncan Sands10343d92010-02-16 11:11:14 +0000745 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000747 TrackedRetVals.find(F);
Chris Lattner3a2499a2009-11-03 03:42:51 +0000748 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000749 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Pateladd320d2008-03-11 05:46:42 +0000750 return;
751 }
752 }
753
Chris Lattnercd73be02008-04-23 05:38:20 +0000754 // Handle functions that return multiple values.
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000755 if (!TrackedMultipleRetVals.empty()) {
756 if (const StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
757 if (MRVFunctionsTracked.count(F))
758 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
759 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
760 getStructValueState(ResultOp, i));
761
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 }
763}
764
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
766 SmallVector<bool, 16> SuccFeasible;
767 getFeasibleSuccessors(TI, SuccFeasible);
768
769 BasicBlock *BB = TI.getParent();
770
Chris Lattnerc8798002009-11-02 02:33:50 +0000771 // Mark all feasible successors executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
773 if (SuccFeasible[i])
774 markEdgeExecutable(BB, TI.getSuccessor(i));
775}
776
777void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000778 LatticeVal OpSt = getValueState(I.getOperand(0));
779 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 markOverdefined(&I);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000781 else if (OpSt.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000782 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner6367c3f2009-11-02 05:55:40 +0000783 OpSt.getConstant(), I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784}
785
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000786
Dan Gohman856193b2008-06-20 01:15:44 +0000787void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000788 // If this returns a struct, mark all elements over defined, we don't track
789 // structs in structs.
Duncan Sands10343d92010-02-16 11:11:14 +0000790 if (EVI.getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000791 return markAnythingOverdefined(&EVI);
792
793 // If this is extracting from more than one level of struct, we don't know.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000794 if (EVI.getNumIndices() != 1)
795 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000796
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000797 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands10343d92010-02-16 11:11:14 +0000798 if (AggVal->getType()->isStructTy()) {
Chris Lattner1b8b0592009-11-10 22:02:09 +0000799 unsigned i = *EVI.idx_begin();
800 LatticeVal EltVal = getStructValueState(AggVal, i);
801 mergeInValue(getValueState(&EVI), &EVI, EltVal);
802 } else {
803 // Otherwise, must be extracting from an array.
804 return markOverdefined(&EVI);
805 }
Dan Gohman856193b2008-06-20 01:15:44 +0000806}
807
808void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000809 const StructType *STy = dyn_cast<StructType>(IVI.getType());
810 if (STy == 0)
Chris Lattnerb52f7002009-11-02 03:03:42 +0000811 return markOverdefined(&IVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000812
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000813 // If this has more than one index, we can't handle it, drive all results to
814 // undef.
815 if (IVI.getNumIndices() != 1)
816 return markAnythingOverdefined(&IVI);
817
818 Value *Aggr = IVI.getAggregateOperand();
819 unsigned Idx = *IVI.idx_begin();
820
821 // Compute the result based on what we're inserting.
822 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
823 // This passes through all values that aren't the inserted element.
824 if (i != Idx) {
825 LatticeVal EltVal = getStructValueState(Aggr, i);
826 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
827 continue;
828 }
829
830 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands10343d92010-02-16 11:11:14 +0000831 if (Val->getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000832 // We don't track structs in structs.
833 markOverdefined(getStructValueState(&IVI, i), &IVI);
834 else {
835 LatticeVal InVal = getValueState(Val);
836 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
837 }
838 }
Dan Gohman856193b2008-06-20 01:15:44 +0000839}
840
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000842 // If this select returns a struct, just mark the result overdefined.
843 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands10343d92010-02-16 11:11:14 +0000844 if (I.getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +0000845 return markAnythingOverdefined(&I);
846
Chris Lattner6367c3f2009-11-02 05:55:40 +0000847 LatticeVal CondValue = getValueState(I.getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 if (CondValue.isUndefined())
849 return;
Chris Lattner220571c2009-11-02 03:21:36 +0000850
851 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000852 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
853 mergeInValue(&I, getValueState(OpVal));
Chris Lattner220571c2009-11-02 03:21:36 +0000854 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 }
856
857 // Otherwise, the condition is overdefined or a constant we can't evaluate.
858 // See if we can produce something better than overdefined based on the T/F
859 // value.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000860 LatticeVal TVal = getValueState(I.getTrueValue());
861 LatticeVal FVal = getValueState(I.getFalseValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862
863 // select ?, C, C -> C.
864 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattnerb52f7002009-11-02 03:03:42 +0000865 TVal.getConstant() == FVal.getConstant())
866 return markConstant(&I, FVal.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867
Chris Lattner6367c3f2009-11-02 05:55:40 +0000868 if (TVal.isUndefined()) // select ?, undef, X -> X.
869 return mergeInValue(&I, FVal);
870 if (FVal.isUndefined()) // select ?, X, undef -> X.
871 return mergeInValue(&I, TVal);
872 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873}
874
Chris Lattner6367c3f2009-11-02 05:55:40 +0000875// Handle Binary Operators.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000877 LatticeVal V1State = getValueState(I.getOperand(0));
878 LatticeVal V2State = getValueState(I.getOperand(1));
879
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 LatticeVal &IV = ValueState[&I];
881 if (IV.isOverdefined()) return;
882
Chris Lattner6367c3f2009-11-02 05:55:40 +0000883 if (V1State.isConstant() && V2State.isConstant())
884 return markConstant(IV, &I,
885 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
886 V2State.getConstant()));
887
888 // If something is undef, wait for it to resolve.
889 if (!V1State.isOverdefined() && !V2State.isOverdefined())
890 return;
891
892 // Otherwise, one of our operands is overdefined. Try to produce something
893 // better than overdefined with some tricks.
894
895 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
896 // operand is overdefined.
897 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
898 LatticeVal *NonOverdefVal = 0;
899 if (!V1State.isOverdefined())
900 NonOverdefVal = &V1State;
901 else if (!V2State.isOverdefined())
902 NonOverdefVal = &V2State;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903
Chris Lattner6367c3f2009-11-02 05:55:40 +0000904 if (NonOverdefVal) {
905 if (NonOverdefVal->isUndefined()) {
906 // Could annihilate value.
907 if (I.getOpcode() == Instruction::And)
908 markConstant(IV, &I, Constant::getNullValue(I.getType()));
909 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
910 markConstant(IV, &I, Constant::getAllOnesValue(PT));
911 else
912 markConstant(IV, &I,
913 Constant::getAllOnesValue(I.getType()));
914 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000916
917 if (I.getOpcode() == Instruction::And) {
918 // X and 0 = 0
919 if (NonOverdefVal->getConstant()->isNullValue())
920 return markConstant(IV, &I, NonOverdefVal->getConstant());
921 } else {
922 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
923 if (CI->isAllOnesValue()) // X or -1 = -1
924 return markConstant(IV, &I, NonOverdefVal->getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 }
926 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000927 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928
929
Chris Lattner6367c3f2009-11-02 05:55:40 +0000930 // If both operands are PHI nodes, it is possible that this instruction has
931 // a constant value, despite the fact that the PHI node doesn't. Check for
932 // this condition now.
933 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
934 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
935 if (PN1->getParent() == PN2->getParent()) {
936 // Since the two PHI nodes are in the same basic block, they must have
937 // entries for the same predecessors. Walk the predecessor list, and
938 // if all of the incoming values are constants, and the result of
939 // evaluating this expression with all incoming value pairs is the
940 // same, then this expression is a constant even though the PHI node
941 // is not a constant!
942 LatticeVal Result;
943 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
944 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
945 BasicBlock *InBlock = PN1->getIncomingBlock(i);
946 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947
Chris Lattner6367c3f2009-11-02 05:55:40 +0000948 if (In1.isOverdefined() || In2.isOverdefined()) {
949 Result.markOverdefined();
950 break; // Cannot fold this operation over the PHI nodes!
951 }
952
953 if (In1.isConstant() && In2.isConstant()) {
954 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
955 In2.getConstant());
956 if (Result.isUndefined())
957 Result.markConstant(V);
958 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +0000960 break;
Chris Lattnerb52f7002009-11-02 03:03:42 +0000961 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 }
963 }
964
Chris Lattner6367c3f2009-11-02 05:55:40 +0000965 // If we found a constant value here, then we know the instruction is
966 // constant despite the fact that the PHI nodes are overdefined.
967 if (Result.isConstant()) {
968 markConstant(IV, &I, Result.getConstant());
969 // Remember that this instruction is virtually using the PHI node
970 // operands.
971 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
972 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
973 return;
974 }
975
976 if (Result.isUndefined())
977 return;
978
979 // Okay, this really is overdefined now. Since we might have
980 // speculatively thought that this was not overdefined before, and
981 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
982 // make sure to clean out any entries that we put there, for
983 // efficiency.
Chris Lattnere84f1232009-11-02 06:28:16 +0000984 RemoveFromOverdefinedPHIs(&I, PN1);
985 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000986 }
987
988 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989}
990
Chris Lattnerc8798002009-11-02 02:33:50 +0000991// Handle ICmpInst instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000993 LatticeVal V1State = getValueState(I.getOperand(0));
994 LatticeVal V2State = getValueState(I.getOperand(1));
995
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 LatticeVal &IV = ValueState[&I];
997 if (IV.isOverdefined()) return;
998
Chris Lattner6367c3f2009-11-02 05:55:40 +0000999 if (V1State.isConstant() && V2State.isConstant())
1000 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
1001 V1State.getConstant(),
1002 V2State.getConstant()));
1003
1004 // If operands are still undefined, wait for it to resolve.
1005 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1006 return;
1007
1008 // If something is overdefined, use some tricks to avoid ending up and over
1009 // defined if we can.
1010
1011 // If both operands are PHI nodes, it is possible that this instruction has
1012 // a constant value, despite the fact that the PHI node doesn't. Check for
1013 // this condition now.
1014 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
1015 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
1016 if (PN1->getParent() == PN2->getParent()) {
1017 // Since the two PHI nodes are in the same basic block, they must have
1018 // entries for the same predecessors. Walk the predecessor list, and
1019 // if all of the incoming values are constants, and the result of
1020 // evaluating this expression with all incoming value pairs is the
1021 // same, then this expression is a constant even though the PHI node
1022 // is not a constant!
1023 LatticeVal Result;
1024 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
1025 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
1026 BasicBlock *InBlock = PN1->getIncomingBlock(i);
1027 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
Chris Lattner6367c3f2009-11-02 05:55:40 +00001029 if (In1.isOverdefined() || In2.isOverdefined()) {
1030 Result.markOverdefined();
1031 break; // Cannot fold this operation over the PHI nodes!
1032 }
1033
1034 if (In1.isConstant() && In2.isConstant()) {
1035 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
1036 In1.getConstant(),
1037 In2.getConstant());
1038 if (Result.isUndefined())
1039 Result.markConstant(V);
1040 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +00001042 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 }
1046
Chris Lattner6367c3f2009-11-02 05:55:40 +00001047 // If we found a constant value here, then we know the instruction is
1048 // constant despite the fact that the PHI nodes are overdefined.
1049 if (Result.isConstant()) {
1050 markConstant(&I, Result.getConstant());
1051 // Remember that this instruction is virtually using the PHI node
1052 // operands.
1053 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1054 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1055 return;
1056 }
1057
1058 if (Result.isUndefined())
1059 return;
1060
1061 // Okay, this really is overdefined now. Since we might have
1062 // speculatively thought that this was not overdefined before, and
1063 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1064 // make sure to clean out any entries that we put there, for
1065 // efficiency.
Chris Lattnere84f1232009-11-02 06:28:16 +00001066 RemoveFromOverdefinedPHIs(&I, PN1);
1067 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner6367c3f2009-11-02 05:55:40 +00001068 }
1069
1070 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071}
1072
1073void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001074 // TODO : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001075 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076
1077#if 0
1078 LatticeVal &ValState = getValueState(I.getOperand(0));
1079 LatticeVal &IdxState = getValueState(I.getOperand(1));
1080
1081 if (ValState.isOverdefined() || IdxState.isOverdefined())
1082 markOverdefined(&I);
1083 else if(ValState.isConstant() && IdxState.isConstant())
1084 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1085 IdxState.getConstant()));
1086#endif
1087}
1088
1089void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001090 // TODO : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001091 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092#if 0
1093 LatticeVal &ValState = getValueState(I.getOperand(0));
1094 LatticeVal &EltState = getValueState(I.getOperand(1));
1095 LatticeVal &IdxState = getValueState(I.getOperand(2));
1096
1097 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1098 IdxState.isOverdefined())
1099 markOverdefined(&I);
1100 else if(ValState.isConstant() && EltState.isConstant() &&
1101 IdxState.isConstant())
1102 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1103 EltState.getConstant(),
1104 IdxState.getConstant()));
1105 else if (ValState.isUndefined() && EltState.isConstant() &&
1106 IdxState.isConstant())
1107 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1108 EltState.getConstant(),
1109 IdxState.getConstant()));
1110#endif
1111}
1112
1113void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001114 // TODO : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001115 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116#if 0
1117 LatticeVal &V1State = getValueState(I.getOperand(0));
1118 LatticeVal &V2State = getValueState(I.getOperand(1));
1119 LatticeVal &MaskState = getValueState(I.getOperand(2));
1120
1121 if (MaskState.isUndefined() ||
1122 (V1State.isUndefined() && V2State.isUndefined()))
1123 return; // Undefined output if mask or both inputs undefined.
1124
1125 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1126 MaskState.isOverdefined()) {
1127 markOverdefined(&I);
1128 } else {
1129 // A mix of constant/undef inputs.
1130 Constant *V1 = V1State.isConstant() ?
1131 V1State.getConstant() : UndefValue::get(I.getType());
1132 Constant *V2 = V2State.isConstant() ?
1133 V2State.getConstant() : UndefValue::get(I.getType());
1134 Constant *Mask = MaskState.isConstant() ?
1135 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1136 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1137 }
1138#endif
1139}
1140
Chris Lattnerc8798002009-11-02 02:33:50 +00001141// Handle getelementptr instructions. If all operands are constants then we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142// can turn this into a getelementptr ConstantExpr.
1143//
1144void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerdd355c42009-11-02 23:25:39 +00001145 if (ValueState[&I].isOverdefined()) return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146
1147 SmallVector<Constant*, 8> Operands;
1148 Operands.reserve(I.getNumOperands());
1149
1150 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001151 LatticeVal State = getValueState(I.getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 if (State.isUndefined())
Chris Lattnerc8798002009-11-02 02:33:50 +00001153 return; // Operands are not resolved yet.
1154
Chris Lattnerb52f7002009-11-02 03:03:42 +00001155 if (State.isOverdefined())
Chris Lattnerdd355c42009-11-02 23:25:39 +00001156 return markOverdefined(&I);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001157
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 assert(State.isConstant() && "Unknown state!");
1159 Operands.push_back(State.getConstant());
1160 }
1161
1162 Constant *Ptr = Operands[0];
Chris Lattner6367c3f2009-11-02 05:55:40 +00001163 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1164 Operands.size()-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165}
1166
Chris Lattner6367c3f2009-11-02 05:55:40 +00001167void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001168 // If this store is of a struct, ignore it.
Duncan Sands10343d92010-02-16 11:11:14 +00001169 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001170 return;
1171
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1173 return;
Chris Lattner6367c3f2009-11-02 05:55:40 +00001174
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1176 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1177 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1178
Chris Lattner6367c3f2009-11-02 05:55:40 +00001179 // Get the value we are storing into the global, then merge it.
1180 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 if (I->second.isOverdefined())
1182 TrackedGlobals.erase(I); // No need to keep tracking this!
1183}
1184
1185
1186// Handle load instructions. If the operand is a constant pointer to a constant
1187// global, we can replace the load with the loaded constant value!
1188void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001189 // If this load is of a struct, just mark the result overdefined.
Duncan Sands10343d92010-02-16 11:11:14 +00001190 if (I.getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001191 return markAnythingOverdefined(&I);
1192
Chris Lattner6367c3f2009-11-02 05:55:40 +00001193 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner0148bb22009-11-02 06:06:14 +00001194 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner6367c3f2009-11-02 05:55:40 +00001195
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 LatticeVal &IV = ValueState[&I];
1197 if (IV.isOverdefined()) return;
1198
Chris Lattner6367c3f2009-11-02 05:55:40 +00001199 if (!PtrVal.isConstant() || I.isVolatile())
1200 return markOverdefined(IV, &I);
1201
Chris Lattner0148bb22009-11-02 06:06:14 +00001202 Constant *Ptr = PtrVal.getConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203
Chris Lattner6367c3f2009-11-02 05:55:40 +00001204 // load null -> null
1205 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1206 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1207
1208 // Transform load (constant global) into the value loaded.
1209 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001210 if (!TrackedGlobals.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001211 // If we are tracking this global, merge in the known value for it.
1212 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1213 TrackedGlobals.find(GV);
1214 if (It != TrackedGlobals.end()) {
1215 mergeInValue(IV, &I, It->second);
1216 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 }
1218 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 }
1220
Chris Lattner0148bb22009-11-02 06:06:14 +00001221 // Transform load from a constant into a constant if possible.
1222 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1223 return markConstant(IV, &I, C);
Chris Lattner6367c3f2009-11-02 05:55:40 +00001224
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 // Otherwise we cannot say for certain what value this load will produce.
1226 // Bail out.
1227 markOverdefined(IV, &I);
1228}
1229
1230void SCCPSolver::visitCallSite(CallSite CS) {
1231 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001233
1234 // The common case is that we aren't tracking the callee, either because we
1235 // are not doing interprocedural analysis or the callee is indirect, or is
1236 // external. Handle these cases first.
Chris Lattner3a2499a2009-11-03 03:42:51 +00001237 if (F == 0 || F->isDeclaration()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001238CallOverdefined:
1239 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001240 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001241
1242 // Otherwise, if we have a single return value case, and if the function is
1243 // a declaration, maybe we can constant fold it.
Duncan Sands10343d92010-02-16 11:11:14 +00001244 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattnercd73be02008-04-23 05:38:20 +00001245 canConstantFoldCallTo(F)) {
1246
1247 SmallVector<Constant*, 8> Operands;
1248 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1249 AI != E; ++AI) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001250 LatticeVal State = getValueState(*AI);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001251
Chris Lattnercd73be02008-04-23 05:38:20 +00001252 if (State.isUndefined())
1253 return; // Operands are not resolved yet.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001254 if (State.isOverdefined())
1255 return markOverdefined(I);
Chris Lattnercd73be02008-04-23 05:38:20 +00001256 assert(State.isConstant() && "Unknown state!");
1257 Operands.push_back(State.getConstant());
1258 }
1259
1260 // If we can constant fold this, mark the result of the call as a
1261 // constant.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001262 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1263 return markConstant(I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001265
1266 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001267 return markAnythingOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 }
1269
Chris Lattner59dc8e62009-11-03 19:24:51 +00001270 // If this is a local function that doesn't have its address taken, mark its
1271 // entry block executable and merge in the actual arguments to the call into
1272 // the formal arguments of the function.
1273 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1274 MarkBlockExecutable(F->begin());
1275
1276 // Propagate information from this call site into the callee.
1277 CallSite::arg_iterator CAI = CS.arg_begin();
1278 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1279 AI != E; ++AI, ++CAI) {
1280 // If this argument is byval, and if the function is not readonly, there
1281 // will be an implicit copy formed of the input aggregate.
1282 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1283 markOverdefined(AI);
1284 continue;
1285 }
1286
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001287 if (const StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattnerbf2c3732009-11-04 18:57:42 +00001288 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1289 LatticeVal CallArg = getStructValueState(*CAI, i);
1290 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1291 }
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001292 } else {
1293 mergeInValue(AI, getValueState(*CAI));
1294 }
Chris Lattner59dc8e62009-11-03 19:24:51 +00001295 }
1296 }
1297
Chris Lattnercd73be02008-04-23 05:38:20 +00001298 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001299 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1300 if (!MRVFunctionsTracked.count(F))
1301 goto CallOverdefined; // Not tracking this callee.
1302
1303 // If we are tracking this callee, propagate the result of the function
1304 // into this call site.
1305 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1306 mergeInValue(getStructValueState(I, i), I,
1307 TrackedMultipleRetVals[std::make_pair(F, i)]);
1308 } else {
1309 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1310 if (TFRVI == TrackedRetVals.end())
1311 goto CallOverdefined; // Not tracking this callee.
1312
Chris Lattnercd73be02008-04-23 05:38:20 +00001313 // If so, propagate the return value of the callee into this call result.
1314 mergeInValue(I, TFRVI->second);
Chris Lattnercd73be02008-04-23 05:38:20 +00001315 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316}
1317
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318void SCCPSolver::Solve() {
1319 // Process the work lists until they are empty!
1320 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1321 !OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001322 // Process the overdefined instruction's work list first, which drives other
1323 // things to overdefined more quickly.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001325 Value *I = OverdefinedInstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326
David Greenedbf1d5a2010-01-05 01:27:15 +00001327 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328
1329 // "I" got into the work list because it either made the transition from
1330 // bottom to constant
1331 //
1332 // Anything on this worklist that is overdefined need not be visited
1333 // since all of its users will have already been marked as overdefined
Chris Lattnerc8798002009-11-02 02:33:50 +00001334 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 //
1336 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1337 UI != E; ++UI)
Chris Lattner3a2499a2009-11-03 03:42:51 +00001338 if (Instruction *I = dyn_cast<Instruction>(*UI))
1339 OperandChangedState(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 }
Chris Lattnerc8798002009-11-02 02:33:50 +00001341
1342 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 while (!InstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001344 Value *I = InstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345
David Greenedbf1d5a2010-01-05 01:27:15 +00001346 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347
Chris Lattner6367c3f2009-11-02 05:55:40 +00001348 // "I" got into the work list because it made the transition from undef to
1349 // constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 //
1351 // Anything on this worklist that is overdefined need not be visited
1352 // since all of its users will have already been marked as overdefined.
Chris Lattnerc8798002009-11-02 02:33:50 +00001353 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 //
Duncan Sands10343d92010-02-16 11:11:14 +00001355 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1357 UI != E; ++UI)
Chris Lattner3a2499a2009-11-03 03:42:51 +00001358 if (Instruction *I = dyn_cast<Instruction>(*UI))
1359 OperandChangedState(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 }
1361
Chris Lattnerc8798002009-11-02 02:33:50 +00001362 // Process the basic block work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 while (!BBWorkList.empty()) {
1364 BasicBlock *BB = BBWorkList.back();
1365 BBWorkList.pop_back();
1366
David Greenedbf1d5a2010-01-05 01:27:15 +00001367 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368
1369 // Notify all instructions in this basic block that they are newly
1370 // executable.
1371 visit(BB);
1372 }
1373 }
1374}
1375
1376/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1377/// that branches on undef values cannot reach any of their successors.
1378/// However, this is not a safe assumption. After we solve dataflow, this
1379/// method should be use to handle this. If this returns true, the solver
1380/// should be rerun.
1381///
1382/// This method handles this by finding an unresolved branch and marking it one
1383/// of the edges from the block as being feasible, even though the condition
1384/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1385/// CFG and only slightly pessimizes the analysis results (by marking one,
1386/// potentially infeasible, edge feasible). This cannot usefully modify the
1387/// constraints on the condition of the branch, as that would impact other users
1388/// of the value.
1389///
1390/// This scan also checks for values that use undefs, whose results are actually
1391/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1392/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1393/// even if X isn't defined.
1394bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1395 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1396 if (!BBExecutable.count(BB))
1397 continue;
1398
1399 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1400 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001401 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001403 if (const StructType *STy = dyn_cast<StructType>(I->getType())) {
1404 // Only a few things that can be structs matter for undef. Just send
1405 // all their results to overdefined. We could be more precise than this
1406 // but it isn't worth bothering.
1407 if (isa<CallInst>(I) || isa<SelectInst>(I)) {
1408 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1409 LatticeVal &LV = getStructValueState(I, i);
1410 if (LV.isUndefined())
1411 markOverdefined(LV, I);
1412 }
1413 }
1414 continue;
1415 }
1416
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 LatticeVal &LV = getValueState(I);
1418 if (!LV.isUndefined()) continue;
1419
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001420 // No instructions using structs need disambiguation.
Duncan Sands10343d92010-02-16 11:11:14 +00001421 if (I->getOperand(0)->getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001422 continue;
1423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 // Get the lattice values of the first two operands for use below.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001425 LatticeVal Op0LV = getValueState(I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 LatticeVal Op1LV;
1427 if (I->getNumOperands() == 2) {
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001428 // No instructions using structs need disambiguation.
Duncan Sands10343d92010-02-16 11:11:14 +00001429 if (I->getOperand(1)->getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001430 continue;
1431
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 // If this is a two-operand instruction, and if both operands are
1433 // undefs, the result stays undef.
1434 Op1LV = getValueState(I->getOperand(1));
1435 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1436 continue;
1437 }
1438
1439 // If this is an instructions whose result is defined even if the input is
1440 // not fully defined, propagate the information.
1441 const Type *ITy = I->getType();
1442 switch (I->getOpcode()) {
1443 default: break; // Leave the instruction as an undef.
1444 case Instruction::ZExt:
1445 // After a zero extend, we know the top part is zero. SExt doesn't have
1446 // to be handled here, because we don't know whether the top part is 1's
1447 // or 0's.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001448 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 return true;
1450 case Instruction::Mul:
1451 case Instruction::And:
1452 // undef * X -> 0. X could be zero.
1453 // undef & X -> 0. X could be zero.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001454 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 return true;
1456
1457 case Instruction::Or:
1458 // undef | X -> -1. X could be -1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001459 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460 return true;
1461
1462 case Instruction::SDiv:
1463 case Instruction::UDiv:
1464 case Instruction::SRem:
1465 case Instruction::URem:
1466 // X / undef -> undef. No change.
1467 // X % undef -> undef. No change.
1468 if (Op1LV.isUndefined()) break;
1469
1470 // undef / X -> 0. X could be maxint.
1471 // undef % X -> 0. X could be 1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001472 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473 return true;
1474
1475 case Instruction::AShr:
1476 // undef >>s X -> undef. No change.
1477 if (Op0LV.isUndefined()) break;
1478
1479 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1480 if (Op0LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001481 markForcedConstant(I, Op0LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001482 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001483 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 return true;
1485 case Instruction::LShr:
1486 case Instruction::Shl:
1487 // undef >> X -> undef. No change.
1488 // undef << X -> undef. No change.
1489 if (Op0LV.isUndefined()) break;
1490
1491 // X >> undef -> 0. X could be 0.
1492 // X << undef -> 0. X could be 0.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001493 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494 return true;
1495 case Instruction::Select:
1496 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1497 if (Op0LV.isUndefined()) {
1498 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1499 Op1LV = getValueState(I->getOperand(2));
1500 } else if (Op1LV.isUndefined()) {
1501 // c ? undef : undef -> undef. No change.
1502 Op1LV = getValueState(I->getOperand(2));
1503 if (Op1LV.isUndefined())
1504 break;
1505 // Otherwise, c ? undef : x -> x.
1506 } else {
1507 // Leave Op1LV as Operand(1)'s LatticeValue.
1508 }
1509
1510 if (Op1LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001511 markForcedConstant(I, Op1LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001513 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001515 case Instruction::Call:
1516 // If a call has an undef result, it is because it is constant foldable
1517 // but one of the inputs was undef. Just force the result to
1518 // overdefined.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001519 markOverdefined(I);
Chris Lattner9110ac92008-05-24 03:59:33 +00001520 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 }
1522 }
1523
1524 TerminatorInst *TI = BB->getTerminator();
1525 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1526 if (!BI->isConditional()) continue;
1527 if (!getValueState(BI->getCondition()).isUndefined())
1528 continue;
1529 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001530 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001531 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 if (!getValueState(SI->getCondition()).isUndefined())
1533 continue;
1534 } else {
1535 continue;
1536 }
1537
Chris Lattner6186e8c2008-01-28 00:32:30 +00001538 // If the edge to the second successor isn't thought to be feasible yet,
1539 // mark it so now. We pick the second one so that this goes to some
1540 // enumerated value in a switch instead of going to the default destination.
1541 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 continue;
1543
1544 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1545 // and return. This will make other blocks reachable, which will allow new
1546 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001547 markEdgeExecutable(BB, TI->getSuccessor(1));
1548
1549 // This must be a conditional branch of switch on undef. At this point,
1550 // force the old terminator to branch to the first successor. This is
1551 // required because we are now influencing the dataflow of the function with
1552 // the assumption that this edge is taken. If we leave the branch condition
1553 // as undef, then further analysis could think the undef went another way
1554 // leading to an inconsistent set of conclusions.
1555 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001556 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001557 } else {
1558 SwitchInst *SI = cast<SwitchInst>(TI);
1559 SI->setCondition(SI->getCaseValue(1));
1560 }
1561
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562 return true;
1563 }
1564
1565 return false;
1566}
1567
1568
1569namespace {
1570 //===--------------------------------------------------------------------===//
1571 //
1572 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1573 /// Sparse Conditional Constant Propagator.
1574 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001575 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001577 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001578
1579 // runOnFunction - Run the Sparse Conditional Constant Propagation
1580 // algorithm, and return true if the function was modified.
1581 //
1582 bool runOnFunction(Function &F);
1583
1584 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1585 AU.setPreservesCFG();
1586 }
1587 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588} // end anonymous namespace
1589
Dan Gohman089efff2008-05-13 00:00:25 +00001590char SCCP::ID = 0;
1591static RegisterPass<SCCP>
1592X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593
Chris Lattnerc8798002009-11-02 02:33:50 +00001594// createSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001595FunctionPass *llvm::createSCCPPass() {
1596 return new SCCP();
1597}
1598
Chris Lattner14513dc2009-11-02 02:47:51 +00001599static void DeleteInstructionInBlock(BasicBlock *BB) {
David Greenedbf1d5a2010-01-05 01:27:15 +00001600 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattner14513dc2009-11-02 02:47:51 +00001601 ++NumDeadBlocks;
1602
1603 // Delete the instructions backwards, as it has a reduced likelihood of
1604 // having to update as many def-use and use-def chains.
1605 while (!isa<TerminatorInst>(BB->begin())) {
1606 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1607
1608 if (!I->use_empty())
1609 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1610 BB->getInstList().erase(I);
1611 ++NumInstRemoved;
1612 }
1613}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614
1615// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1616// and return true if the function was modified.
1617//
1618bool SCCP::runOnFunction(Function &F) {
David Greenedbf1d5a2010-01-05 01:27:15 +00001619 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner0148bb22009-11-02 06:06:14 +00001620 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001621
1622 // Mark the first block of the function as being executable.
1623 Solver.MarkBlockExecutable(F.begin());
1624
1625 // Mark all arguments to the function as being overdefined.
1626 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001627 Solver.markAnythingOverdefined(AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628
1629 // Solve for constants.
1630 bool ResolvedUndefs = true;
1631 while (ResolvedUndefs) {
1632 Solver.Solve();
David Greenedbf1d5a2010-01-05 01:27:15 +00001633 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1635 }
1636
1637 bool MadeChanges = false;
1638
1639 // If we decided that there are basic blocks that are dead in this function,
1640 // delete their contents now. Note that we cannot actually delete the blocks,
1641 // as we cannot modify the CFG of the function.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642
Chris Lattner14513dc2009-11-02 02:47:51 +00001643 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001644 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001645 DeleteInstructionInBlock(BB);
1646 MadeChanges = true;
1647 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001649
1650 // Iterate over all of the instructions in a function, replacing them with
1651 // constants if we have found them to be of constant values.
1652 //
1653 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1654 Instruction *Inst = BI++;
1655 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1656 continue;
1657
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001658 // TODO: Reconstruct structs from their elements.
Duncan Sands10343d92010-02-16 11:11:14 +00001659 if (Inst->getType()->isStructTy())
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001660 continue;
1661
Chris Lattnerc9edab82009-11-02 02:54:24 +00001662 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1663 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001664 continue;
1665
1666 Constant *Const = IV.isConstant()
1667 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greenedbf1d5a2010-01-05 01:27:15 +00001668 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattner14513dc2009-11-02 02:47:51 +00001669
1670 // Replaces all of the uses of a variable with uses of the constant.
1671 Inst->replaceAllUsesWith(Const);
1672
1673 // Delete the instruction.
1674 Inst->eraseFromParent();
1675
1676 // Hey, we just changed something!
1677 MadeChanges = true;
1678 ++NumInstRemoved;
1679 }
1680 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681
1682 return MadeChanges;
1683}
1684
1685namespace {
1686 //===--------------------------------------------------------------------===//
1687 //
1688 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1689 /// Constant Propagation.
1690 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001691 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001692 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001693 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 bool runOnModule(Module &M);
1695 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696} // end anonymous namespace
1697
Dan Gohman089efff2008-05-13 00:00:25 +00001698char IPSCCP::ID = 0;
1699static RegisterPass<IPSCCP>
1700Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1701
Chris Lattnerc8798002009-11-02 02:33:50 +00001702// createIPSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703ModulePass *llvm::createIPSCCPPass() {
1704 return new IPSCCP();
1705}
1706
1707
Gabor Greif944971a2010-03-24 10:29:52 +00001708static bool AddressIsTaken(const GlobalValue *GV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709 // Delete any dead constantexpr klingons.
1710 GV->removeDeadConstantUsers();
1711
Gabor Greiff23f0252010-03-25 23:06:16 +00001712 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greif944971a2010-03-24 10:29:52 +00001713 UI != E; ++UI) {
1714 const User *U = *UI;
1715 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001716 if (SI->getOperand(0) == GV || SI->isVolatile())
1717 return true; // Storing addr of GV.
Gabor Greif944971a2010-03-24 10:29:52 +00001718 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719 // Make sure we are calling the function, not passing the address.
Gabor Greif09452dc2010-03-24 13:21:49 +00001720 CallSite CS((Instruction*)U);
1721 if (!CS.isCallee(UI))
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001722 return true;
Gabor Greif944971a2010-03-24 10:29:52 +00001723 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001724 if (LI->isVolatile())
1725 return true;
Gabor Greif944971a2010-03-24 10:29:52 +00001726 } else if (isa<BlockAddress>(U)) {
Chris Lattner2f487502009-11-01 06:11:53 +00001727 // blockaddress doesn't take the address of the function, it takes addr
1728 // of label.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001729 } else {
1730 return true;
1731 }
Gabor Greif944971a2010-03-24 10:29:52 +00001732 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 return false;
1734}
1735
1736bool IPSCCP::runOnModule(Module &M) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001737 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738
1739 // Loop over all functions, marking arguments to those with their addresses
1740 // taken or that are external as overdefined.
1741 //
Chris Lattner74f9ed22009-11-02 06:34:04 +00001742 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1743 if (F->isDeclaration())
1744 continue;
1745
Chris Lattner3a2499a2009-11-03 03:42:51 +00001746 // If this is a strong or ODR definition of this function, then we can
1747 // propagate information about its result into callsites of it.
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001748 if (!F->mayBeOverridden())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749 Solver.AddTrackedFunction(F);
Chris Lattner3a2499a2009-11-03 03:42:51 +00001750
1751 // If this function only has direct calls that we can see, we can track its
1752 // arguments and return value aggressively, and can assume it is not called
1753 // unless we see evidence to the contrary.
Chris Lattner59dc8e62009-11-03 19:24:51 +00001754 if (F->hasLocalLinkage() && !AddressIsTaken(F)) {
1755 Solver.AddArgumentTrackedFunction(F);
Chris Lattner3a2499a2009-11-03 03:42:51 +00001756 continue;
Chris Lattner59dc8e62009-11-03 19:24:51 +00001757 }
Chris Lattner3a2499a2009-11-03 03:42:51 +00001758
1759 // Assume the function is called.
1760 Solver.MarkBlockExecutable(F->begin());
1761
1762 // Assume nothing about the incoming arguments.
1763 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1764 AI != E; ++AI)
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001765 Solver.markAnythingOverdefined(AI);
Chris Lattner74f9ed22009-11-02 06:34:04 +00001766 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767
1768 // Loop over global variables. We inform the solver about any internal global
1769 // variables that do not have their 'addresses taken'. If they don't have
1770 // their addresses taken, we can propagate constants through them.
1771 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1772 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001773 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001774 Solver.TrackValueOfGlobalVariable(G);
1775
1776 // Solve for constants.
1777 bool ResolvedUndefs = true;
1778 while (ResolvedUndefs) {
1779 Solver.Solve();
1780
David Greenedbf1d5a2010-01-05 01:27:15 +00001781 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001782 ResolvedUndefs = false;
1783 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1784 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1785 }
1786
1787 bool MadeChanges = false;
1788
1789 // Iterate over all of the instructions in the module, replacing them with
1790 // constants if we have found them to be of constant values.
1791 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001792 SmallVector<BasicBlock*, 512> BlocksToErase;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793
1794 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner84388f12009-11-02 03:25:55 +00001795 if (Solver.isBlockExecutable(F->begin())) {
1796 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1797 AI != E; ++AI) {
Duncan Sands10343d92010-02-16 11:11:14 +00001798 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Chris Lattner84388f12009-11-02 03:25:55 +00001799
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001800 // TODO: Could use getStructLatticeValueFor to find out if the entire
1801 // result is a constant and replace it entirely if so.
1802
Chris Lattner84388f12009-11-02 03:25:55 +00001803 LatticeVal IV = Solver.getLatticeValueFor(AI);
1804 if (IV.isOverdefined()) continue;
1805
1806 Constant *CST = IV.isConstant() ?
1807 IV.getConstant() : UndefValue::get(AI->getType());
David Greenedbf1d5a2010-01-05 01:27:15 +00001808 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Chris Lattner84388f12009-11-02 03:25:55 +00001809
1810 // Replaces all of the uses of a variable with uses of the
1811 // constant.
1812 AI->replaceAllUsesWith(CST);
1813 ++IPNumArgsElimed;
1814 }
Chris Lattnerc9edab82009-11-02 02:54:24 +00001815 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001816
Chris Lattner14513dc2009-11-02 02:47:51 +00001817 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001818 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001819 DeleteInstructionInBlock(BB);
1820 MadeChanges = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001822 TerminatorInst *TI = BB->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001823 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1824 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001825 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001826 TI->getSuccessor(i)->removePredecessor(BB);
1827 }
1828 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001829 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner14513dc2009-11-02 02:47:51 +00001830 TI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831
1832 if (&*BB != &F->front())
1833 BlocksToErase.push_back(BB);
1834 else
Owen Anderson35b47072009-08-13 21:58:54 +00001835 new UnreachableInst(M.getContext(), BB);
Chris Lattner14513dc2009-11-02 02:47:51 +00001836 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001837 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001838
1839 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1840 Instruction *Inst = BI++;
Duncan Sands10343d92010-02-16 11:11:14 +00001841 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattner14513dc2009-11-02 02:47:51 +00001842 continue;
1843
Chris Lattnerdca9e5c2009-11-03 23:40:48 +00001844 // TODO: Could use getStructLatticeValueFor to find out if the entire
1845 // result is a constant and replace it entirely if so.
1846
Chris Lattnerc9edab82009-11-02 02:54:24 +00001847 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1848 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001849 continue;
1850
1851 Constant *Const = IV.isConstant()
1852 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greenedbf1d5a2010-01-05 01:27:15 +00001853 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattner14513dc2009-11-02 02:47:51 +00001854
1855 // Replaces all of the uses of a variable with uses of the
1856 // constant.
1857 Inst->replaceAllUsesWith(Const);
1858
1859 // Delete the instruction.
1860 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1861 Inst->eraseFromParent();
1862
1863 // Hey, we just changed something!
1864 MadeChanges = true;
1865 ++IPNumInstRemoved;
1866 }
1867 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001868
1869 // Now that all instructions in the function are constant folded, erase dead
1870 // blocks, because we can now use ConstantFoldTerminator to get rid of
1871 // in-edges.
1872 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1873 // If there are any PHI nodes in this successor, drop entries for BB now.
1874 BasicBlock *DeadBB = BlocksToErase[i];
Dan Gohman082f11b2009-11-20 20:19:14 +00001875 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1876 UI != UE; ) {
Dan Gohman3d97a632009-11-23 16:13:39 +00001877 // Grab the user and then increment the iterator early, as the user
1878 // will be deleted. Step past all adjacent uses from the same user.
1879 Instruction *I = dyn_cast<Instruction>(*UI);
1880 do { ++UI; } while (UI != UE && *UI == I);
1881
Dan Gohman082f11b2009-11-20 20:19:14 +00001882 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohman082f11b2009-11-20 20:19:14 +00001883 if (!I) continue;
1884
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885 bool Folded = ConstantFoldTerminator(I->getParent());
1886 if (!Folded) {
1887 // The constant folder may not have been able to fold the terminator
1888 // if this is a branch or switch on undef. Fold it manually as a
1889 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001890#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1892 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1893 "Branch should be foldable!");
1894 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1895 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1896 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001897 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898 }
Devang Patele92c16d2008-11-21 01:52:59 +00001899#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900
1901 // Make this an uncond branch to the first successor.
1902 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001903 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001904
1905 // Remove entries in successor phi nodes to remove edges.
1906 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1907 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1908
1909 // Remove the old terminator.
1910 TI->eraseFromParent();
1911 }
1912 }
1913
1914 // Finally, delete the basic block.
1915 F->getBasicBlockList().erase(DeadBB);
1916 }
1917 BlocksToErase.clear();
1918 }
1919
1920 // If we inferred constant or undef return values for a function, we replaced
1921 // all call uses with the inferred value. This means we don't need to bother
1922 // actually returning anything from the function. Replace all return
1923 // instructions with return undef.
Chris Lattnerc51d86c2010-02-27 00:07:42 +00001924 //
1925 // Do this in two stages: first identify the functions we should process, then
1926 // actually zap their returns. This is important because we can only do this
Chris Lattnercde3e3b2010-02-27 07:50:40 +00001927 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerc51d86c2010-02-27 00:07:42 +00001928 // last use of a function, the order of processing functions would affect
Chris Lattnercde3e3b2010-02-27 07:50:40 +00001929 // whether other functions are optimizable.
Chris Lattnerc51d86c2010-02-27 00:07:42 +00001930 SmallVector<ReturnInst*, 8> ReturnsToZap;
1931
Devang Pateld04d42b2008-03-11 17:32:05 +00001932 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001933 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001934 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner3a2499a2009-11-03 03:42:51 +00001935 E = RV.end(); I != E; ++I) {
1936 Function *F = I->first;
1937 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1938 continue;
1939
1940 // We can only do this if we know that nothing else can call the function.
1941 if (!F->hasLocalLinkage() || AddressIsTaken(F))
1942 continue;
1943
1944 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1945 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1946 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerc51d86c2010-02-27 00:07:42 +00001947 ReturnsToZap.push_back(RI);
1948 }
1949
1950 // Zap all returns which we've identified as zap to change.
1951 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1952 Function *F = ReturnsToZap[i]->getParent()->getParent();
1953 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner3a2499a2009-11-03 03:42:51 +00001954 }
1955
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 // If we infered constant or undef values for globals variables, we can delete
1957 // the global and any stores that remain to it.
1958 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1959 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1960 E = TG.end(); I != E; ++I) {
1961 GlobalVariable *GV = I->first;
1962 assert(!I->second.isOverdefined() &&
1963 "Overdefined values should have been taken out of the map!");
David Greenedbf1d5a2010-01-05 01:27:15 +00001964 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965 while (!GV->use_empty()) {
1966 StoreInst *SI = cast<StoreInst>(GV->use_back());
1967 SI->eraseFromParent();
1968 }
1969 M.getGlobalList().erase(GV);
1970 ++IPNumGlobalConst;
1971 }
1972
1973 return MadeChanges;
1974}