blob: 31ad26774acc24860f63d5629fd8213dbae969f4 [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-06-27 23:38:11 +000011//
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
Chris Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-06-27 23:38:11 +000017//
Chris Lattner138a1242001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Chris Lattneref36dfd2004-11-15 05:03:30 +000020#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000021#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000022#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000023#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000024#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000025#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000026#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner3774c912009-11-02 19:31:10 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000029#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000030#include "llvm/Transforms/Utils/Local.h"
Chris Lattner5638dc62009-11-02 06:06:14 +000031#include "llvm/Target/TargetData.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000032#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000036#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000038#include "llvm/ADT/DenseSet.h"
Chris Lattner79272202009-11-02 02:20:32 +000039#include "llvm/ADT/PointerIntPair.h"
Chris Lattner09275292009-11-02 06:11:23 +000040#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000041#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000044#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000045#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Chris Lattner0e5f4992006-12-19 21:40:18 +000048STATISTIC(NumInstRemoved, "Number of instructions removed");
49STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000051STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000052STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
Chris Lattner0dbfc052002-04-29 21:26:08 +000055namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000056/// LatticeVal class - This class represents the different lattice values that
57/// an LLVM value may occupy. It is a simple class with value semantics.
58///
Chris Lattner3e8b6632009-09-02 06:11:42 +000059class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000060 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000061 /// undefined - This LLVM Value has no known value yet.
62 undefined,
63
64 /// constant - This LLVM Value has a specific constant value.
65 constant,
66
67 /// forcedconstant - This LLVM Value was thought to be undef until
68 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
69 /// with another (different) constant, it goes to overdefined, instead of
70 /// asserting.
71 forcedconstant,
72
73 /// overdefined - This instruction is not known to be constant, and we know
74 /// it has a value.
75 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000076 };
77
78 /// Val: This stores the current lattice value along with the Constant* for
79 /// the constant if this is a 'constant' or 'forcedconstant' value.
80 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000081
Chris Lattner79272202009-11-02 02:20:32 +000082 LatticeValueTy getLatticeValue() const {
83 return Val.getInt();
84 }
85
Chris Lattner138a1242001-06-27 23:38:11 +000086public:
Chris Lattner38871e42009-11-02 03:03:42 +000087 LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000088
Chris Lattner38871e42009-11-02 03:03:42 +000089 bool isUndefined() const { return getLatticeValue() == undefined; }
90 bool isConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000091 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 }
Chris Lattner38871e42009-11-02 03:03:42 +000093 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner79272202009-11-02 02:20:32 +000094
Chris Lattner38871e42009-11-02 03:03:42 +000095 Constant *getConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000096 assert(isConstant() && "Cannot get the constant of a non-constant!");
97 return Val.getPointer();
98 }
99
100 /// markOverdefined - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000101 bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000102 if (isOverdefined())
103 return false;
104
105 Val.setInt(overdefined);
106 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000107 }
108
Chris Lattner79272202009-11-02 02:20:32 +0000109 /// markConstant - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000110 bool markConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000111 if (isConstant()) {
112 assert(getConstant() == V && "Marking constant with different value");
113 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000114 }
Chris Lattner79272202009-11-02 02:20:32 +0000115
116 if (isUndefined()) {
117 Val.setInt(constant);
118 assert(V && "Marking constant with NULL");
119 Val.setPointer(V);
120 } else {
121 assert(getLatticeValue() == forcedconstant &&
122 "Cannot move from overdefined to constant!");
123 // Stay at forcedconstant if the constant is the same.
124 if (V == getConstant()) return false;
125
126 // Otherwise, we go to overdefined. Assumptions made based on the
127 // forced value are possibly wrong. Assuming this is another constant
128 // could expose a contradiction.
129 Val.setInt(overdefined);
130 }
131 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000132 }
133
Chris Lattner36c99522009-11-02 03:21:36 +0000134 /// getConstantInt - If this is a constant with a ConstantInt value, return it
135 /// otherwise return null.
136 ConstantInt *getConstantInt() const {
137 if (isConstant())
138 return dyn_cast<ConstantInt>(getConstant());
139 return 0;
140 }
141
Chris Lattner38871e42009-11-02 03:03:42 +0000142 void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000143 assert(isUndefined() && "Can't force a defined value!");
144 Val.setInt(forcedconstant);
145 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000146 }
Chris Lattner138a1242001-06-27 23:38:11 +0000147};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000148} // end anonymous namespace.
149
150
151namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000152
Chris Lattner138a1242001-06-27 23:38:11 +0000153//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000154//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000155/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
156/// Constant Propagation.
157///
158class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner5638dc62009-11-02 06:06:14 +0000159 const TargetData *TD;
Chris Lattner09275292009-11-02 06:11:23 +0000160 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000161 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000162
Chris Lattnerdd336d12004-12-11 05:15:59 +0000163 /// GlobalValue - If we are tracking any values for the contents of a global
164 /// variable, we keep a mapping from the constant accessor to the element of
165 /// the global, to the currently known value. If the value becomes
166 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000167 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000168
Devang Patel7c490d42008-03-11 05:46:42 +0000169 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000170 /// value out of a function, it will have an entry in this map, indicating
171 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000172 DenseMap<Function*, LatticeVal> TrackedRetVals;
173
174 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
175 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000176 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000177
Chris Lattner38871e42009-11-02 03:03:42 +0000178 /// The reason for two worklists is that overdefined is the lowest state
179 /// on the lattice, and moving things to overdefined as fast as possible
180 /// makes SCCP converge much faster.
181 ///
182 /// By having a separate worklist, we accomplish this because everything
183 /// possibly overdefined will become overdefined at the soonest possible
184 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000185 SmallVector<Value*, 64> OverdefinedInstWorkList;
186 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000187
188
Chris Lattnercf712de2008-08-23 23:36:38 +0000189 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000190
Chris Lattner1daee8b2004-01-12 03:57:30 +0000191 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
192 /// overdefined, despite the fact that the PHI node is overdefined.
193 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
194
Chris Lattner16b18fd2003-10-08 16:55:34 +0000195 /// KnownFeasibleEdges - Entries in this set are edges which have already had
196 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000197 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
198 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000199public:
Chris Lattner5638dc62009-11-02 06:06:14 +0000200 SCCPSolver(const TargetData *td) : TD(td) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000201
Chris Lattner82bec2c2004-11-15 04:44:20 +0000202 /// MarkBlockExecutable - This method can be used by clients to mark all of
203 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner09275292009-11-02 06:11:23 +0000204 ///
205 /// This returns true if the block was not considered live before.
206 bool MarkBlockExecutable(BasicBlock *BB) {
207 if (!BBExecutable.insert(BB)) return false;
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000208 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000209 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner09275292009-11-02 06:11:23 +0000210 return true;
Chris Lattner0dbfc052002-04-29 21:26:08 +0000211 }
212
Chris Lattnerdd336d12004-12-11 05:15:59 +0000213 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000214 /// inform the SCCPSolver that it should track loads and stores to the
215 /// specified global variable if it can. This is only legal to call if
216 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000217 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
218 const Type *ElTy = GV->getType()->getElementType();
219 if (ElTy->isFirstClassType()) {
220 LatticeVal &IV = TrackedGlobals[GV];
221 if (!isa<UndefValue>(GV->getInitializer()))
222 IV.markConstant(GV->getInitializer());
223 }
224 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000225
226 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
227 /// and out of the specified function (which cannot have its address taken),
228 /// this method must be called.
229 void AddTrackedFunction(Function *F) {
Chris Lattner3774c912009-11-02 19:31:10 +0000230 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000231 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000232 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
233 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000234 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
235 LatticeVal()));
236 } else
237 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000238 }
239
Chris Lattner82bec2c2004-11-15 04:44:20 +0000240 /// Solve - Solve for constants and executable blocks.
241 ///
242 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000243
Chris Lattner3bad2532006-12-20 06:21:33 +0000244 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000245 /// that branches on undef values cannot reach any of their successors.
246 /// However, this is not a safe assumption. After we solve dataflow, this
247 /// method should be use to handle this. If this returns true, the solver
248 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000249 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000250
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000251 bool isBlockExecutable(BasicBlock *BB) const {
252 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000253 }
254
Chris Lattner8db50122009-11-02 02:54:24 +0000255 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000256 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000257 assert(I != ValueState.end() && "V is not in valuemap!");
258 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000259 }
260
Devang Patel7c490d42008-03-11 05:46:42 +0000261 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000262 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000263 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
264 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000265 }
266
Chris Lattnerdd336d12004-12-11 05:15:59 +0000267 /// getTrackedGlobals - Get and return the set of inferred initializers for
268 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000269 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000270 return TrackedGlobals;
271 }
272
Chris Lattner36c99522009-11-02 03:21:36 +0000273 void markOverdefined(Value *V) {
Chris Lattner57939df2007-03-04 04:50:21 +0000274 markOverdefined(ValueState[V], V);
275 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000276
Chris Lattner138a1242001-06-27 23:38:11 +0000277private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000278 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000279 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000280 // the users of the instruction are updated later.
281 //
Chris Lattner38871e42009-11-02 03:03:42 +0000282 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
283 if (!IV.markConstant(C)) return;
284 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
285 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000286 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000287
Chris Lattner38871e42009-11-02 03:03:42 +0000288 void markConstant(Value *V, Constant *C) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000289 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000290 }
291
Chris Lattner2a0433b2009-11-02 05:55:40 +0000292 void markForcedConstant(Value *V, Constant *C) {
293 ValueState[V].markForcedConstant(C);
294 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
295 InstWorkList.push_back(V);
296 }
297
298
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000299 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000300 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000301 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000302 void markOverdefined(LatticeVal &IV, Value *V) {
303 if (!IV.markOverdefined()) return;
304
305 DEBUG(errs() << "markOverdefined: ";
306 if (Function *F = dyn_cast<Function>(V))
307 errs() << "Function '" << F->getName() << "'\n";
308 else
309 errs() << *V << '\n');
310 // Only instructions go on the work list
311 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000312 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000313
Chris Lattner2a0433b2009-11-02 05:55:40 +0000314 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000315 if (IV.isOverdefined() || MergeWithV.isUndefined())
316 return; // Noop.
317 if (MergeWithV.isOverdefined())
318 markOverdefined(IV, V);
319 else if (IV.isUndefined())
320 markConstant(IV, V, MergeWithV.getConstant());
321 else if (IV.getConstant() != MergeWithV.getConstant())
322 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000323 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000324
Chris Lattner2a0433b2009-11-02 05:55:40 +0000325 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattner36c99522009-11-02 03:21:36 +0000326 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000327 }
328
Chris Lattner138a1242001-06-27 23:38:11 +0000329
Chris Lattner2a0433b2009-11-02 05:55:40 +0000330 /// getValueState - Return the LatticeVal object that corresponds to the
331 /// value. This function handles the case when the value hasn't been seen yet
332 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000333 LatticeVal &getValueState(Value *V) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000334 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000335 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000336
Chris Lattner36c99522009-11-02 03:21:36 +0000337 LatticeVal &LV = ValueState[V];
338
Chris Lattner3bad2532006-12-20 06:21:33 +0000339 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000340 // Undef values remain undefined.
341 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000342 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000343 }
Chris Lattner36c99522009-11-02 03:21:36 +0000344
Chris Lattner2f096252009-11-02 02:33:50 +0000345 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000346 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000347 }
348
Chris Lattner2a0433b2009-11-02 05:55:40 +0000349 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
350 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000351 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
352 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
353 return; // This edge is already known to be executable!
354
Chris Lattner09275292009-11-02 06:11:23 +0000355 if (!MarkBlockExecutable(Dest)) {
356 // If the destination is already executable, we just made an *edge*
357 // feasible that wasn't before. Revisit the PHI nodes in the block
358 // because they have potentially new operands.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000359 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
360 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000361
Chris Lattner09275292009-11-02 06:11:23 +0000362 PHINode *PN;
363 for (BasicBlock::iterator I = Dest->begin();
364 (PN = dyn_cast<PHINode>(I)); ++I)
365 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000366 }
Chris Lattner138a1242001-06-27 23:38:11 +0000367 }
368
Chris Lattner82bec2c2004-11-15 04:44:20 +0000369 // getFeasibleSuccessors - Return a vector of booleans to indicate which
370 // successors are reachable from a given terminator instruction.
371 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000372 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000373
374 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000375 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000376 //
377 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
378
379 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000380 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000381 // information, we need to update the specified user of this instruction.
382 //
Chris Lattner3774c912009-11-02 19:31:10 +0000383 void OperandChangedState(User *U) {
384 // Only instructions use other variable values!
385 Instruction &I = cast<Instruction>(*U);
386 if (BBExecutable.count(I.getParent())) // Inst is executable?
387 visit(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000388 }
Chris Lattnere01985c2009-11-02 06:28:16 +0000389
390 /// RemoveFromOverdefinedPHIs - If I has any entries in the
391 /// UsersOfOverdefinedPHIs map for PN, remove them now.
392 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
393 if (UsersOfOverdefinedPHIs.empty()) return;
394 std::multimap<PHINode*, Instruction*>::iterator It, E;
395 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
396 while (It != E) {
397 if (It->second == I)
398 UsersOfOverdefinedPHIs.erase(It++);
399 else
400 ++It;
401 }
402 }
Chris Lattner82bec2c2004-11-15 04:44:20 +0000403
404private:
405 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000406
Chris Lattner2f096252009-11-02 02:33:50 +0000407 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000408 // operand made a transition, or the instruction is newly executable. Change
409 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000410 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000411
412 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000413 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000414 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000415
Chris Lattnerb8047602002-08-14 17:53:45 +0000416 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000417 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000418 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000419 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000420 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000421 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000422 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000423 void visitExtractValueInst(ExtractValueInst &EVI);
424 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000425
Chris Lattner2f096252009-11-02 02:33:50 +0000426 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000427 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000428 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000429 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000430 void visitCallInst (CallInst &I) {
Chris Lattner3774c912009-11-02 19:31:10 +0000431 if (isFreeCall(&I))
432 return;
Chris Lattner32c0d222009-09-27 21:35:11 +0000433 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000434 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000435 void visitInvokeInst (InvokeInst &II) {
436 visitCallSite(CallSite::get(&II));
437 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000438 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000439 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000440 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000441 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000442 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000443 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
444 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000445
Chris Lattner7e708292002-06-25 16:13:24 +0000446 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000447 // If a new instruction is added to LLVM that we don't handle.
Chris Lattnerbdff5482009-08-23 04:37:46 +0000448 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000449 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000450 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000451};
Chris Lattnerf6293092002-07-23 18:06:35 +0000452
Duncan Sandse2abf122007-07-20 08:56:21 +0000453} // end anonymous namespace
454
455
Chris Lattnerb9a66342002-05-02 21:44:00 +0000456// getFeasibleSuccessors - Return a vector of booleans to indicate which
457// successors are reachable from a given terminator instruction.
458//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000459void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000460 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000461 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000462 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000463 if (BI->isUnconditional()) {
464 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000465 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000466 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000467
Chris Lattner2a0433b2009-11-02 05:55:40 +0000468 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000469 ConstantInt *CI = BCValue.getConstantInt();
470 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000471 // Overdefined condition variables, and branches on unfoldable constant
472 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000473 if (!BCValue.isUndefined())
474 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000475 return;
476 }
477
478 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000479 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000480 return;
481 }
482
Chris Lattner36c99522009-11-02 03:21:36 +0000483 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000484 // Invoke instructions successors are always executable.
485 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000486 return;
487 }
488
489 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000490 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000491 ConstantInt *CI = SCValue.getConstantInt();
492
493 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000494 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000495 if (!SCValue.isUndefined())
496 Succs.assign(TI.getNumSuccessors(), true);
497 return;
498 }
499
500 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000501 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000502 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000503
504 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
505 if (isa<IndirectBrInst>(&TI)) {
506 // Just mark all destinations executable!
507 Succs.assign(TI.getNumSuccessors(), true);
508 return;
509 }
510
511#ifndef NDEBUG
512 errs() << "Unknown terminator instruction: " << TI << '\n';
513#endif
514 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000515}
516
517
Chris Lattner59f0ce22002-05-02 21:18:01 +0000518// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000519// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000520//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000521bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000522 assert(BBExecutable.count(To) && "Dest should always be alive!");
523
524 // Make sure the source basic block is executable!!
525 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000526
Chris Lattner2f096252009-11-02 02:33:50 +0000527 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000528 TerminatorInst *TI = From->getTerminator();
529 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
530 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000531 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000532
Chris Lattner2a0433b2009-11-02 05:55:40 +0000533 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000534
Chris Lattnerea0db072009-11-02 02:30:06 +0000535 // Overdefined condition variables mean the branch could go either way,
536 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000537 ConstantInt *CI = BCValue.getConstantInt();
538 if (CI == 0)
539 return !BCValue.isUndefined();
Chris Lattnerea0db072009-11-02 02:30:06 +0000540
Chris Lattnerea0db072009-11-02 02:30:06 +0000541 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000542 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000543 }
544
545 // Invoke instructions successors are always executable.
546 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000547 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000548
549 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000550 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000551 ConstantInt *CI = SCValue.getConstantInt();
552
553 if (CI == 0)
554 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000555
Chris Lattner36c99522009-11-02 03:21:36 +0000556 // Make sure to skip the "default value" which isn't a value
557 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
558 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
559 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000560
Chris Lattner36c99522009-11-02 03:21:36 +0000561 // If the constant value is not equal to any of the branches, we must
562 // execute default branch.
563 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000564 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000565
566 // Just mark all destinations executable!
567 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
568 if (isa<IndirectBrInst>(&TI))
569 return true;
570
571#ifndef NDEBUG
572 errs() << "Unknown terminator instruction: " << *TI << '\n';
573#endif
574 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000575}
Chris Lattner138a1242001-06-27 23:38:11 +0000576
Chris Lattner2f096252009-11-02 02:33:50 +0000577// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000578// operand made a transition, or the instruction is newly executable. Change
579// the value type of I to reflect these changes if appropriate. This method
580// makes sure to do the following actions:
581//
582// 1. If a phi node merges two constants in, and has conflicting value coming
583// from different branches, or if the PHI node merges in an overdefined
584// value, then the PHI node becomes overdefined.
585// 2. If a phi node merges only constants in, and they all agree on value, the
586// PHI node becomes a constant value equal to that.
587// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
588// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
589// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
590// 6. If a conditional branch has a value that is constant, make the selected
591// destination executable
592// 7. If a conditional branch has a value that is overdefined, make all
593// successors executable.
594//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000595void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000596 if (getValueState(&PN).isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000597 // There may be instructions using this PHI node that are not overdefined
598 // themselves. If so, make sure that they know that the PHI node operand
599 // changed.
600 std::multimap<PHINode*, Instruction*>::iterator I, E;
601 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000602 if (I == E)
603 return;
604
605 SmallVector<Instruction*, 16> Users;
606 for (; I != E; ++I)
607 Users.push_back(I->second);
608 while (!Users.empty())
609 visit(Users.pop_back_val());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000610 return; // Quick exit
611 }
Chris Lattner138a1242001-06-27 23:38:11 +0000612
Chris Lattnera2f652d2004-03-16 19:49:59 +0000613 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
614 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000615 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000616 return markOverdefined(&PN);
Chris Lattnera2f652d2004-03-16 19:49:59 +0000617
Chris Lattner2a632552002-04-18 15:13:15 +0000618 // Look at all of the executable operands of the PHI node. If any of them
619 // are overdefined, the PHI becomes overdefined as well. If they are all
620 // constant, and they agree with each other, the PHI becomes the identical
621 // constant. If they are constant and don't agree, the PHI is overdefined.
622 // If there are no executable operands, the PHI remains undefined.
623 //
Chris Lattner9de28282003-04-25 02:50:03 +0000624 Constant *OperandVal = 0;
625 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000626 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000627 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000628
Chris Lattner38871e42009-11-02 03:03:42 +0000629 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
630 continue;
631
632 if (IV.isOverdefined()) // PHI node becomes overdefined!
633 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000634
Chris Lattner38871e42009-11-02 03:03:42 +0000635 if (OperandVal == 0) { // Grab the first value.
636 OperandVal = IV.getConstant();
637 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000638 }
Chris Lattner38871e42009-11-02 03:03:42 +0000639
640 // There is already a reachable operand. If we conflict with it,
641 // then the PHI node becomes overdefined. If we agree with it, we
642 // can continue on.
643
644 // Check to see if there are two different constants merging, if so, the PHI
645 // node is overdefined.
646 if (IV.getConstant() != OperandVal)
647 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000648 }
649
Chris Lattner2a632552002-04-18 15:13:15 +0000650 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000651 // arguments that agree with each other(and OperandVal is the constant) or
652 // OperandVal is null because there are no defined incoming arguments. If
653 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000654 //
Chris Lattner9de28282003-04-25 02:50:03 +0000655 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000656 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000657}
658
Chris Lattner59acc7d2004-12-10 08:02:06 +0000659void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000660 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000661
Chris Lattner59acc7d2004-12-10 08:02:06 +0000662 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000663 // If we are tracking the return value of this function, merge it in.
Chris Lattner3774c912009-11-02 19:31:10 +0000664 if (!F->hasLocalLinkage())
665 return;
666
Chris Lattner2a0433b2009-11-02 05:55:40 +0000667 if (!TrackedRetVals.empty()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000668 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000669 TrackedRetVals.find(F);
Chris Lattner3774c912009-11-02 19:31:10 +0000670 if (TFRVI != TrackedRetVals.end() &&
671 !TFRVI->second.isOverdefined()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000672 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
Devang Patel7c490d42008-03-11 05:46:42 +0000673 return;
674 }
675 }
676
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000677 // Handle functions that return multiple values.
Chris Lattner574fa9e2009-11-02 06:17:06 +0000678 if (!TrackedMultipleRetVals.empty() &&
679 isa<StructType>(I.getOperand(0)->getType())) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000680 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
681 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000682 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000683 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
684 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000685 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000686 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000687 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000688 }
689}
690
Chris Lattner82bec2c2004-11-15 04:44:20 +0000691void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000692 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000693 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000694
Chris Lattner16b18fd2003-10-08 16:55:34 +0000695 BasicBlock *BB = TI.getParent();
696
Chris Lattner2f096252009-11-02 02:33:50 +0000697 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000698 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000699 if (SuccFeasible[i])
700 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000701}
702
Chris Lattner82bec2c2004-11-15 04:44:20 +0000703void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000704 LatticeVal OpSt = getValueState(I.getOperand(0));
705 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000706 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000707 else if (OpSt.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000708 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000709 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000710}
711
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000712void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000713 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000714
Dan Gohman60ea2682008-06-20 16:41:17 +0000715 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000716 if (isa<UndefValue>(Aggr))
717 return;
718
719 // Currently only handle single-index extractvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000720 if (EVI.getNumIndices() != 1)
721 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000722
723 Function *F = 0;
724 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
725 F = CI->getCalledFunction();
726 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
727 F = II->getCalledFunction();
728
729 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
730 // result back!
Chris Lattner38871e42009-11-02 03:03:42 +0000731 if (F == 0 || TrackedMultipleRetVals.empty())
732 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000733
Chris Lattnercf712de2008-08-23 23:36:38 +0000734 // See if we are tracking the result of the callee. If not tracking this
735 // function (for example, it is a declaration) just move to overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000736 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
737 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000738
739 // Otherwise, the value will be merged in here as a result of CallSite
740 // handling.
741}
742
743void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000744 Value *Aggr = IVI.getAggregateOperand();
745 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000746
Dan Gohman60ea2682008-06-20 16:41:17 +0000747 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000748 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000749 return;
750
751 // Currently only handle single-index insertvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000752 if (IVI.getNumIndices() != 1)
753 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000754
755 // Currently only handle insertvalue instructions that are in a single-use
756 // chain that builds up a return value.
757 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
Chris Lattner38871e42009-11-02 03:03:42 +0000758 if (!TmpIVI->hasOneUse())
759 return markOverdefined(&IVI);
760
Dan Gohmandfaceb42008-06-20 16:39:44 +0000761 const Value *V = *TmpIVI->use_begin();
762 if (isa<ReturnInst>(V))
763 break;
764 TmpIVI = dyn_cast<InsertValueInst>(V);
Chris Lattner38871e42009-11-02 03:03:42 +0000765 if (!TmpIVI)
766 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000767 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000768
769 // See if we are tracking the result of the callee.
770 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000771 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000772 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
773
774 // Merge in the inserted member value.
775 if (It != TrackedMultipleRetVals.end())
776 mergeInValue(It->second, F, getValueState(Val));
777
Dan Gohman60ea2682008-06-20 16:41:17 +0000778 // Mark the aggregate result of the IVI overdefined; any tracking that we do
779 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000780 markOverdefined(&IVI);
781}
782
Chris Lattner82bec2c2004-11-15 04:44:20 +0000783void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000784 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000785 if (CondValue.isUndefined())
786 return;
Chris Lattner36c99522009-11-02 03:21:36 +0000787
788 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000789 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
790 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000791 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000792 }
793
794 // Otherwise, the condition is overdefined or a constant we can't evaluate.
795 // See if we can produce something better than overdefined based on the T/F
796 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000797 LatticeVal TVal = getValueState(I.getTrueValue());
798 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000799
800 // select ?, C, C -> C.
801 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000802 TVal.getConstant() == FVal.getConstant())
803 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000804
Chris Lattner2a0433b2009-11-02 05:55:40 +0000805 if (TVal.isUndefined()) // select ?, undef, X -> X.
806 return mergeInValue(&I, FVal);
807 if (FVal.isUndefined()) // select ?, X, undef -> X.
808 return mergeInValue(&I, TVal);
809 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000810}
811
Chris Lattner2a0433b2009-11-02 05:55:40 +0000812// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000813void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000814 LatticeVal V1State = getValueState(I.getOperand(0));
815 LatticeVal V2State = getValueState(I.getOperand(1));
816
Chris Lattneref36dfd2004-11-15 05:03:30 +0000817 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000818 if (IV.isOverdefined()) return;
819
Chris Lattner2a0433b2009-11-02 05:55:40 +0000820 if (V1State.isConstant() && V2State.isConstant())
821 return markConstant(IV, &I,
822 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
823 V2State.getConstant()));
824
825 // If something is undef, wait for it to resolve.
826 if (!V1State.isOverdefined() && !V2State.isOverdefined())
827 return;
828
829 // Otherwise, one of our operands is overdefined. Try to produce something
830 // better than overdefined with some tricks.
831
832 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
833 // operand is overdefined.
834 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
835 LatticeVal *NonOverdefVal = 0;
836 if (!V1State.isOverdefined())
837 NonOverdefVal = &V1State;
838 else if (!V2State.isOverdefined())
839 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000840
Chris Lattner2a0433b2009-11-02 05:55:40 +0000841 if (NonOverdefVal) {
842 if (NonOverdefVal->isUndefined()) {
843 // Could annihilate value.
844 if (I.getOpcode() == Instruction::And)
845 markConstant(IV, &I, Constant::getNullValue(I.getType()));
846 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
847 markConstant(IV, &I, Constant::getAllOnesValue(PT));
848 else
849 markConstant(IV, &I,
850 Constant::getAllOnesValue(I.getType()));
851 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000852 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000853
854 if (I.getOpcode() == Instruction::And) {
855 // X and 0 = 0
856 if (NonOverdefVal->getConstant()->isNullValue())
857 return markConstant(IV, &I, NonOverdefVal->getConstant());
858 } else {
859 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
860 if (CI->isAllOnesValue()) // X or -1 = -1
861 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000862 }
863 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000864 }
Chris Lattnera177c672004-12-11 23:15:19 +0000865
866
Chris Lattner2a0433b2009-11-02 05:55:40 +0000867 // If both operands are PHI nodes, it is possible that this instruction has
868 // a constant value, despite the fact that the PHI node doesn't. Check for
869 // this condition now.
870 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
871 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
872 if (PN1->getParent() == PN2->getParent()) {
873 // Since the two PHI nodes are in the same basic block, they must have
874 // entries for the same predecessors. Walk the predecessor list, and
875 // if all of the incoming values are constants, and the result of
876 // evaluating this expression with all incoming value pairs is the
877 // same, then this expression is a constant even though the PHI node
878 // is not a constant!
879 LatticeVal Result;
880 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
881 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
882 BasicBlock *InBlock = PN1->getIncomingBlock(i);
883 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000884
Chris Lattner2a0433b2009-11-02 05:55:40 +0000885 if (In1.isOverdefined() || In2.isOverdefined()) {
886 Result.markOverdefined();
887 break; // Cannot fold this operation over the PHI nodes!
888 }
889
890 if (In1.isConstant() && In2.isConstant()) {
891 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
892 In2.getConstant());
893 if (Result.isUndefined())
894 Result.markConstant(V);
895 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000896 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000897 break;
Chris Lattner38871e42009-11-02 03:03:42 +0000898 }
Chris Lattner1daee8b2004-01-12 03:57:30 +0000899 }
900 }
901
Chris Lattner2a0433b2009-11-02 05:55:40 +0000902 // If we found a constant value here, then we know the instruction is
903 // constant despite the fact that the PHI nodes are overdefined.
904 if (Result.isConstant()) {
905 markConstant(IV, &I, Result.getConstant());
906 // Remember that this instruction is virtually using the PHI node
907 // operands.
908 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
909 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
910 return;
911 }
912
913 if (Result.isUndefined())
914 return;
915
916 // Okay, this really is overdefined now. Since we might have
917 // speculatively thought that this was not overdefined before, and
918 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
919 // make sure to clean out any entries that we put there, for
920 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +0000921 RemoveFromOverdefinedPHIs(&I, PN1);
922 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000923 }
924
925 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +0000926}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000927
Chris Lattner2f096252009-11-02 02:33:50 +0000928// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000929void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000930 LatticeVal V1State = getValueState(I.getOperand(0));
931 LatticeVal V2State = getValueState(I.getOperand(1));
932
Reid Spencere4d87aa2006-12-23 06:05:41 +0000933 LatticeVal &IV = ValueState[&I];
934 if (IV.isOverdefined()) return;
935
Chris Lattner2a0433b2009-11-02 05:55:40 +0000936 if (V1State.isConstant() && V2State.isConstant())
937 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
938 V1State.getConstant(),
939 V2State.getConstant()));
940
941 // If operands are still undefined, wait for it to resolve.
942 if (!V1State.isOverdefined() && !V2State.isOverdefined())
943 return;
944
945 // If something is overdefined, use some tricks to avoid ending up and over
946 // defined if we can.
947
948 // If both operands are PHI nodes, it is possible that this instruction has
949 // a constant value, despite the fact that the PHI node doesn't. Check for
950 // this condition now.
951 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
952 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
953 if (PN1->getParent() == PN2->getParent()) {
954 // Since the two PHI nodes are in the same basic block, they must have
955 // entries for the same predecessors. Walk the predecessor list, and
956 // if all of the incoming values are constants, and the result of
957 // evaluating this expression with all incoming value pairs is the
958 // same, then this expression is a constant even though the PHI node
959 // is not a constant!
960 LatticeVal Result;
961 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
962 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
963 BasicBlock *InBlock = PN1->getIncomingBlock(i);
964 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000965
Chris Lattner2a0433b2009-11-02 05:55:40 +0000966 if (In1.isOverdefined() || In2.isOverdefined()) {
967 Result.markOverdefined();
968 break; // Cannot fold this operation over the PHI nodes!
969 }
970
971 if (In1.isConstant() && In2.isConstant()) {
972 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
973 In1.getConstant(),
974 In2.getConstant());
975 if (Result.isUndefined())
976 Result.markConstant(V);
977 else if (Result.isConstant() && Result.getConstant() != V) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000978 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000979 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000980 }
981 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000982 }
983
Chris Lattner2a0433b2009-11-02 05:55:40 +0000984 // If we found a constant value here, then we know the instruction is
985 // constant despite the fact that the PHI nodes are overdefined.
986 if (Result.isConstant()) {
987 markConstant(&I, Result.getConstant());
988 // Remember that this instruction is virtually using the PHI node
989 // operands.
990 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
991 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
992 return;
993 }
994
995 if (Result.isUndefined())
996 return;
997
998 // Okay, this really is overdefined now. Since we might have
999 // speculatively thought that this was not overdefined before, and
1000 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1001 // make sure to clean out any entries that we put there, for
1002 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +00001003 RemoveFromOverdefinedPHIs(&I, PN1);
1004 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001005 }
1006
1007 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001008}
1009
Robert Bocchino56107e22006-01-10 19:05:05 +00001010void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001011 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001012 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001013
1014#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001015 LatticeVal &ValState = getValueState(I.getOperand(0));
1016 LatticeVal &IdxState = getValueState(I.getOperand(1));
1017
1018 if (ValState.isOverdefined() || IdxState.isOverdefined())
1019 markOverdefined(&I);
1020 else if(ValState.isConstant() && IdxState.isConstant())
1021 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1022 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001023#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001024}
1025
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001026void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001027 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001028 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001029#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001030 LatticeVal &ValState = getValueState(I.getOperand(0));
1031 LatticeVal &EltState = getValueState(I.getOperand(1));
1032 LatticeVal &IdxState = getValueState(I.getOperand(2));
1033
1034 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1035 IdxState.isOverdefined())
1036 markOverdefined(&I);
1037 else if(ValState.isConstant() && EltState.isConstant() &&
1038 IdxState.isConstant())
1039 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1040 EltState.getConstant(),
1041 IdxState.getConstant()));
1042 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001043 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001044 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1045 EltState.getConstant(),
1046 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001047#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001048}
1049
Chris Lattner543abdf2006-04-08 01:19:12 +00001050void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001051 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001052 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001053#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001054 LatticeVal &V1State = getValueState(I.getOperand(0));
1055 LatticeVal &V2State = getValueState(I.getOperand(1));
1056 LatticeVal &MaskState = getValueState(I.getOperand(2));
1057
1058 if (MaskState.isUndefined() ||
1059 (V1State.isUndefined() && V2State.isUndefined()))
1060 return; // Undefined output if mask or both inputs undefined.
1061
1062 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1063 MaskState.isOverdefined()) {
1064 markOverdefined(&I);
1065 } else {
1066 // A mix of constant/undef inputs.
1067 Constant *V1 = V1State.isConstant() ?
1068 V1State.getConstant() : UndefValue::get(I.getType());
1069 Constant *V2 = V2State.isConstant() ?
1070 V2State.getConstant() : UndefValue::get(I.getType());
1071 Constant *Mask = MaskState.isConstant() ?
1072 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1073 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1074 }
Devang Patel67a821d2006-12-04 23:54:59 +00001075#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001076}
1077
Chris Lattner2f096252009-11-02 02:33:50 +00001078// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001079// can turn this into a getelementptr ConstantExpr.
1080//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001081void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner5cc66d92009-11-02 23:25:39 +00001082 if (ValueState[&I].isOverdefined()) return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001083
Chris Lattnere777ff22007-02-02 20:51:48 +00001084 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001085 Operands.reserve(I.getNumOperands());
1086
1087 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001088 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001089 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001090 return; // Operands are not resolved yet.
1091
Chris Lattner38871e42009-11-02 03:03:42 +00001092 if (State.isOverdefined())
Chris Lattner5cc66d92009-11-02 23:25:39 +00001093 return markOverdefined(&I);
Chris Lattner38871e42009-11-02 03:03:42 +00001094
Chris Lattner2a88bb72002-08-30 23:39:00 +00001095 assert(State.isConstant() && "Unknown state!");
1096 Operands.push_back(State.getConstant());
1097 }
1098
1099 Constant *Ptr = Operands[0];
Chris Lattner2a0433b2009-11-02 05:55:40 +00001100 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1101 Operands.size()-1));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001102}
Brian Gaeked0fde302003-11-11 22:41:34 +00001103
Chris Lattner2a0433b2009-11-02 05:55:40 +00001104void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001105 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1106 return;
Chris Lattner2a0433b2009-11-02 05:55:40 +00001107
Chris Lattnerdd336d12004-12-11 05:15:59 +00001108 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001109 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001110 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1111
Chris Lattner2a0433b2009-11-02 05:55:40 +00001112 // Get the value we are storing into the global, then merge it.
1113 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001114 if (I->second.isOverdefined())
1115 TrackedGlobals.erase(I); // No need to keep tracking this!
1116}
1117
1118
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001119// Handle load instructions. If the operand is a constant pointer to a constant
1120// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001121void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001122 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001123 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner2a0433b2009-11-02 05:55:40 +00001124
Chris Lattneref36dfd2004-11-15 05:03:30 +00001125 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001126 if (IV.isOverdefined()) return;
1127
Chris Lattner2a0433b2009-11-02 05:55:40 +00001128 if (!PtrVal.isConstant() || I.isVolatile())
1129 return markOverdefined(IV, &I);
1130
Chris Lattner5638dc62009-11-02 06:06:14 +00001131 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001132
Chris Lattner2a0433b2009-11-02 05:55:40 +00001133 // load null -> null
1134 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1135 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1136
1137 // Transform load (constant global) into the value loaded.
1138 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001139 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001140 // If we are tracking this global, merge in the known value for it.
1141 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1142 TrackedGlobals.find(GV);
1143 if (It != TrackedGlobals.end()) {
1144 mergeInValue(IV, &I, It->second);
1145 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001146 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001147 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001148 }
1149
Chris Lattner5638dc62009-11-02 06:06:14 +00001150 // Transform load from a constant into a constant if possible.
1151 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1152 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001153
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001154 // Otherwise we cannot say for certain what value this load will produce.
1155 // Bail out.
1156 markOverdefined(IV, &I);
1157}
Chris Lattner58b7b082004-04-13 19:43:54 +00001158
Chris Lattner59acc7d2004-12-10 08:02:06 +00001159void SCCPSolver::visitCallSite(CallSite CS) {
1160 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001161 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001162
1163 // The common case is that we aren't tracking the callee, either because we
1164 // are not doing interprocedural analysis or the callee is indirect, or is
1165 // external. Handle these cases first.
Chris Lattner3774c912009-11-02 19:31:10 +00001166 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001167CallOverdefined:
1168 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001169 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001170
1171 // Otherwise, if we have a single return value case, and if the function is
1172 // a declaration, maybe we can constant fold it.
Chris Lattner3774c912009-11-02 19:31:10 +00001173 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001174 canConstantFoldCallTo(F)) {
1175
1176 SmallVector<Constant*, 8> Operands;
1177 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1178 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001179 LatticeVal State = getValueState(*AI);
Chris Lattner38871e42009-11-02 03:03:42 +00001180
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001181 if (State.isUndefined())
1182 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001183 if (State.isOverdefined())
1184 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001185 assert(State.isConstant() && "Unknown state!");
1186 Operands.push_back(State.getConstant());
1187 }
1188
1189 // If we can constant fold this, mark the result of the call as a
1190 // constant.
Chris Lattner38871e42009-11-02 03:03:42 +00001191 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1192 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001193 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001194
1195 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +00001196 return markOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001197 }
1198
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001199 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001200 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1201 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001202 // If so, propagate the return value of the callee into this call result.
1203 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001204 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001205 // Check to see if we're tracking this callee, if not, handle it in the
1206 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001207 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1208 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001209 if (TMRVI == TrackedMultipleRetVals.end())
1210 goto CallOverdefined;
Torok Edwin2b6183d2009-10-20 15:15:09 +00001211
1212 // Need to mark as overdefined, otherwise it stays undefined which
1213 // creates extractvalue undef, <idx>
1214 markOverdefined(I);
Chris Lattner38871e42009-11-02 03:03:42 +00001215
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001216 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001217 // into this call site. We do this by walking all the uses. Single-index
1218 // ExtractValueInst uses can be tracked; anything more complicated is
1219 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001220 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1221 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001222 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1223 if (EVI->getNumIndices() == 1) {
1224 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001225 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001226 continue;
1227 }
1228 }
1229 // The aggregate value is used in a way not handled here. Assume nothing.
1230 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001231 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001232 } else {
1233 // Otherwise we're not tracking this callee, so handle it in the
1234 // common path above.
1235 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001236 }
Chris Lattner3774c912009-11-02 19:31:10 +00001237
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001238 // Finally, if this is the first call to the function hit, mark its entry
1239 // block executable.
Chris Lattner09275292009-11-02 06:11:23 +00001240 MarkBlockExecutable(F->begin());
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001241
1242 // Propagate information from this call site into the callee.
1243 CallSite::arg_iterator CAI = CS.arg_begin();
1244 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1245 AI != E; ++AI, ++CAI) {
Torok Edwinc3384992009-09-24 18:33:42 +00001246 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001247 markOverdefined(AI);
Torok Edwin30a94e32009-09-24 09:47:18 +00001248 continue;
1249 }
Chris Lattner2a0433b2009-11-02 05:55:40 +00001250
1251 mergeInValue(AI, getValueState(*CAI));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001252 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001253}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001254
Chris Lattner82bec2c2004-11-15 04:44:20 +00001255void SCCPSolver::Solve() {
1256 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001257 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001258 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001259 // Process the overdefined instruction's work list first, which drives other
1260 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001261 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001262 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001263
Dan Gohman87325772009-08-17 15:25:05 +00001264 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001265
Chris Lattner82bec2c2004-11-15 04:44:20 +00001266 // "I" got into the work list because it either made the transition from
1267 // bottom to constant
1268 //
1269 // Anything on this worklist that is overdefined need not be visited
1270 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001271 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001272 //
1273 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1274 UI != E; ++UI)
Chris Lattner3774c912009-11-02 19:31:10 +00001275 OperandChangedState(*UI);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001276 }
Chris Lattner2f096252009-11-02 02:33:50 +00001277
1278 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001279 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001280 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001281
Dan Gohman87325772009-08-17 15:25:05 +00001282 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001283
Chris Lattner2a0433b2009-11-02 05:55:40 +00001284 // "I" got into the work list because it made the transition from undef to
1285 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001286 //
1287 // Anything on this worklist that is overdefined need not be visited
1288 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001289 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001290 //
1291 if (!getValueState(I).isOverdefined())
1292 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1293 UI != E; ++UI)
Chris Lattner3774c912009-11-02 19:31:10 +00001294 OperandChangedState(*UI);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001295 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001296
Chris Lattner2f096252009-11-02 02:33:50 +00001297 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001298 while (!BBWorkList.empty()) {
1299 BasicBlock *BB = BBWorkList.back();
1300 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001301
Dan Gohman87325772009-08-17 15:25:05 +00001302 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001303
Chris Lattner82bec2c2004-11-15 04:44:20 +00001304 // Notify all instructions in this basic block that they are newly
1305 // executable.
1306 visit(BB);
1307 }
1308 }
1309}
1310
Chris Lattner3bad2532006-12-20 06:21:33 +00001311/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001312/// that branches on undef values cannot reach any of their successors.
1313/// However, this is not a safe assumption. After we solve dataflow, this
1314/// method should be use to handle this. If this returns true, the solver
1315/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001316///
1317/// This method handles this by finding an unresolved branch and marking it one
1318/// of the edges from the block as being feasible, even though the condition
1319/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1320/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001321/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001322/// constraints on the condition of the branch, as that would impact other users
1323/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001324///
1325/// This scan also checks for values that use undefs, whose results are actually
1326/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1327/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1328/// even if X isn't defined.
1329bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001330 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1331 if (!BBExecutable.count(BB))
1332 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001333
1334 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1335 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001336 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001337
1338 LatticeVal &LV = getValueState(I);
1339 if (!LV.isUndefined()) continue;
1340
1341 // Get the lattice values of the first two operands for use below.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001342 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001343 LatticeVal Op1LV;
1344 if (I->getNumOperands() == 2) {
1345 // If this is a two-operand instruction, and if both operands are
1346 // undefs, the result stays undef.
1347 Op1LV = getValueState(I->getOperand(1));
1348 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1349 continue;
1350 }
1351
1352 // If this is an instructions whose result is defined even if the input is
1353 // not fully defined, propagate the information.
1354 const Type *ITy = I->getType();
1355 switch (I->getOpcode()) {
1356 default: break; // Leave the instruction as an undef.
1357 case Instruction::ZExt:
1358 // After a zero extend, we know the top part is zero. SExt doesn't have
1359 // to be handled here, because we don't know whether the top part is 1's
1360 // or 0's.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001361 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001362 return true;
1363 case Instruction::Mul:
1364 case Instruction::And:
1365 // undef * X -> 0. X could be zero.
1366 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001367 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001368 return true;
1369
1370 case Instruction::Or:
1371 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001372 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001373 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001374
1375 case Instruction::SDiv:
1376 case Instruction::UDiv:
1377 case Instruction::SRem:
1378 case Instruction::URem:
1379 // X / undef -> undef. No change.
1380 // X % undef -> undef. No change.
1381 if (Op1LV.isUndefined()) break;
1382
1383 // undef / X -> 0. X could be maxint.
1384 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001385 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001386 return true;
1387
1388 case Instruction::AShr:
1389 // undef >>s X -> undef. No change.
1390 if (Op0LV.isUndefined()) break;
1391
1392 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1393 if (Op0LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001394 markForcedConstant(I, Op0LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001395 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001396 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001397 return true;
1398 case Instruction::LShr:
1399 case Instruction::Shl:
1400 // undef >> X -> undef. No change.
1401 // undef << X -> undef. No change.
1402 if (Op0LV.isUndefined()) break;
1403
1404 // X >> undef -> 0. X could be 0.
1405 // X << undef -> 0. X could be 0.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001406 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001407 return true;
1408 case Instruction::Select:
1409 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1410 if (Op0LV.isUndefined()) {
1411 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1412 Op1LV = getValueState(I->getOperand(2));
1413 } else if (Op1LV.isUndefined()) {
1414 // c ? undef : undef -> undef. No change.
1415 Op1LV = getValueState(I->getOperand(2));
1416 if (Op1LV.isUndefined())
1417 break;
1418 // Otherwise, c ? undef : x -> x.
1419 } else {
1420 // Leave Op1LV as Operand(1)'s LatticeValue.
1421 }
1422
1423 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001424 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001425 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001426 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001427 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001428 case Instruction::Call:
1429 // If a call has an undef result, it is because it is constant foldable
1430 // but one of the inputs was undef. Just force the result to
1431 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001432 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001433 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001434 }
1435 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001436
1437 TerminatorInst *TI = BB->getTerminator();
1438 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1439 if (!BI->isConditional()) continue;
1440 if (!getValueState(BI->getCondition()).isUndefined())
1441 continue;
1442 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001443 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001444 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001445 if (!getValueState(SI->getCondition()).isUndefined())
1446 continue;
1447 } else {
1448 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001449 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001450
Chris Lattner05bb7892008-01-28 00:32:30 +00001451 // If the edge to the second successor isn't thought to be feasible yet,
1452 // mark it so now. We pick the second one so that this goes to some
1453 // enumerated value in a switch instead of going to the default destination.
1454 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001455 continue;
1456
1457 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1458 // and return. This will make other blocks reachable, which will allow new
1459 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001460 markEdgeExecutable(BB, TI->getSuccessor(1));
1461
1462 // This must be a conditional branch of switch on undef. At this point,
1463 // force the old terminator to branch to the first successor. This is
1464 // required because we are now influencing the dataflow of the function with
1465 // the assumption that this edge is taken. If we leave the branch condition
1466 // as undef, then further analysis could think the undef went another way
1467 // leading to an inconsistent set of conclusions.
1468 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001469 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner05bb7892008-01-28 00:32:30 +00001470 } else {
1471 SwitchInst *SI = cast<SwitchInst>(TI);
1472 SI->setCondition(SI->getCaseValue(1));
1473 }
1474
Chris Lattnerd2d86702006-10-22 05:59:17 +00001475 return true;
1476 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001477
Chris Lattnerd2d86702006-10-22 05:59:17 +00001478 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001479}
1480
Chris Lattner82bec2c2004-11-15 04:44:20 +00001481
1482namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001483 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001484 //
Chris Lattner14051812004-11-15 07:15:04 +00001485 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001486 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001487 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001488 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001489 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001490 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001491
Chris Lattner14051812004-11-15 07:15:04 +00001492 // runOnFunction - Run the Sparse Conditional Constant Propagation
1493 // algorithm, and return true if the function was modified.
1494 //
1495 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001496
Chris Lattner14051812004-11-15 07:15:04 +00001497 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1498 AU.setPreservesCFG();
1499 }
1500 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001501} // end anonymous namespace
1502
Dan Gohman844731a2008-05-13 00:00:25 +00001503char SCCP::ID = 0;
1504static RegisterPass<SCCP>
1505X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001506
Chris Lattner2f096252009-11-02 02:33:50 +00001507// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001508FunctionPass *llvm::createSCCPPass() {
1509 return new SCCP();
1510}
1511
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001512static void DeleteInstructionInBlock(BasicBlock *BB) {
1513 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1514 ++NumDeadBlocks;
1515
1516 // Delete the instructions backwards, as it has a reduced likelihood of
1517 // having to update as many def-use and use-def chains.
1518 while (!isa<TerminatorInst>(BB->begin())) {
1519 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1520
1521 if (!I->use_empty())
1522 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1523 BB->getInstList().erase(I);
1524 ++NumInstRemoved;
1525 }
1526}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001527
Chris Lattner82bec2c2004-11-15 04:44:20 +00001528// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1529// and return true if the function was modified.
1530//
1531bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001532 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner5638dc62009-11-02 06:06:14 +00001533 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001534
1535 // Mark the first block of the function as being executable.
1536 Solver.MarkBlockExecutable(F.begin());
1537
Chris Lattner7e529e42004-11-15 05:45:33 +00001538 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001539 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001540 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001541
Chris Lattner82bec2c2004-11-15 04:44:20 +00001542 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001543 bool ResolvedUndefs = true;
1544 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001545 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001546 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001547 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001548 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001549
Chris Lattner7e529e42004-11-15 05:45:33 +00001550 bool MadeChanges = false;
1551
1552 // If we decided that there are basic blocks that are dead in this function,
1553 // delete their contents now. Note that we cannot actually delete the blocks,
1554 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001555
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001556 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001557 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001558 DeleteInstructionInBlock(BB);
1559 MadeChanges = true;
1560 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001561 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001562
1563 // Iterate over all of the instructions in a function, replacing them with
1564 // constants if we have found them to be of constant values.
1565 //
1566 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1567 Instruction *Inst = BI++;
1568 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1569 continue;
1570
Chris Lattner8db50122009-11-02 02:54:24 +00001571 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1572 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001573 continue;
1574
1575 Constant *Const = IV.isConstant()
1576 ? IV.getConstant() : UndefValue::get(Inst->getType());
1577 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1578
1579 // Replaces all of the uses of a variable with uses of the constant.
1580 Inst->replaceAllUsesWith(Const);
1581
1582 // Delete the instruction.
1583 Inst->eraseFromParent();
1584
1585 // Hey, we just changed something!
1586 MadeChanges = true;
1587 ++NumInstRemoved;
1588 }
1589 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001590
1591 return MadeChanges;
1592}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001593
1594namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001595 //===--------------------------------------------------------------------===//
1596 //
1597 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1598 /// Constant Propagation.
1599 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001600 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001601 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001602 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001603 bool runOnModule(Module &M);
1604 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001605} // end anonymous namespace
1606
Dan Gohman844731a2008-05-13 00:00:25 +00001607char IPSCCP::ID = 0;
1608static RegisterPass<IPSCCP>
1609Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1610
Chris Lattner2f096252009-11-02 02:33:50 +00001611// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001612ModulePass *llvm::createIPSCCPPass() {
1613 return new IPSCCP();
1614}
1615
1616
1617static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001618 // Delete any dead constantexpr klingons.
1619 GV->removeDeadConstantUsers();
1620
Chris Lattner59acc7d2004-12-10 08:02:06 +00001621 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1622 UI != E; ++UI)
1623 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001624 if (SI->getOperand(0) == GV || SI->isVolatile())
1625 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001626 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1627 // Make sure we are calling the function, not passing the address.
Chris Lattnerb2710042009-11-01 06:11:53 +00001628 if (UI.getOperandNo() != 0)
Nick Lewyckyaf386132008-11-03 03:49:14 +00001629 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001630 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1631 if (LI->isVolatile())
1632 return true;
Chris Lattnerb2710042009-11-01 06:11:53 +00001633 } else if (isa<BlockAddress>(*UI)) {
1634 // blockaddress doesn't take the address of the function, it takes addr
1635 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001636 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001637 return true;
1638 }
1639 return false;
1640}
1641
1642bool IPSCCP::runOnModule(Module &M) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001643 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner59acc7d2004-12-10 08:02:06 +00001644
1645 // Loop over all functions, marking arguments to those with their addresses
1646 // taken or that are external as overdefined.
1647 //
Chris Lattnerff3ca152009-11-02 06:34:04 +00001648 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1649 if (F->isDeclaration())
1650 continue;
1651
Chris Lattner3774c912009-11-02 19:31:10 +00001652 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
1653 Solver.MarkBlockExecutable(F->begin());
1654 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1655 AI != E; ++AI)
1656 Solver.markOverdefined(AI);
1657 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001658 Solver.AddTrackedFunction(F);
Chris Lattner3774c912009-11-02 19:31:10 +00001659 }
Chris Lattnerff3ca152009-11-02 06:34:04 +00001660 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001661
Chris Lattnerdd336d12004-12-11 05:15:59 +00001662 // Loop over global variables. We inform the solver about any internal global
1663 // variables that do not have their 'addresses taken'. If they don't have
1664 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001665 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1666 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001667 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001668 Solver.TrackValueOfGlobalVariable(G);
1669
Chris Lattner59acc7d2004-12-10 08:02:06 +00001670 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001671 bool ResolvedUndefs = true;
1672 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001673 Solver.Solve();
1674
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001675 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001676 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001677 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001678 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001679 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001680
1681 bool MadeChanges = false;
1682
1683 // Iterate over all of the instructions in the module, replacing them with
1684 // constants if we have found them to be of constant values.
1685 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001686 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001687
Chris Lattner59acc7d2004-12-10 08:02:06 +00001688 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001689 if (Solver.isBlockExecutable(F->begin())) {
1690 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1691 AI != E; ++AI) {
1692 if (AI->use_empty()) continue;
1693
1694 LatticeVal IV = Solver.getLatticeValueFor(AI);
1695 if (IV.isOverdefined()) continue;
1696
1697 Constant *CST = IV.isConstant() ?
1698 IV.getConstant() : UndefValue::get(AI->getType());
1699 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1700
1701 // Replaces all of the uses of a variable with uses of the
1702 // constant.
1703 AI->replaceAllUsesWith(CST);
1704 ++IPNumArgsElimed;
1705 }
Chris Lattner8db50122009-11-02 02:54:24 +00001706 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001707
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001708 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001709 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001710 DeleteInstructionInBlock(BB);
1711 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001712
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001713 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001714 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1715 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001716 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001717 TI->getSuccessor(i)->removePredecessor(BB);
1718 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001719 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001720 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001721 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001722
Chris Lattner864737b2004-12-11 05:32:19 +00001723 if (&*BB != &F->front())
1724 BlocksToErase.push_back(BB);
1725 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001726 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001727 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001728 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001729
1730 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1731 Instruction *Inst = BI++;
1732 if (Inst->getType()->isVoidTy())
1733 continue;
1734
Chris Lattner8db50122009-11-02 02:54:24 +00001735 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1736 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001737 continue;
1738
1739 Constant *Const = IV.isConstant()
1740 ? IV.getConstant() : UndefValue::get(Inst->getType());
1741 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1742
1743 // Replaces all of the uses of a variable with uses of the
1744 // constant.
1745 Inst->replaceAllUsesWith(Const);
1746
1747 // Delete the instruction.
1748 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1749 Inst->eraseFromParent();
1750
1751 // Hey, we just changed something!
1752 MadeChanges = true;
1753 ++IPNumInstRemoved;
1754 }
1755 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001756
1757 // Now that all instructions in the function are constant folded, erase dead
1758 // blocks, because we can now use ConstantFoldTerminator to get rid of
1759 // in-edges.
1760 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1761 // If there are any PHI nodes in this successor, drop entries for BB now.
1762 BasicBlock *DeadBB = BlocksToErase[i];
1763 while (!DeadBB->use_empty()) {
1764 Instruction *I = cast<Instruction>(DeadBB->use_back());
1765 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001766 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001767 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001768 // if this is a branch or switch on undef. Fold it manually as a
1769 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001770#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001771 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1772 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1773 "Branch should be foldable!");
1774 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1775 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1776 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001777 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001778 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001779#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001780
1781 // Make this an uncond branch to the first successor.
1782 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001783 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001784
1785 // Remove entries in successor phi nodes to remove edges.
1786 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1787 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1788
1789 // Remove the old terminator.
1790 TI->eraseFromParent();
1791 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001792 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001793
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001794 // Finally, delete the basic block.
1795 F->getBasicBlockList().erase(DeadBB);
1796 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001797 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001798 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001799
1800 // If we inferred constant or undef return values for a function, we replaced
1801 // all call uses with the inferred value. This means we don't need to bother
1802 // actually returning anything from the function. Replace all return
1803 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001804 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001805 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001806 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner3774c912009-11-02 19:31:10 +00001807 E = RV.end(); I != E; ++I)
1808 if (!I->second.isOverdefined() &&
1809 !I->first->getReturnType()->isVoidTy()) {
1810 Function *F = I->first;
1811 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1812 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1813 if (!isa<UndefValue>(RI->getOperand(0)))
1814 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1815 }
1816
Chris Lattnerdd336d12004-12-11 05:15:59 +00001817 // If we infered constant or undef values for globals variables, we can delete
1818 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001819 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1820 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001821 E = TG.end(); I != E; ++I) {
1822 GlobalVariable *GV = I->first;
1823 assert(!I->second.isOverdefined() &&
1824 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001825 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001826 while (!GV->use_empty()) {
1827 StoreInst *SI = cast<StoreInst>(GV->use_back());
1828 SI->eraseFromParent();
1829 }
1830 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001831 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001832 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001833
Chris Lattner59acc7d2004-12-10 08:02:06 +00001834 return MadeChanges;
1835}