blob: 83fcd8434b5cee2e57e5e5bb4483e3257d18a9c8 [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"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000028#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000029#include "llvm/Transforms/Utils/Local.h"
Chris Lattner5638dc62009-11-02 06:06:14 +000030#include "llvm/Target/TargetData.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000031#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattner79272202009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Chris Lattner09275292009-11-02 06:11:23 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000043#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000044#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
Chris Lattner0dbfc052002-04-29 21:26:08 +000054namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000055/// LatticeVal class - This class represents the different lattice values that
56/// an LLVM value may occupy. It is a simple class with value semantics.
57///
Chris Lattner3e8b6632009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000059 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000060 /// undefined - This LLVM Value has no known value yet.
61 undefined,
62
63 /// constant - This LLVM Value has a specific constant value.
64 constant,
65
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
69 /// asserting.
70 forcedconstant,
71
72 /// overdefined - This instruction is not known to be constant, and we know
73 /// it has a value.
74 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000075 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000080
Chris Lattner79272202009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Chris Lattner138a1242001-06-27 23:38:11 +000085public:
Chris Lattner38871e42009-11-02 03:03:42 +000086 LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000087
Chris Lattner38871e42009-11-02 03:03:42 +000088 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000090 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
Chris Lattner38871e42009-11-02 03:03:42 +000092 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner79272202009-11-02 02:20:32 +000093
Chris Lattner38871e42009-11-02 03:03:42 +000094 Constant *getConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000095 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
97 }
98
99 /// markOverdefined - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000100 bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000106 }
107
Chris Lattner79272202009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000109 bool markConstant(Constant *V) {
Chris Lattnerc175e5d2009-11-03 16:50:11 +0000110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattner79272202009-11-02 02:20:32 +0000111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000113 }
Chris Lattner79272202009-11-02 02:20:32 +0000114
115 if (isUndefined()) {
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
118 Val.setPointer(V);
119 } else {
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
124
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
129 }
130 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000131 }
132
Chris Lattner36c99522009-11-02 03:21:36 +0000133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
136 if (isConstant())
137 return dyn_cast<ConstantInt>(getConstant());
138 return 0;
139 }
140
Chris Lattner38871e42009-11-02 03:03:42 +0000141 void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
144 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000145 }
Chris Lattner138a1242001-06-27 23:38:11 +0000146};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000147} // end anonymous namespace.
148
149
150namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000151
Chris Lattner138a1242001-06-27 23:38:11 +0000152//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000153//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000154/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155/// Constant Propagation.
156///
157class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner5638dc62009-11-02 06:06:14 +0000158 const TargetData *TD;
Chris Lattner09275292009-11-02 06:11:23 +0000159 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000161
Chris Lattnerdd336d12004-12-11 05:15:59 +0000162 /// GlobalValue - If we are tracking any values for the contents of a global
163 /// variable, we keep a mapping from the constant accessor to the element of
164 /// the global, to the currently known value. If the value becomes
165 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000166 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000167
Devang Patel7c490d42008-03-11 05:46:42 +0000168 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000169 /// value out of a function, it will have an entry in this map, indicating
170 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000171 DenseMap<Function*, LatticeVal> TrackedRetVals;
172
173 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
174 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000175 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000176
Chris Lattnerabf67ef2009-11-03 20:52:57 +0000177 /// TrackingIncomingArguments - This is the set of functions for whose
178 /// arguments we make optimistic assumptions about and try to prove as
179 /// constants.
Chris Lattner2396cc32009-11-03 19:24:51 +0000180 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
181
Chris Lattner38871e42009-11-02 03:03:42 +0000182 /// The reason for two worklists is that overdefined is the lowest state
183 /// on the lattice, and moving things to overdefined as fast as possible
184 /// makes SCCP converge much faster.
185 ///
186 /// By having a separate worklist, we accomplish this because everything
187 /// possibly overdefined will become overdefined at the soonest possible
188 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000189 SmallVector<Value*, 64> OverdefinedInstWorkList;
190 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000191
192
Chris Lattnercf712de2008-08-23 23:36:38 +0000193 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000194
Chris Lattner1daee8b2004-01-12 03:57:30 +0000195 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
196 /// overdefined, despite the fact that the PHI node is overdefined.
197 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
198
Chris Lattner16b18fd2003-10-08 16:55:34 +0000199 /// KnownFeasibleEdges - Entries in this set are edges which have already had
200 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000201 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
202 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000203public:
Chris Lattner5638dc62009-11-02 06:06:14 +0000204 SCCPSolver(const TargetData *td) : TD(td) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000205
Chris Lattner82bec2c2004-11-15 04:44:20 +0000206 /// MarkBlockExecutable - This method can be used by clients to mark all of
207 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner09275292009-11-02 06:11:23 +0000208 ///
209 /// This returns true if the block was not considered live before.
210 bool MarkBlockExecutable(BasicBlock *BB) {
211 if (!BBExecutable.insert(BB)) return false;
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000212 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000213 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner09275292009-11-02 06:11:23 +0000214 return true;
Chris Lattner0dbfc052002-04-29 21:26:08 +0000215 }
216
Chris Lattnerdd336d12004-12-11 05:15:59 +0000217 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000218 /// inform the SCCPSolver that it should track loads and stores to the
219 /// specified global variable if it can. This is only legal to call if
220 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000221 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
222 const Type *ElTy = GV->getType()->getElementType();
223 if (ElTy->isFirstClassType()) {
224 LatticeVal &IV = TrackedGlobals[GV];
225 if (!isa<UndefValue>(GV->getInitializer()))
226 IV.markConstant(GV->getInitializer());
227 }
228 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000229
230 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
231 /// and out of the specified function (which cannot have its address taken),
232 /// this method must be called.
233 void AddTrackedFunction(Function *F) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000234 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000235 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
236 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000237 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
238 LatticeVal()));
239 } else
240 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000241 }
242
Chris Lattner2396cc32009-11-03 19:24:51 +0000243 void AddArgumentTrackedFunction(Function *F) {
244 TrackingIncomingArguments.insert(F);
245 }
246
Chris Lattner82bec2c2004-11-15 04:44:20 +0000247 /// Solve - Solve for constants and executable blocks.
248 ///
249 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000250
Chris Lattner3bad2532006-12-20 06:21:33 +0000251 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000252 /// that branches on undef values cannot reach any of their successors.
253 /// However, this is not a safe assumption. After we solve dataflow, this
254 /// method should be use to handle this. If this returns true, the solver
255 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000256 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000257
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000258 bool isBlockExecutable(BasicBlock *BB) const {
259 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000260 }
261
Chris Lattner8db50122009-11-02 02:54:24 +0000262 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000263 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000264 assert(I != ValueState.end() && "V is not in valuemap!");
265 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000266 }
267
Devang Patel7c490d42008-03-11 05:46:42 +0000268 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000269 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000270 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
271 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000272 }
273
Chris Lattnerdd336d12004-12-11 05:15:59 +0000274 /// getTrackedGlobals - Get and return the set of inferred initializers for
275 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000276 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000277 return TrackedGlobals;
278 }
279
Chris Lattner36c99522009-11-02 03:21:36 +0000280 void markOverdefined(Value *V) {
Chris Lattner57939df2007-03-04 04:50:21 +0000281 markOverdefined(ValueState[V], V);
282 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000283
Chris Lattner138a1242001-06-27 23:38:11 +0000284private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000285 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000286 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000287 // the users of the instruction are updated later.
288 //
Chris Lattner38871e42009-11-02 03:03:42 +0000289 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
290 if (!IV.markConstant(C)) return;
291 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
292 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000293 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000294
Chris Lattner38871e42009-11-02 03:03:42 +0000295 void markConstant(Value *V, Constant *C) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000296 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000297 }
298
Chris Lattner2a0433b2009-11-02 05:55:40 +0000299 void markForcedConstant(Value *V, Constant *C) {
300 ValueState[V].markForcedConstant(C);
301 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
302 InstWorkList.push_back(V);
303 }
304
305
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000306 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000307 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000308 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000309 void markOverdefined(LatticeVal &IV, Value *V) {
310 if (!IV.markOverdefined()) return;
311
312 DEBUG(errs() << "markOverdefined: ";
313 if (Function *F = dyn_cast<Function>(V))
314 errs() << "Function '" << F->getName() << "'\n";
315 else
316 errs() << *V << '\n');
317 // Only instructions go on the work list
318 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000319 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000320
Chris Lattner2a0433b2009-11-02 05:55:40 +0000321 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000322 if (IV.isOverdefined() || MergeWithV.isUndefined())
323 return; // Noop.
324 if (MergeWithV.isOverdefined())
325 markOverdefined(IV, V);
326 else if (IV.isUndefined())
327 markConstant(IV, V, MergeWithV.getConstant());
328 else if (IV.getConstant() != MergeWithV.getConstant())
329 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000330 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000331
Chris Lattner2a0433b2009-11-02 05:55:40 +0000332 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattner36c99522009-11-02 03:21:36 +0000333 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000334 }
335
Chris Lattner138a1242001-06-27 23:38:11 +0000336
Chris Lattner2a0433b2009-11-02 05:55:40 +0000337 /// getValueState - Return the LatticeVal object that corresponds to the
338 /// value. This function handles the case when the value hasn't been seen yet
339 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000340 LatticeVal &getValueState(Value *V) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000341 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000342 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000343
Chris Lattner36c99522009-11-02 03:21:36 +0000344 LatticeVal &LV = ValueState[V];
345
Chris Lattner3bad2532006-12-20 06:21:33 +0000346 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000347 // Undef values remain undefined.
348 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000349 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000350 }
Chris Lattner36c99522009-11-02 03:21:36 +0000351
Chris Lattner2f096252009-11-02 02:33:50 +0000352 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000353 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000354 }
355
Chris Lattner2a0433b2009-11-02 05:55:40 +0000356 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
357 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000358 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
359 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
360 return; // This edge is already known to be executable!
361
Chris Lattner09275292009-11-02 06:11:23 +0000362 if (!MarkBlockExecutable(Dest)) {
363 // If the destination is already executable, we just made an *edge*
364 // feasible that wasn't before. Revisit the PHI nodes in the block
365 // because they have potentially new operands.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000366 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
367 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000368
Chris Lattner09275292009-11-02 06:11:23 +0000369 PHINode *PN;
370 for (BasicBlock::iterator I = Dest->begin();
371 (PN = dyn_cast<PHINode>(I)); ++I)
372 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000373 }
Chris Lattner138a1242001-06-27 23:38:11 +0000374 }
375
Chris Lattner82bec2c2004-11-15 04:44:20 +0000376 // getFeasibleSuccessors - Return a vector of booleans to indicate which
377 // successors are reachable from a given terminator instruction.
378 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000379 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000380
381 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000382 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000383 //
384 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
385
386 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000387 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000388 // information, we need to update the specified user of this instruction.
389 //
Chris Lattner14532d02009-11-03 03:42:51 +0000390 void OperandChangedState(Instruction *I) {
391 if (BBExecutable.count(I->getParent())) // Inst is executable?
392 visit(*I);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000393 }
Chris Lattnere01985c2009-11-02 06:28:16 +0000394
395 /// RemoveFromOverdefinedPHIs - If I has any entries in the
396 /// UsersOfOverdefinedPHIs map for PN, remove them now.
397 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
398 if (UsersOfOverdefinedPHIs.empty()) return;
399 std::multimap<PHINode*, Instruction*>::iterator It, E;
400 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
401 while (It != E) {
402 if (It->second == I)
403 UsersOfOverdefinedPHIs.erase(It++);
404 else
405 ++It;
406 }
407 }
Chris Lattner82bec2c2004-11-15 04:44:20 +0000408
409private:
410 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000411
Chris Lattner2f096252009-11-02 02:33:50 +0000412 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000413 // operand made a transition, or the instruction is newly executable. Change
414 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000415 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000416
417 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000418 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000419 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000420
Chris Lattnerb8047602002-08-14 17:53:45 +0000421 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000422 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000423 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000424 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000425 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000426 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000427 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000428 void visitExtractValueInst(ExtractValueInst &EVI);
429 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000430
Chris Lattner2f096252009-11-02 02:33:50 +0000431 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000432 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000433 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000434 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000435 void visitCallInst (CallInst &I) {
Chris Lattner32c0d222009-09-27 21:35:11 +0000436 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000437 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000438 void visitInvokeInst (InvokeInst &II) {
439 visitCallSite(CallSite::get(&II));
440 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000441 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000442 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000443 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000444 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000445 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000446 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
447 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000448
Chris Lattner7e708292002-06-25 16:13:24 +0000449 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000450 // If a new instruction is added to LLVM that we don't handle.
Chris Lattnerbdff5482009-08-23 04:37:46 +0000451 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000452 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000453 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000454};
Chris Lattnerf6293092002-07-23 18:06:35 +0000455
Duncan Sandse2abf122007-07-20 08:56:21 +0000456} // end anonymous namespace
457
458
Chris Lattnerb9a66342002-05-02 21:44:00 +0000459// getFeasibleSuccessors - Return a vector of booleans to indicate which
460// successors are reachable from a given terminator instruction.
461//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000462void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000463 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000464 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000465 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000466 if (BI->isUnconditional()) {
467 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000468 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000469 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000470
Chris Lattner2a0433b2009-11-02 05:55:40 +0000471 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000472 ConstantInt *CI = BCValue.getConstantInt();
473 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000474 // Overdefined condition variables, and branches on unfoldable constant
475 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000476 if (!BCValue.isUndefined())
477 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000478 return;
479 }
480
481 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000482 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000483 return;
484 }
485
Chris Lattner36c99522009-11-02 03:21:36 +0000486 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000487 // Invoke instructions successors are always executable.
488 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000489 return;
490 }
491
492 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000493 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000494 ConstantInt *CI = SCValue.getConstantInt();
495
496 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000497 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000498 if (!SCValue.isUndefined())
499 Succs.assign(TI.getNumSuccessors(), true);
500 return;
501 }
502
503 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000504 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000505 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000506
507 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
508 if (isa<IndirectBrInst>(&TI)) {
509 // Just mark all destinations executable!
510 Succs.assign(TI.getNumSuccessors(), true);
511 return;
512 }
513
514#ifndef NDEBUG
515 errs() << "Unknown terminator instruction: " << TI << '\n';
516#endif
517 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000518}
519
520
Chris Lattner59f0ce22002-05-02 21:18:01 +0000521// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000522// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000523//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000524bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000525 assert(BBExecutable.count(To) && "Dest should always be alive!");
526
527 // Make sure the source basic block is executable!!
528 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000529
Chris Lattner2f096252009-11-02 02:33:50 +0000530 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000531 TerminatorInst *TI = From->getTerminator();
532 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
533 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000534 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000535
Chris Lattner2a0433b2009-11-02 05:55:40 +0000536 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000537
Chris Lattnerea0db072009-11-02 02:30:06 +0000538 // Overdefined condition variables mean the branch could go either way,
539 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000540 ConstantInt *CI = BCValue.getConstantInt();
541 if (CI == 0)
542 return !BCValue.isUndefined();
Chris Lattnerea0db072009-11-02 02:30:06 +0000543
Chris Lattnerea0db072009-11-02 02:30:06 +0000544 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000545 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000546 }
547
548 // Invoke instructions successors are always executable.
549 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000550 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000551
552 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000553 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000554 ConstantInt *CI = SCValue.getConstantInt();
555
556 if (CI == 0)
557 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000558
Chris Lattner36c99522009-11-02 03:21:36 +0000559 // Make sure to skip the "default value" which isn't a value
560 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
561 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
562 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000563
Chris Lattner36c99522009-11-02 03:21:36 +0000564 // If the constant value is not equal to any of the branches, we must
565 // execute default branch.
566 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000567 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000568
569 // Just mark all destinations executable!
570 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
571 if (isa<IndirectBrInst>(&TI))
572 return true;
573
574#ifndef NDEBUG
575 errs() << "Unknown terminator instruction: " << *TI << '\n';
576#endif
577 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000578}
Chris Lattner138a1242001-06-27 23:38:11 +0000579
Chris Lattner2f096252009-11-02 02:33:50 +0000580// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000581// operand made a transition, or the instruction is newly executable. Change
582// the value type of I to reflect these changes if appropriate. This method
583// makes sure to do the following actions:
584//
585// 1. If a phi node merges two constants in, and has conflicting value coming
586// from different branches, or if the PHI node merges in an overdefined
587// value, then the PHI node becomes overdefined.
588// 2. If a phi node merges only constants in, and they all agree on value, the
589// PHI node becomes a constant value equal to that.
590// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
591// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
592// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
593// 6. If a conditional branch has a value that is constant, make the selected
594// destination executable
595// 7. If a conditional branch has a value that is overdefined, make all
596// successors executable.
597//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000598void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000599 if (getValueState(&PN).isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000600 // There may be instructions using this PHI node that are not overdefined
601 // themselves. If so, make sure that they know that the PHI node operand
602 // changed.
603 std::multimap<PHINode*, Instruction*>::iterator I, E;
604 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000605 if (I == E)
606 return;
607
608 SmallVector<Instruction*, 16> Users;
609 for (; I != E; ++I)
610 Users.push_back(I->second);
611 while (!Users.empty())
612 visit(Users.pop_back_val());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000613 return; // Quick exit
614 }
Chris Lattner138a1242001-06-27 23:38:11 +0000615
Chris Lattnera2f652d2004-03-16 19:49:59 +0000616 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
617 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000618 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000619 return markOverdefined(&PN);
Chris Lattnera2f652d2004-03-16 19:49:59 +0000620
Chris Lattner2a632552002-04-18 15:13:15 +0000621 // Look at all of the executable operands of the PHI node. If any of them
622 // are overdefined, the PHI becomes overdefined as well. If they are all
623 // constant, and they agree with each other, the PHI becomes the identical
624 // constant. If they are constant and don't agree, the PHI is overdefined.
625 // If there are no executable operands, the PHI remains undefined.
626 //
Chris Lattner9de28282003-04-25 02:50:03 +0000627 Constant *OperandVal = 0;
628 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000629 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000630 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000631
Chris Lattner38871e42009-11-02 03:03:42 +0000632 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
633 continue;
634
635 if (IV.isOverdefined()) // PHI node becomes overdefined!
636 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000637
Chris Lattner38871e42009-11-02 03:03:42 +0000638 if (OperandVal == 0) { // Grab the first value.
639 OperandVal = IV.getConstant();
640 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000641 }
Chris Lattner38871e42009-11-02 03:03:42 +0000642
643 // There is already a reachable operand. If we conflict with it,
644 // then the PHI node becomes overdefined. If we agree with it, we
645 // can continue on.
646
647 // Check to see if there are two different constants merging, if so, the PHI
648 // node is overdefined.
649 if (IV.getConstant() != OperandVal)
650 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000651 }
652
Chris Lattner2a632552002-04-18 15:13:15 +0000653 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000654 // arguments that agree with each other(and OperandVal is the constant) or
655 // OperandVal is null because there are no defined incoming arguments. If
656 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000657 //
Chris Lattner9de28282003-04-25 02:50:03 +0000658 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000659 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000660}
661
Chris Lattner14532d02009-11-03 03:42:51 +0000662
663
664
Chris Lattner59acc7d2004-12-10 08:02:06 +0000665void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000666 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000667
Chris Lattner59acc7d2004-12-10 08:02:06 +0000668 Function *F = I.getParent()->getParent();
Chris Lattner14532d02009-11-03 03:42:51 +0000669
Devang Patel7c490d42008-03-11 05:46:42 +0000670 // If we are tracking the return value of this function, merge it in.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000671 if (!TrackedRetVals.empty()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000672 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000673 TrackedRetVals.find(F);
Chris Lattner14532d02009-11-03 03:42:51 +0000674 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000675 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
Devang Patel7c490d42008-03-11 05:46:42 +0000676 return;
677 }
678 }
679
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000680 // Handle functions that return multiple values.
Chris Lattner574fa9e2009-11-02 06:17:06 +0000681 if (!TrackedMultipleRetVals.empty() &&
682 isa<StructType>(I.getOperand(0)->getType())) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000683 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
684 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000685 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000686 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
687 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000688 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000689 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000690 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000691 }
692}
693
Chris Lattner82bec2c2004-11-15 04:44:20 +0000694void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000695 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000696 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000697
Chris Lattner16b18fd2003-10-08 16:55:34 +0000698 BasicBlock *BB = TI.getParent();
699
Chris Lattner2f096252009-11-02 02:33:50 +0000700 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000701 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000702 if (SuccFeasible[i])
703 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000704}
705
Chris Lattner82bec2c2004-11-15 04:44:20 +0000706void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000707 LatticeVal OpSt = getValueState(I.getOperand(0));
708 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000709 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000710 else if (OpSt.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000711 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000712 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000713}
714
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000715void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000716 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000717
Dan Gohman60ea2682008-06-20 16:41:17 +0000718 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000719 if (isa<UndefValue>(Aggr))
720 return;
721
722 // Currently only handle single-index extractvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000723 if (EVI.getNumIndices() != 1)
724 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000725
726 Function *F = 0;
727 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
728 F = CI->getCalledFunction();
729 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
730 F = II->getCalledFunction();
731
732 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
733 // result back!
Chris Lattner38871e42009-11-02 03:03:42 +0000734 if (F == 0 || TrackedMultipleRetVals.empty())
735 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000736
Chris Lattnercf712de2008-08-23 23:36:38 +0000737 // See if we are tracking the result of the callee. If not tracking this
738 // function (for example, it is a declaration) just move to overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000739 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
740 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000741
742 // Otherwise, the value will be merged in here as a result of CallSite
743 // handling.
744}
745
746void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000747 Value *Aggr = IVI.getAggregateOperand();
748 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000749
Dan Gohman60ea2682008-06-20 16:41:17 +0000750 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000751 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000752 return;
753
754 // Currently only handle single-index insertvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000755 if (IVI.getNumIndices() != 1)
756 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000757
758 // Currently only handle insertvalue instructions that are in a single-use
759 // chain that builds up a return value.
760 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
Chris Lattner38871e42009-11-02 03:03:42 +0000761 if (!TmpIVI->hasOneUse())
762 return markOverdefined(&IVI);
763
Dan Gohmandfaceb42008-06-20 16:39:44 +0000764 const Value *V = *TmpIVI->use_begin();
765 if (isa<ReturnInst>(V))
766 break;
767 TmpIVI = dyn_cast<InsertValueInst>(V);
Chris Lattner38871e42009-11-02 03:03:42 +0000768 if (!TmpIVI)
769 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000770 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000771
772 // See if we are tracking the result of the callee.
773 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000774 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000775 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
776
777 // Merge in the inserted member value.
778 if (It != TrackedMultipleRetVals.end())
779 mergeInValue(It->second, F, getValueState(Val));
780
Dan Gohman60ea2682008-06-20 16:41:17 +0000781 // Mark the aggregate result of the IVI overdefined; any tracking that we do
782 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000783 markOverdefined(&IVI);
784}
785
Chris Lattner82bec2c2004-11-15 04:44:20 +0000786void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000787 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000788 if (CondValue.isUndefined())
789 return;
Chris Lattner36c99522009-11-02 03:21:36 +0000790
791 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000792 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
793 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000794 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000795 }
796
797 // Otherwise, the condition is overdefined or a constant we can't evaluate.
798 // See if we can produce something better than overdefined based on the T/F
799 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000800 LatticeVal TVal = getValueState(I.getTrueValue());
801 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000802
803 // select ?, C, C -> C.
804 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000805 TVal.getConstant() == FVal.getConstant())
806 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000807
Chris Lattner2a0433b2009-11-02 05:55:40 +0000808 if (TVal.isUndefined()) // select ?, undef, X -> X.
809 return mergeInValue(&I, FVal);
810 if (FVal.isUndefined()) // select ?, X, undef -> X.
811 return mergeInValue(&I, TVal);
812 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000813}
814
Chris Lattner2a0433b2009-11-02 05:55:40 +0000815// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000816void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000817 LatticeVal V1State = getValueState(I.getOperand(0));
818 LatticeVal V2State = getValueState(I.getOperand(1));
819
Chris Lattneref36dfd2004-11-15 05:03:30 +0000820 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000821 if (IV.isOverdefined()) return;
822
Chris Lattner2a0433b2009-11-02 05:55:40 +0000823 if (V1State.isConstant() && V2State.isConstant())
824 return markConstant(IV, &I,
825 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
826 V2State.getConstant()));
827
828 // If something is undef, wait for it to resolve.
829 if (!V1State.isOverdefined() && !V2State.isOverdefined())
830 return;
831
832 // Otherwise, one of our operands is overdefined. Try to produce something
833 // better than overdefined with some tricks.
834
835 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
836 // operand is overdefined.
837 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
838 LatticeVal *NonOverdefVal = 0;
839 if (!V1State.isOverdefined())
840 NonOverdefVal = &V1State;
841 else if (!V2State.isOverdefined())
842 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000843
Chris Lattner2a0433b2009-11-02 05:55:40 +0000844 if (NonOverdefVal) {
845 if (NonOverdefVal->isUndefined()) {
846 // Could annihilate value.
847 if (I.getOpcode() == Instruction::And)
848 markConstant(IV, &I, Constant::getNullValue(I.getType()));
849 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
850 markConstant(IV, &I, Constant::getAllOnesValue(PT));
851 else
852 markConstant(IV, &I,
853 Constant::getAllOnesValue(I.getType()));
854 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000855 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000856
857 if (I.getOpcode() == Instruction::And) {
858 // X and 0 = 0
859 if (NonOverdefVal->getConstant()->isNullValue())
860 return markConstant(IV, &I, NonOverdefVal->getConstant());
861 } else {
862 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
863 if (CI->isAllOnesValue()) // X or -1 = -1
864 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000865 }
866 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000867 }
Chris Lattnera177c672004-12-11 23:15:19 +0000868
869
Chris Lattner2a0433b2009-11-02 05:55:40 +0000870 // If both operands are PHI nodes, it is possible that this instruction has
871 // a constant value, despite the fact that the PHI node doesn't. Check for
872 // this condition now.
873 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
874 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
875 if (PN1->getParent() == PN2->getParent()) {
876 // Since the two PHI nodes are in the same basic block, they must have
877 // entries for the same predecessors. Walk the predecessor list, and
878 // if all of the incoming values are constants, and the result of
879 // evaluating this expression with all incoming value pairs is the
880 // same, then this expression is a constant even though the PHI node
881 // is not a constant!
882 LatticeVal Result;
883 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
884 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
885 BasicBlock *InBlock = PN1->getIncomingBlock(i);
886 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000887
Chris Lattner2a0433b2009-11-02 05:55:40 +0000888 if (In1.isOverdefined() || In2.isOverdefined()) {
889 Result.markOverdefined();
890 break; // Cannot fold this operation over the PHI nodes!
891 }
892
893 if (In1.isConstant() && In2.isConstant()) {
894 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
895 In2.getConstant());
896 if (Result.isUndefined())
897 Result.markConstant(V);
898 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000899 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000900 break;
Chris Lattner38871e42009-11-02 03:03:42 +0000901 }
Chris Lattner1daee8b2004-01-12 03:57:30 +0000902 }
903 }
904
Chris Lattner2a0433b2009-11-02 05:55:40 +0000905 // If we found a constant value here, then we know the instruction is
906 // constant despite the fact that the PHI nodes are overdefined.
907 if (Result.isConstant()) {
908 markConstant(IV, &I, Result.getConstant());
909 // Remember that this instruction is virtually using the PHI node
910 // operands.
911 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
912 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
913 return;
914 }
915
916 if (Result.isUndefined())
917 return;
918
919 // Okay, this really is overdefined now. Since we might have
920 // speculatively thought that this was not overdefined before, and
921 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
922 // make sure to clean out any entries that we put there, for
923 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +0000924 RemoveFromOverdefinedPHIs(&I, PN1);
925 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000926 }
927
928 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +0000929}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000930
Chris Lattner2f096252009-11-02 02:33:50 +0000931// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000932void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000933 LatticeVal V1State = getValueState(I.getOperand(0));
934 LatticeVal V2State = getValueState(I.getOperand(1));
935
Reid Spencere4d87aa2006-12-23 06:05:41 +0000936 LatticeVal &IV = ValueState[&I];
937 if (IV.isOverdefined()) return;
938
Chris Lattner2a0433b2009-11-02 05:55:40 +0000939 if (V1State.isConstant() && V2State.isConstant())
940 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
941 V1State.getConstant(),
942 V2State.getConstant()));
943
944 // If operands are still undefined, wait for it to resolve.
945 if (!V1State.isOverdefined() && !V2State.isOverdefined())
946 return;
947
948 // If something is overdefined, use some tricks to avoid ending up and over
949 // defined if we can.
950
951 // If both operands are PHI nodes, it is possible that this instruction has
952 // a constant value, despite the fact that the PHI node doesn't. Check for
953 // this condition now.
954 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
955 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
956 if (PN1->getParent() == PN2->getParent()) {
957 // Since the two PHI nodes are in the same basic block, they must have
958 // entries for the same predecessors. Walk the predecessor list, and
959 // if all of the incoming values are constants, and the result of
960 // evaluating this expression with all incoming value pairs is the
961 // same, then this expression is a constant even though the PHI node
962 // is not a constant!
963 LatticeVal Result;
964 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
965 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
966 BasicBlock *InBlock = PN1->getIncomingBlock(i);
967 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000968
Chris Lattner2a0433b2009-11-02 05:55:40 +0000969 if (In1.isOverdefined() || In2.isOverdefined()) {
970 Result.markOverdefined();
971 break; // Cannot fold this operation over the PHI nodes!
972 }
973
974 if (In1.isConstant() && In2.isConstant()) {
975 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
976 In1.getConstant(),
977 In2.getConstant());
978 if (Result.isUndefined())
979 Result.markConstant(V);
980 else if (Result.isConstant() && Result.getConstant() != V) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000981 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000982 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000983 }
984 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000985 }
986
Chris Lattner2a0433b2009-11-02 05:55:40 +0000987 // If we found a constant value here, then we know the instruction is
988 // constant despite the fact that the PHI nodes are overdefined.
989 if (Result.isConstant()) {
990 markConstant(&I, Result.getConstant());
991 // Remember that this instruction is virtually using the PHI node
992 // operands.
993 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
994 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
995 return;
996 }
997
998 if (Result.isUndefined())
999 return;
1000
1001 // Okay, this really is overdefined now. Since we might have
1002 // speculatively thought that this was not overdefined before, and
1003 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1004 // make sure to clean out any entries that we put there, for
1005 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +00001006 RemoveFromOverdefinedPHIs(&I, PN1);
1007 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001008 }
1009
1010 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001011}
1012
Robert Bocchino56107e22006-01-10 19:05:05 +00001013void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001014 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001015 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001016
1017#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001018 LatticeVal &ValState = getValueState(I.getOperand(0));
1019 LatticeVal &IdxState = getValueState(I.getOperand(1));
1020
1021 if (ValState.isOverdefined() || IdxState.isOverdefined())
1022 markOverdefined(&I);
1023 else if(ValState.isConstant() && IdxState.isConstant())
1024 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1025 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001026#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001027}
1028
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001029void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001030 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001031 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001032#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001033 LatticeVal &ValState = getValueState(I.getOperand(0));
1034 LatticeVal &EltState = getValueState(I.getOperand(1));
1035 LatticeVal &IdxState = getValueState(I.getOperand(2));
1036
1037 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1038 IdxState.isOverdefined())
1039 markOverdefined(&I);
1040 else if(ValState.isConstant() && EltState.isConstant() &&
1041 IdxState.isConstant())
1042 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1043 EltState.getConstant(),
1044 IdxState.getConstant()));
1045 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001046 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001047 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1048 EltState.getConstant(),
1049 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001050#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001051}
1052
Chris Lattner543abdf2006-04-08 01:19:12 +00001053void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001054 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001055 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001056#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001057 LatticeVal &V1State = getValueState(I.getOperand(0));
1058 LatticeVal &V2State = getValueState(I.getOperand(1));
1059 LatticeVal &MaskState = getValueState(I.getOperand(2));
1060
1061 if (MaskState.isUndefined() ||
1062 (V1State.isUndefined() && V2State.isUndefined()))
1063 return; // Undefined output if mask or both inputs undefined.
1064
1065 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1066 MaskState.isOverdefined()) {
1067 markOverdefined(&I);
1068 } else {
1069 // A mix of constant/undef inputs.
1070 Constant *V1 = V1State.isConstant() ?
1071 V1State.getConstant() : UndefValue::get(I.getType());
1072 Constant *V2 = V2State.isConstant() ?
1073 V2State.getConstant() : UndefValue::get(I.getType());
1074 Constant *Mask = MaskState.isConstant() ?
1075 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1076 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1077 }
Devang Patel67a821d2006-12-04 23:54:59 +00001078#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001079}
1080
Chris Lattner2f096252009-11-02 02:33:50 +00001081// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001082// can turn this into a getelementptr ConstantExpr.
1083//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001084void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner5cc66d92009-11-02 23:25:39 +00001085 if (ValueState[&I].isOverdefined()) return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001086
Chris Lattnere777ff22007-02-02 20:51:48 +00001087 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001088 Operands.reserve(I.getNumOperands());
1089
1090 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001091 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001092 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001093 return; // Operands are not resolved yet.
1094
Chris Lattner38871e42009-11-02 03:03:42 +00001095 if (State.isOverdefined())
Chris Lattner5cc66d92009-11-02 23:25:39 +00001096 return markOverdefined(&I);
Chris Lattner38871e42009-11-02 03:03:42 +00001097
Chris Lattner2a88bb72002-08-30 23:39:00 +00001098 assert(State.isConstant() && "Unknown state!");
1099 Operands.push_back(State.getConstant());
1100 }
1101
1102 Constant *Ptr = Operands[0];
Chris Lattner2a0433b2009-11-02 05:55:40 +00001103 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1104 Operands.size()-1));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001105}
Brian Gaeked0fde302003-11-11 22:41:34 +00001106
Chris Lattner2a0433b2009-11-02 05:55:40 +00001107void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001108 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1109 return;
Chris Lattner2a0433b2009-11-02 05:55:40 +00001110
Chris Lattnerdd336d12004-12-11 05:15:59 +00001111 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001112 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001113 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1114
Chris Lattner2a0433b2009-11-02 05:55:40 +00001115 // Get the value we are storing into the global, then merge it.
1116 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001117 if (I->second.isOverdefined())
1118 TrackedGlobals.erase(I); // No need to keep tracking this!
1119}
1120
1121
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001122// Handle load instructions. If the operand is a constant pointer to a constant
1123// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001124void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001125 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001126 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner2a0433b2009-11-02 05:55:40 +00001127
Chris Lattneref36dfd2004-11-15 05:03:30 +00001128 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001129 if (IV.isOverdefined()) return;
1130
Chris Lattner2a0433b2009-11-02 05:55:40 +00001131 if (!PtrVal.isConstant() || I.isVolatile())
1132 return markOverdefined(IV, &I);
1133
Chris Lattner5638dc62009-11-02 06:06:14 +00001134 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001135
Chris Lattner2a0433b2009-11-02 05:55:40 +00001136 // load null -> null
1137 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1138 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1139
1140 // Transform load (constant global) into the value loaded.
1141 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001142 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001143 // If we are tracking this global, merge in the known value for it.
1144 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1145 TrackedGlobals.find(GV);
1146 if (It != TrackedGlobals.end()) {
1147 mergeInValue(IV, &I, It->second);
1148 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001149 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001150 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001151 }
1152
Chris Lattner5638dc62009-11-02 06:06:14 +00001153 // Transform load from a constant into a constant if possible.
1154 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1155 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001156
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001157 // Otherwise we cannot say for certain what value this load will produce.
1158 // Bail out.
1159 markOverdefined(IV, &I);
1160}
Chris Lattner58b7b082004-04-13 19:43:54 +00001161
Chris Lattner59acc7d2004-12-10 08:02:06 +00001162void SCCPSolver::visitCallSite(CallSite CS) {
1163 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001164 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001165
1166 // The common case is that we aren't tracking the callee, either because we
1167 // are not doing interprocedural analysis or the callee is indirect, or is
1168 // external. Handle these cases first.
Chris Lattner14532d02009-11-03 03:42:51 +00001169 if (F == 0 || F->isDeclaration()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001170CallOverdefined:
1171 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001172 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001173
1174 // Otherwise, if we have a single return value case, and if the function is
1175 // a declaration, maybe we can constant fold it.
Chris Lattner14532d02009-11-03 03:42:51 +00001176 if (F && F->isDeclaration() && !isa<StructType>(I->getType()) &&
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001177 canConstantFoldCallTo(F)) {
1178
1179 SmallVector<Constant*, 8> Operands;
1180 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1181 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001182 LatticeVal State = getValueState(*AI);
Chris Lattner38871e42009-11-02 03:03:42 +00001183
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001184 if (State.isUndefined())
1185 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001186 if (State.isOverdefined())
1187 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001188 assert(State.isConstant() && "Unknown state!");
1189 Operands.push_back(State.getConstant());
1190 }
1191
1192 // If we can constant fold this, mark the result of the call as a
1193 // constant.
Chris Lattner38871e42009-11-02 03:03:42 +00001194 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1195 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001196 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001197
1198 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +00001199 return markOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001200 }
1201
Chris Lattner2396cc32009-11-03 19:24:51 +00001202 // If this is a local function that doesn't have its address taken, mark its
1203 // entry block executable and merge in the actual arguments to the call into
1204 // the formal arguments of the function.
1205 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1206 MarkBlockExecutable(F->begin());
1207
1208 // Propagate information from this call site into the callee.
1209 CallSite::arg_iterator CAI = CS.arg_begin();
1210 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1211 AI != E; ++AI, ++CAI) {
1212 // If this argument is byval, and if the function is not readonly, there
1213 // will be an implicit copy formed of the input aggregate.
1214 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1215 markOverdefined(AI);
1216 continue;
1217 }
1218
1219 mergeInValue(AI, getValueState(*CAI));
1220 }
1221 }
1222
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001223 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001224 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1225 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001226 // If so, propagate the return value of the callee into this call result.
1227 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001228 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001229 // Check to see if we're tracking this callee, if not, handle it in the
1230 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001231 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1232 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001233 if (TMRVI == TrackedMultipleRetVals.end())
1234 goto CallOverdefined;
Torok Edwin2b6183d2009-10-20 15:15:09 +00001235
1236 // Need to mark as overdefined, otherwise it stays undefined which
1237 // creates extractvalue undef, <idx>
1238 markOverdefined(I);
Chris Lattner38871e42009-11-02 03:03:42 +00001239
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001240 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001241 // into this call site. We do this by walking all the uses. Single-index
1242 // ExtractValueInst uses can be tracked; anything more complicated is
1243 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001244 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1245 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001246 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1247 if (EVI->getNumIndices() == 1) {
1248 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001249 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001250 continue;
1251 }
1252 }
1253 // The aggregate value is used in a way not handled here. Assume nothing.
1254 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001255 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001256 } else {
1257 // Otherwise we're not tracking this callee, so handle it in the
1258 // common path above.
1259 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001260 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001261}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001262
Chris Lattner82bec2c2004-11-15 04:44:20 +00001263void SCCPSolver::Solve() {
1264 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001265 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001266 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001267 // Process the overdefined instruction's work list first, which drives other
1268 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001269 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001270 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001271
Dan Gohman87325772009-08-17 15:25:05 +00001272 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001273
Chris Lattner82bec2c2004-11-15 04:44:20 +00001274 // "I" got into the work list because it either made the transition from
1275 // bottom to constant
1276 //
1277 // Anything on this worklist that is overdefined need not be visited
1278 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001279 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001280 //
1281 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1282 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001283 if (Instruction *I = dyn_cast<Instruction>(*UI))
1284 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001285 }
Chris Lattner2f096252009-11-02 02:33:50 +00001286
1287 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001288 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001289 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001290
Dan Gohman87325772009-08-17 15:25:05 +00001291 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001292
Chris Lattner2a0433b2009-11-02 05:55:40 +00001293 // "I" got into the work list because it made the transition from undef to
1294 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001295 //
1296 // Anything on this worklist that is overdefined need not be visited
1297 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001298 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001299 //
1300 if (!getValueState(I).isOverdefined())
1301 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1302 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001303 if (Instruction *I = dyn_cast<Instruction>(*UI))
1304 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001305 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001306
Chris Lattner2f096252009-11-02 02:33:50 +00001307 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001308 while (!BBWorkList.empty()) {
1309 BasicBlock *BB = BBWorkList.back();
1310 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001311
Dan Gohman87325772009-08-17 15:25:05 +00001312 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001313
Chris Lattner82bec2c2004-11-15 04:44:20 +00001314 // Notify all instructions in this basic block that they are newly
1315 // executable.
1316 visit(BB);
1317 }
1318 }
1319}
1320
Chris Lattner3bad2532006-12-20 06:21:33 +00001321/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001322/// that branches on undef values cannot reach any of their successors.
1323/// However, this is not a safe assumption. After we solve dataflow, this
1324/// method should be use to handle this. If this returns true, the solver
1325/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001326///
1327/// This method handles this by finding an unresolved branch and marking it one
1328/// of the edges from the block as being feasible, even though the condition
1329/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1330/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001331/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001332/// constraints on the condition of the branch, as that would impact other users
1333/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001334///
1335/// This scan also checks for values that use undefs, whose results are actually
1336/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1337/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1338/// even if X isn't defined.
1339bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001340 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1341 if (!BBExecutable.count(BB))
1342 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001343
1344 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1345 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001346 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001347
1348 LatticeVal &LV = getValueState(I);
1349 if (!LV.isUndefined()) continue;
1350
1351 // Get the lattice values of the first two operands for use below.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001352 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001353 LatticeVal Op1LV;
1354 if (I->getNumOperands() == 2) {
1355 // If this is a two-operand instruction, and if both operands are
1356 // undefs, the result stays undef.
1357 Op1LV = getValueState(I->getOperand(1));
1358 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1359 continue;
1360 }
1361
1362 // If this is an instructions whose result is defined even if the input is
1363 // not fully defined, propagate the information.
1364 const Type *ITy = I->getType();
1365 switch (I->getOpcode()) {
1366 default: break; // Leave the instruction as an undef.
1367 case Instruction::ZExt:
1368 // After a zero extend, we know the top part is zero. SExt doesn't have
1369 // to be handled here, because we don't know whether the top part is 1's
1370 // or 0's.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001371 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001372 return true;
1373 case Instruction::Mul:
1374 case Instruction::And:
1375 // undef * X -> 0. X could be zero.
1376 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001377 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001378 return true;
1379
1380 case Instruction::Or:
1381 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001382 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001383 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001384
1385 case Instruction::SDiv:
1386 case Instruction::UDiv:
1387 case Instruction::SRem:
1388 case Instruction::URem:
1389 // X / undef -> undef. No change.
1390 // X % undef -> undef. No change.
1391 if (Op1LV.isUndefined()) break;
1392
1393 // undef / X -> 0. X could be maxint.
1394 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001395 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001396 return true;
1397
1398 case Instruction::AShr:
1399 // undef >>s X -> undef. No change.
1400 if (Op0LV.isUndefined()) break;
1401
1402 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1403 if (Op0LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001404 markForcedConstant(I, Op0LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001405 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001406 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001407 return true;
1408 case Instruction::LShr:
1409 case Instruction::Shl:
1410 // undef >> X -> undef. No change.
1411 // undef << X -> undef. No change.
1412 if (Op0LV.isUndefined()) break;
1413
1414 // X >> undef -> 0. X could be 0.
1415 // X << undef -> 0. X could be 0.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001416 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001417 return true;
1418 case Instruction::Select:
1419 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1420 if (Op0LV.isUndefined()) {
1421 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1422 Op1LV = getValueState(I->getOperand(2));
1423 } else if (Op1LV.isUndefined()) {
1424 // c ? undef : undef -> undef. No change.
1425 Op1LV = getValueState(I->getOperand(2));
1426 if (Op1LV.isUndefined())
1427 break;
1428 // Otherwise, c ? undef : x -> x.
1429 } else {
1430 // Leave Op1LV as Operand(1)'s LatticeValue.
1431 }
1432
1433 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001434 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001435 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001436 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001437 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001438 case Instruction::Call:
1439 // If a call has an undef result, it is because it is constant foldable
1440 // but one of the inputs was undef. Just force the result to
1441 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001442 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001443 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001444 }
1445 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001446
1447 TerminatorInst *TI = BB->getTerminator();
1448 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1449 if (!BI->isConditional()) continue;
1450 if (!getValueState(BI->getCondition()).isUndefined())
1451 continue;
1452 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001453 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001454 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001455 if (!getValueState(SI->getCondition()).isUndefined())
1456 continue;
1457 } else {
1458 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001459 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001460
Chris Lattner05bb7892008-01-28 00:32:30 +00001461 // If the edge to the second successor isn't thought to be feasible yet,
1462 // mark it so now. We pick the second one so that this goes to some
1463 // enumerated value in a switch instead of going to the default destination.
1464 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001465 continue;
1466
1467 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1468 // and return. This will make other blocks reachable, which will allow new
1469 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001470 markEdgeExecutable(BB, TI->getSuccessor(1));
1471
1472 // This must be a conditional branch of switch on undef. At this point,
1473 // force the old terminator to branch to the first successor. This is
1474 // required because we are now influencing the dataflow of the function with
1475 // the assumption that this edge is taken. If we leave the branch condition
1476 // as undef, then further analysis could think the undef went another way
1477 // leading to an inconsistent set of conclusions.
1478 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001479 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner05bb7892008-01-28 00:32:30 +00001480 } else {
1481 SwitchInst *SI = cast<SwitchInst>(TI);
1482 SI->setCondition(SI->getCaseValue(1));
1483 }
1484
Chris Lattnerd2d86702006-10-22 05:59:17 +00001485 return true;
1486 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001487
Chris Lattnerd2d86702006-10-22 05:59:17 +00001488 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001489}
1490
Chris Lattner82bec2c2004-11-15 04:44:20 +00001491
1492namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001493 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001494 //
Chris Lattner14051812004-11-15 07:15:04 +00001495 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001496 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001497 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001498 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001499 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001500 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001501
Chris Lattner14051812004-11-15 07:15:04 +00001502 // runOnFunction - Run the Sparse Conditional Constant Propagation
1503 // algorithm, and return true if the function was modified.
1504 //
1505 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001506
Chris Lattner14051812004-11-15 07:15:04 +00001507 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1508 AU.setPreservesCFG();
1509 }
1510 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001511} // end anonymous namespace
1512
Dan Gohman844731a2008-05-13 00:00:25 +00001513char SCCP::ID = 0;
1514static RegisterPass<SCCP>
1515X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001516
Chris Lattner2f096252009-11-02 02:33:50 +00001517// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001518FunctionPass *llvm::createSCCPPass() {
1519 return new SCCP();
1520}
1521
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001522static void DeleteInstructionInBlock(BasicBlock *BB) {
1523 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1524 ++NumDeadBlocks;
1525
1526 // Delete the instructions backwards, as it has a reduced likelihood of
1527 // having to update as many def-use and use-def chains.
1528 while (!isa<TerminatorInst>(BB->begin())) {
1529 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1530
1531 if (!I->use_empty())
1532 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1533 BB->getInstList().erase(I);
1534 ++NumInstRemoved;
1535 }
1536}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001537
Chris Lattner82bec2c2004-11-15 04:44:20 +00001538// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1539// and return true if the function was modified.
1540//
1541bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001542 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner5638dc62009-11-02 06:06:14 +00001543 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001544
1545 // Mark the first block of the function as being executable.
1546 Solver.MarkBlockExecutable(F.begin());
1547
Chris Lattner7e529e42004-11-15 05:45:33 +00001548 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001549 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001550 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001551
Chris Lattner82bec2c2004-11-15 04:44:20 +00001552 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001553 bool ResolvedUndefs = true;
1554 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001555 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001556 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001557 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001558 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001559
Chris Lattner7e529e42004-11-15 05:45:33 +00001560 bool MadeChanges = false;
1561
1562 // If we decided that there are basic blocks that are dead in this function,
1563 // delete their contents now. Note that we cannot actually delete the blocks,
1564 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001565
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001566 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001567 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001568 DeleteInstructionInBlock(BB);
1569 MadeChanges = true;
1570 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001571 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001572
1573 // Iterate over all of the instructions in a function, replacing them with
1574 // constants if we have found them to be of constant values.
1575 //
1576 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1577 Instruction *Inst = BI++;
1578 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1579 continue;
1580
Chris Lattner8db50122009-11-02 02:54:24 +00001581 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1582 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001583 continue;
1584
1585 Constant *Const = IV.isConstant()
1586 ? IV.getConstant() : UndefValue::get(Inst->getType());
1587 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1588
1589 // Replaces all of the uses of a variable with uses of the constant.
1590 Inst->replaceAllUsesWith(Const);
1591
1592 // Delete the instruction.
1593 Inst->eraseFromParent();
1594
1595 // Hey, we just changed something!
1596 MadeChanges = true;
1597 ++NumInstRemoved;
1598 }
1599 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001600
1601 return MadeChanges;
1602}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001603
1604namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001605 //===--------------------------------------------------------------------===//
1606 //
1607 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1608 /// Constant Propagation.
1609 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001610 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001611 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001612 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001613 bool runOnModule(Module &M);
1614 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001615} // end anonymous namespace
1616
Dan Gohman844731a2008-05-13 00:00:25 +00001617char IPSCCP::ID = 0;
1618static RegisterPass<IPSCCP>
1619Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1620
Chris Lattner2f096252009-11-02 02:33:50 +00001621// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001622ModulePass *llvm::createIPSCCPPass() {
1623 return new IPSCCP();
1624}
1625
1626
1627static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001628 // Delete any dead constantexpr klingons.
1629 GV->removeDeadConstantUsers();
1630
Chris Lattner59acc7d2004-12-10 08:02:06 +00001631 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1632 UI != E; ++UI)
1633 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001634 if (SI->getOperand(0) == GV || SI->isVolatile())
1635 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001636 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1637 // Make sure we are calling the function, not passing the address.
Chris Lattnerb2710042009-11-01 06:11:53 +00001638 if (UI.getOperandNo() != 0)
Nick Lewyckyaf386132008-11-03 03:49:14 +00001639 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001640 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1641 if (LI->isVolatile())
1642 return true;
Chris Lattnerb2710042009-11-01 06:11:53 +00001643 } else if (isa<BlockAddress>(*UI)) {
1644 // blockaddress doesn't take the address of the function, it takes addr
1645 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001646 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001647 return true;
1648 }
1649 return false;
1650}
1651
1652bool IPSCCP::runOnModule(Module &M) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001653 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner59acc7d2004-12-10 08:02:06 +00001654
1655 // Loop over all functions, marking arguments to those with their addresses
1656 // taken or that are external as overdefined.
1657 //
Chris Lattnerff3ca152009-11-02 06:34:04 +00001658 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1659 if (F->isDeclaration())
1660 continue;
1661
Chris Lattner14532d02009-11-03 03:42:51 +00001662 // If this is a strong or ODR definition of this function, then we can
1663 // propagate information about its result into callsites of it.
1664 if (!F->mayBeOverridden() &&
1665 !isa<StructType>(F->getReturnType()))
Chris Lattner59acc7d2004-12-10 08:02:06 +00001666 Solver.AddTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001667
1668 // If this function only has direct calls that we can see, we can track its
1669 // arguments and return value aggressively, and can assume it is not called
1670 // unless we see evidence to the contrary.
Chris Lattner2396cc32009-11-03 19:24:51 +00001671 if (F->hasLocalLinkage() && !AddressIsTaken(F)) {
1672 Solver.AddArgumentTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001673 continue;
Chris Lattner2396cc32009-11-03 19:24:51 +00001674 }
Chris Lattner14532d02009-11-03 03:42:51 +00001675
1676 // Assume the function is called.
1677 Solver.MarkBlockExecutable(F->begin());
1678
1679 // Assume nothing about the incoming arguments.
1680 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1681 AI != E; ++AI)
1682 Solver.markOverdefined(AI);
Chris Lattnerff3ca152009-11-02 06:34:04 +00001683 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001684
Chris Lattnerdd336d12004-12-11 05:15:59 +00001685 // Loop over global variables. We inform the solver about any internal global
1686 // variables that do not have their 'addresses taken'. If they don't have
1687 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001688 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1689 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001690 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001691 Solver.TrackValueOfGlobalVariable(G);
1692
Chris Lattner59acc7d2004-12-10 08:02:06 +00001693 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001694 bool ResolvedUndefs = true;
1695 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001696 Solver.Solve();
1697
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001698 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001699 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001700 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001701 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001702 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001703
1704 bool MadeChanges = false;
1705
1706 // Iterate over all of the instructions in the module, replacing them with
1707 // constants if we have found them to be of constant values.
1708 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001709 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001710
Chris Lattner59acc7d2004-12-10 08:02:06 +00001711 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001712 if (Solver.isBlockExecutable(F->begin())) {
1713 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1714 AI != E; ++AI) {
1715 if (AI->use_empty()) continue;
1716
1717 LatticeVal IV = Solver.getLatticeValueFor(AI);
1718 if (IV.isOverdefined()) continue;
1719
1720 Constant *CST = IV.isConstant() ?
1721 IV.getConstant() : UndefValue::get(AI->getType());
1722 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1723
1724 // Replaces all of the uses of a variable with uses of the
1725 // constant.
1726 AI->replaceAllUsesWith(CST);
1727 ++IPNumArgsElimed;
1728 }
Chris Lattner8db50122009-11-02 02:54:24 +00001729 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001730
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001731 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001732 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001733 DeleteInstructionInBlock(BB);
1734 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001735
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001736 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001737 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1738 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001739 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001740 TI->getSuccessor(i)->removePredecessor(BB);
1741 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001742 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001743 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001744 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001745
Chris Lattner864737b2004-12-11 05:32:19 +00001746 if (&*BB != &F->front())
1747 BlocksToErase.push_back(BB);
1748 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001749 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001750 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001751 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001752
1753 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1754 Instruction *Inst = BI++;
1755 if (Inst->getType()->isVoidTy())
1756 continue;
1757
Chris Lattner8db50122009-11-02 02:54:24 +00001758 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1759 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001760 continue;
1761
1762 Constant *Const = IV.isConstant()
1763 ? IV.getConstant() : UndefValue::get(Inst->getType());
1764 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1765
1766 // Replaces all of the uses of a variable with uses of the
1767 // constant.
1768 Inst->replaceAllUsesWith(Const);
1769
1770 // Delete the instruction.
1771 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1772 Inst->eraseFromParent();
1773
1774 // Hey, we just changed something!
1775 MadeChanges = true;
1776 ++IPNumInstRemoved;
1777 }
1778 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001779
1780 // Now that all instructions in the function are constant folded, erase dead
1781 // blocks, because we can now use ConstantFoldTerminator to get rid of
1782 // in-edges.
1783 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1784 // If there are any PHI nodes in this successor, drop entries for BB now.
1785 BasicBlock *DeadBB = BlocksToErase[i];
1786 while (!DeadBB->use_empty()) {
1787 Instruction *I = cast<Instruction>(DeadBB->use_back());
1788 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001789 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001790 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001791 // if this is a branch or switch on undef. Fold it manually as a
1792 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001793#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001794 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1795 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1796 "Branch should be foldable!");
1797 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1798 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1799 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001800 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001801 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001802#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001803
1804 // Make this an uncond branch to the first successor.
1805 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001806 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001807
1808 // Remove entries in successor phi nodes to remove edges.
1809 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1810 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1811
1812 // Remove the old terminator.
1813 TI->eraseFromParent();
1814 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001815 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001816
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001817 // Finally, delete the basic block.
1818 F->getBasicBlockList().erase(DeadBB);
1819 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001820 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001821 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001822
1823 // If we inferred constant or undef return values for a function, we replaced
1824 // all call uses with the inferred value. This means we don't need to bother
1825 // actually returning anything from the function. Replace all return
1826 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001827 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001828 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001829 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner14532d02009-11-03 03:42:51 +00001830 E = RV.end(); I != E; ++I) {
1831 Function *F = I->first;
1832 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1833 continue;
1834
1835 // We can only do this if we know that nothing else can call the function.
1836 if (!F->hasLocalLinkage() || AddressIsTaken(F))
1837 continue;
1838
1839 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1840 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1841 if (!isa<UndefValue>(RI->getOperand(0)))
1842 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1843 }
1844
Chris Lattnerdd336d12004-12-11 05:15:59 +00001845 // If we infered constant or undef values for globals variables, we can delete
1846 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001847 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1848 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001849 E = TG.end(); I != E; ++I) {
1850 GlobalVariable *GV = I->first;
1851 assert(!I->second.isOverdefined() &&
1852 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001853 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001854 while (!GV->use_empty()) {
1855 StoreInst *SI = cast<StoreInst>(GV->use_back());
1856 SI->eraseFromParent();
1857 }
1858 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001859 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001860 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001861
Chris Lattner59acc7d2004-12-10 08:02:06 +00001862 return MadeChanges;
1863}