blob: 15b5bb5bc41f76d168746c4cb88ef6bfc9a7a4ba [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 Lattner2396cc32009-11-03 19:24:51 +0000177 /// TrackingIncomingArguments - This is the set of functions that are
178 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
179
Chris Lattner38871e42009-11-02 03:03:42 +0000180 /// The reason for two worklists is that overdefined is the lowest state
181 /// on the lattice, and moving things to overdefined as fast as possible
182 /// makes SCCP converge much faster.
183 ///
184 /// By having a separate worklist, we accomplish this because everything
185 /// possibly overdefined will become overdefined at the soonest possible
186 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000187 SmallVector<Value*, 64> OverdefinedInstWorkList;
188 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000189
190
Chris Lattnercf712de2008-08-23 23:36:38 +0000191 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000192
Chris Lattner1daee8b2004-01-12 03:57:30 +0000193 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
194 /// overdefined, despite the fact that the PHI node is overdefined.
195 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
196
Chris Lattner16b18fd2003-10-08 16:55:34 +0000197 /// KnownFeasibleEdges - Entries in this set are edges which have already had
198 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000199 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
200 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000201public:
Chris Lattner5638dc62009-11-02 06:06:14 +0000202 SCCPSolver(const TargetData *td) : TD(td) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000203
Chris Lattner82bec2c2004-11-15 04:44:20 +0000204 /// MarkBlockExecutable - This method can be used by clients to mark all of
205 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner09275292009-11-02 06:11:23 +0000206 ///
207 /// This returns true if the block was not considered live before.
208 bool MarkBlockExecutable(BasicBlock *BB) {
209 if (!BBExecutable.insert(BB)) return false;
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000210 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000211 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner09275292009-11-02 06:11:23 +0000212 return true;
Chris Lattner0dbfc052002-04-29 21:26:08 +0000213 }
214
Chris Lattnerdd336d12004-12-11 05:15:59 +0000215 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000216 /// inform the SCCPSolver that it should track loads and stores to the
217 /// specified global variable if it can. This is only legal to call if
218 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000219 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
220 const Type *ElTy = GV->getType()->getElementType();
221 if (ElTy->isFirstClassType()) {
222 LatticeVal &IV = TrackedGlobals[GV];
223 if (!isa<UndefValue>(GV->getInitializer()))
224 IV.markConstant(GV->getInitializer());
225 }
226 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000227
228 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
229 /// and out of the specified function (which cannot have its address taken),
230 /// this method must be called.
231 void AddTrackedFunction(Function *F) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000232 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000233 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
234 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000235 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
236 LatticeVal()));
237 } else
238 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000239 }
240
Chris Lattner2396cc32009-11-03 19:24:51 +0000241 void AddArgumentTrackedFunction(Function *F) {
242 TrackingIncomingArguments.insert(F);
243 }
244
Chris Lattner82bec2c2004-11-15 04:44:20 +0000245 /// Solve - Solve for constants and executable blocks.
246 ///
247 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000248
Chris Lattner3bad2532006-12-20 06:21:33 +0000249 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000250 /// that branches on undef values cannot reach any of their successors.
251 /// However, this is not a safe assumption. After we solve dataflow, this
252 /// method should be use to handle this. If this returns true, the solver
253 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000254 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000255
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000256 bool isBlockExecutable(BasicBlock *BB) const {
257 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000258 }
259
Chris Lattner8db50122009-11-02 02:54:24 +0000260 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000261 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000262 assert(I != ValueState.end() && "V is not in valuemap!");
263 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000264 }
265
Devang Patel7c490d42008-03-11 05:46:42 +0000266 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000267 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000268 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
269 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000270 }
271
Chris Lattnerdd336d12004-12-11 05:15:59 +0000272 /// getTrackedGlobals - Get and return the set of inferred initializers for
273 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000274 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000275 return TrackedGlobals;
276 }
277
Chris Lattner36c99522009-11-02 03:21:36 +0000278 void markOverdefined(Value *V) {
Chris Lattner57939df2007-03-04 04:50:21 +0000279 markOverdefined(ValueState[V], V);
280 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000281
Chris Lattner138a1242001-06-27 23:38:11 +0000282private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000283 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000284 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000285 // the users of the instruction are updated later.
286 //
Chris Lattner38871e42009-11-02 03:03:42 +0000287 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
288 if (!IV.markConstant(C)) return;
289 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
290 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000291 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000292
Chris Lattner38871e42009-11-02 03:03:42 +0000293 void markConstant(Value *V, Constant *C) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000294 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000295 }
296
Chris Lattner2a0433b2009-11-02 05:55:40 +0000297 void markForcedConstant(Value *V, Constant *C) {
298 ValueState[V].markForcedConstant(C);
299 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
300 InstWorkList.push_back(V);
301 }
302
303
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000304 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000305 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000306 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000307 void markOverdefined(LatticeVal &IV, Value *V) {
308 if (!IV.markOverdefined()) return;
309
310 DEBUG(errs() << "markOverdefined: ";
311 if (Function *F = dyn_cast<Function>(V))
312 errs() << "Function '" << F->getName() << "'\n";
313 else
314 errs() << *V << '\n');
315 // Only instructions go on the work list
316 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000317 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000318
Chris Lattner2a0433b2009-11-02 05:55:40 +0000319 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000320 if (IV.isOverdefined() || MergeWithV.isUndefined())
321 return; // Noop.
322 if (MergeWithV.isOverdefined())
323 markOverdefined(IV, V);
324 else if (IV.isUndefined())
325 markConstant(IV, V, MergeWithV.getConstant());
326 else if (IV.getConstant() != MergeWithV.getConstant())
327 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000328 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000329
Chris Lattner2a0433b2009-11-02 05:55:40 +0000330 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattner36c99522009-11-02 03:21:36 +0000331 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000332 }
333
Chris Lattner138a1242001-06-27 23:38:11 +0000334
Chris Lattner2a0433b2009-11-02 05:55:40 +0000335 /// getValueState - Return the LatticeVal object that corresponds to the
336 /// value. This function handles the case when the value hasn't been seen yet
337 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000338 LatticeVal &getValueState(Value *V) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000339 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000340 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000341
Chris Lattner36c99522009-11-02 03:21:36 +0000342 LatticeVal &LV = ValueState[V];
343
Chris Lattner3bad2532006-12-20 06:21:33 +0000344 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000345 // Undef values remain undefined.
346 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000347 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000348 }
Chris Lattner36c99522009-11-02 03:21:36 +0000349
Chris Lattner2f096252009-11-02 02:33:50 +0000350 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000351 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000352 }
353
Chris Lattner2a0433b2009-11-02 05:55:40 +0000354 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
355 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000356 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
357 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
358 return; // This edge is already known to be executable!
359
Chris Lattner09275292009-11-02 06:11:23 +0000360 if (!MarkBlockExecutable(Dest)) {
361 // If the destination is already executable, we just made an *edge*
362 // feasible that wasn't before. Revisit the PHI nodes in the block
363 // because they have potentially new operands.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000364 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
365 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000366
Chris Lattner09275292009-11-02 06:11:23 +0000367 PHINode *PN;
368 for (BasicBlock::iterator I = Dest->begin();
369 (PN = dyn_cast<PHINode>(I)); ++I)
370 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000371 }
Chris Lattner138a1242001-06-27 23:38:11 +0000372 }
373
Chris Lattner82bec2c2004-11-15 04:44:20 +0000374 // getFeasibleSuccessors - Return a vector of booleans to indicate which
375 // successors are reachable from a given terminator instruction.
376 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000377 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000378
379 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000380 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000381 //
382 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
383
384 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000385 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000386 // information, we need to update the specified user of this instruction.
387 //
Chris Lattner14532d02009-11-03 03:42:51 +0000388 void OperandChangedState(Instruction *I) {
389 if (BBExecutable.count(I->getParent())) // Inst is executable?
390 visit(*I);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000391 }
Chris Lattnere01985c2009-11-02 06:28:16 +0000392
393 /// RemoveFromOverdefinedPHIs - If I has any entries in the
394 /// UsersOfOverdefinedPHIs map for PN, remove them now.
395 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
396 if (UsersOfOverdefinedPHIs.empty()) return;
397 std::multimap<PHINode*, Instruction*>::iterator It, E;
398 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
399 while (It != E) {
400 if (It->second == I)
401 UsersOfOverdefinedPHIs.erase(It++);
402 else
403 ++It;
404 }
405 }
Chris Lattner82bec2c2004-11-15 04:44:20 +0000406
407private:
408 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000409
Chris Lattner2f096252009-11-02 02:33:50 +0000410 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000411 // operand made a transition, or the instruction is newly executable. Change
412 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000413 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000414
415 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000416 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000417 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000418
Chris Lattnerb8047602002-08-14 17:53:45 +0000419 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000420 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000421 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000422 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000423 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000424 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000425 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000426 void visitExtractValueInst(ExtractValueInst &EVI);
427 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000428
Chris Lattner2f096252009-11-02 02:33:50 +0000429 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000430 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000431 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000432 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000433 void visitCallInst (CallInst &I) {
Chris Lattner32c0d222009-09-27 21:35:11 +0000434 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000435 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000436 void visitInvokeInst (InvokeInst &II) {
437 visitCallSite(CallSite::get(&II));
438 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000439 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000440 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000441 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000442 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000443 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000444 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
445 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000446
Chris Lattner7e708292002-06-25 16:13:24 +0000447 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000448 // If a new instruction is added to LLVM that we don't handle.
Chris Lattnerbdff5482009-08-23 04:37:46 +0000449 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000450 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000451 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000452};
Chris Lattnerf6293092002-07-23 18:06:35 +0000453
Duncan Sandse2abf122007-07-20 08:56:21 +0000454} // end anonymous namespace
455
456
Chris Lattnerb9a66342002-05-02 21:44:00 +0000457// getFeasibleSuccessors - Return a vector of booleans to indicate which
458// successors are reachable from a given terminator instruction.
459//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000460void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000461 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000462 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000463 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000464 if (BI->isUnconditional()) {
465 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000466 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000467 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000468
Chris Lattner2a0433b2009-11-02 05:55:40 +0000469 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000470 ConstantInt *CI = BCValue.getConstantInt();
471 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000472 // Overdefined condition variables, and branches on unfoldable constant
473 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000474 if (!BCValue.isUndefined())
475 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000476 return;
477 }
478
479 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000480 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000481 return;
482 }
483
Chris Lattner36c99522009-11-02 03:21:36 +0000484 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000485 // Invoke instructions successors are always executable.
486 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000487 return;
488 }
489
490 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000491 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000492 ConstantInt *CI = SCValue.getConstantInt();
493
494 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000495 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000496 if (!SCValue.isUndefined())
497 Succs.assign(TI.getNumSuccessors(), true);
498 return;
499 }
500
501 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000502 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000503 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000504
505 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
506 if (isa<IndirectBrInst>(&TI)) {
507 // Just mark all destinations executable!
508 Succs.assign(TI.getNumSuccessors(), true);
509 return;
510 }
511
512#ifndef NDEBUG
513 errs() << "Unknown terminator instruction: " << TI << '\n';
514#endif
515 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000516}
517
518
Chris Lattner59f0ce22002-05-02 21:18:01 +0000519// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000520// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000521//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000522bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000523 assert(BBExecutable.count(To) && "Dest should always be alive!");
524
525 // Make sure the source basic block is executable!!
526 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000527
Chris Lattner2f096252009-11-02 02:33:50 +0000528 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000529 TerminatorInst *TI = From->getTerminator();
530 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
531 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000532 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000533
Chris Lattner2a0433b2009-11-02 05:55:40 +0000534 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000535
Chris Lattnerea0db072009-11-02 02:30:06 +0000536 // Overdefined condition variables mean the branch could go either way,
537 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000538 ConstantInt *CI = BCValue.getConstantInt();
539 if (CI == 0)
540 return !BCValue.isUndefined();
Chris Lattnerea0db072009-11-02 02:30:06 +0000541
Chris Lattnerea0db072009-11-02 02:30:06 +0000542 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000543 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000544 }
545
546 // Invoke instructions successors are always executable.
547 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000548 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000549
550 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000551 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000552 ConstantInt *CI = SCValue.getConstantInt();
553
554 if (CI == 0)
555 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000556
Chris Lattner36c99522009-11-02 03:21:36 +0000557 // Make sure to skip the "default value" which isn't a value
558 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
559 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
560 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000561
Chris Lattner36c99522009-11-02 03:21:36 +0000562 // If the constant value is not equal to any of the branches, we must
563 // execute default branch.
564 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000565 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000566
567 // Just mark all destinations executable!
568 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
569 if (isa<IndirectBrInst>(&TI))
570 return true;
571
572#ifndef NDEBUG
573 errs() << "Unknown terminator instruction: " << *TI << '\n';
574#endif
575 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000576}
Chris Lattner138a1242001-06-27 23:38:11 +0000577
Chris Lattner2f096252009-11-02 02:33:50 +0000578// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000579// operand made a transition, or the instruction is newly executable. Change
580// the value type of I to reflect these changes if appropriate. This method
581// makes sure to do the following actions:
582//
583// 1. If a phi node merges two constants in, and has conflicting value coming
584// from different branches, or if the PHI node merges in an overdefined
585// value, then the PHI node becomes overdefined.
586// 2. If a phi node merges only constants in, and they all agree on value, the
587// PHI node becomes a constant value equal to that.
588// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
589// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
590// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
591// 6. If a conditional branch has a value that is constant, make the selected
592// destination executable
593// 7. If a conditional branch has a value that is overdefined, make all
594// successors executable.
595//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000596void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000597 if (getValueState(&PN).isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000598 // There may be instructions using this PHI node that are not overdefined
599 // themselves. If so, make sure that they know that the PHI node operand
600 // changed.
601 std::multimap<PHINode*, Instruction*>::iterator I, E;
602 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000603 if (I == E)
604 return;
605
606 SmallVector<Instruction*, 16> Users;
607 for (; I != E; ++I)
608 Users.push_back(I->second);
609 while (!Users.empty())
610 visit(Users.pop_back_val());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000611 return; // Quick exit
612 }
Chris Lattner138a1242001-06-27 23:38:11 +0000613
Chris Lattnera2f652d2004-03-16 19:49:59 +0000614 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
615 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000616 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000617 return markOverdefined(&PN);
Chris Lattnera2f652d2004-03-16 19:49:59 +0000618
Chris Lattner2a632552002-04-18 15:13:15 +0000619 // Look at all of the executable operands of the PHI node. If any of them
620 // are overdefined, the PHI becomes overdefined as well. If they are all
621 // constant, and they agree with each other, the PHI becomes the identical
622 // constant. If they are constant and don't agree, the PHI is overdefined.
623 // If there are no executable operands, the PHI remains undefined.
624 //
Chris Lattner9de28282003-04-25 02:50:03 +0000625 Constant *OperandVal = 0;
626 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000627 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000628 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000629
Chris Lattner38871e42009-11-02 03:03:42 +0000630 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
631 continue;
632
633 if (IV.isOverdefined()) // PHI node becomes overdefined!
634 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000635
Chris Lattner38871e42009-11-02 03:03:42 +0000636 if (OperandVal == 0) { // Grab the first value.
637 OperandVal = IV.getConstant();
638 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000639 }
Chris Lattner38871e42009-11-02 03:03:42 +0000640
641 // There is already a reachable operand. If we conflict with it,
642 // then the PHI node becomes overdefined. If we agree with it, we
643 // can continue on.
644
645 // Check to see if there are two different constants merging, if so, the PHI
646 // node is overdefined.
647 if (IV.getConstant() != OperandVal)
648 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000649 }
650
Chris Lattner2a632552002-04-18 15:13:15 +0000651 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000652 // arguments that agree with each other(and OperandVal is the constant) or
653 // OperandVal is null because there are no defined incoming arguments. If
654 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000655 //
Chris Lattner9de28282003-04-25 02:50:03 +0000656 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000657 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000658}
659
Chris Lattner14532d02009-11-03 03:42:51 +0000660
661
662
Chris Lattner59acc7d2004-12-10 08:02:06 +0000663void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000664 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000665
Chris Lattner59acc7d2004-12-10 08:02:06 +0000666 Function *F = I.getParent()->getParent();
Chris Lattner14532d02009-11-03 03:42:51 +0000667
Devang Patel7c490d42008-03-11 05:46:42 +0000668 // If we are tracking the return value of this function, merge it in.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000669 if (!TrackedRetVals.empty()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000670 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000671 TrackedRetVals.find(F);
Chris Lattner14532d02009-11-03 03:42:51 +0000672 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000673 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
Devang Patel7c490d42008-03-11 05:46:42 +0000674 return;
675 }
676 }
677
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000678 // Handle functions that return multiple values.
Chris Lattner574fa9e2009-11-02 06:17:06 +0000679 if (!TrackedMultipleRetVals.empty() &&
680 isa<StructType>(I.getOperand(0)->getType())) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000681 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
682 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000683 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000684 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
685 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000686 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000687 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000688 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000689 }
690}
691
Chris Lattner82bec2c2004-11-15 04:44:20 +0000692void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000693 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000694 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000695
Chris Lattner16b18fd2003-10-08 16:55:34 +0000696 BasicBlock *BB = TI.getParent();
697
Chris Lattner2f096252009-11-02 02:33:50 +0000698 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000699 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000700 if (SuccFeasible[i])
701 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000702}
703
Chris Lattner82bec2c2004-11-15 04:44:20 +0000704void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000705 LatticeVal OpSt = getValueState(I.getOperand(0));
706 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000707 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000708 else if (OpSt.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000709 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000710 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000711}
712
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000713void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000714 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000715
Dan Gohman60ea2682008-06-20 16:41:17 +0000716 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000717 if (isa<UndefValue>(Aggr))
718 return;
719
720 // Currently only handle single-index extractvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000721 if (EVI.getNumIndices() != 1)
722 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000723
724 Function *F = 0;
725 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
726 F = CI->getCalledFunction();
727 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
728 F = II->getCalledFunction();
729
730 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
731 // result back!
Chris Lattner38871e42009-11-02 03:03:42 +0000732 if (F == 0 || TrackedMultipleRetVals.empty())
733 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000734
Chris Lattnercf712de2008-08-23 23:36:38 +0000735 // See if we are tracking the result of the callee. If not tracking this
736 // function (for example, it is a declaration) just move to overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000737 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
738 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000739
740 // Otherwise, the value will be merged in here as a result of CallSite
741 // handling.
742}
743
744void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000745 Value *Aggr = IVI.getAggregateOperand();
746 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000747
Dan Gohman60ea2682008-06-20 16:41:17 +0000748 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000749 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000750 return;
751
752 // Currently only handle single-index insertvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000753 if (IVI.getNumIndices() != 1)
754 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000755
756 // Currently only handle insertvalue instructions that are in a single-use
757 // chain that builds up a return value.
758 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
Chris Lattner38871e42009-11-02 03:03:42 +0000759 if (!TmpIVI->hasOneUse())
760 return markOverdefined(&IVI);
761
Dan Gohmandfaceb42008-06-20 16:39:44 +0000762 const Value *V = *TmpIVI->use_begin();
763 if (isa<ReturnInst>(V))
764 break;
765 TmpIVI = dyn_cast<InsertValueInst>(V);
Chris Lattner38871e42009-11-02 03:03:42 +0000766 if (!TmpIVI)
767 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000768 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000769
770 // See if we are tracking the result of the callee.
771 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000772 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000773 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
774
775 // Merge in the inserted member value.
776 if (It != TrackedMultipleRetVals.end())
777 mergeInValue(It->second, F, getValueState(Val));
778
Dan Gohman60ea2682008-06-20 16:41:17 +0000779 // Mark the aggregate result of the IVI overdefined; any tracking that we do
780 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000781 markOverdefined(&IVI);
782}
783
Chris Lattner82bec2c2004-11-15 04:44:20 +0000784void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000785 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000786 if (CondValue.isUndefined())
787 return;
Chris Lattner36c99522009-11-02 03:21:36 +0000788
789 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000790 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
791 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000792 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000793 }
794
795 // Otherwise, the condition is overdefined or a constant we can't evaluate.
796 // See if we can produce something better than overdefined based on the T/F
797 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000798 LatticeVal TVal = getValueState(I.getTrueValue());
799 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000800
801 // select ?, C, C -> C.
802 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000803 TVal.getConstant() == FVal.getConstant())
804 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000805
Chris Lattner2a0433b2009-11-02 05:55:40 +0000806 if (TVal.isUndefined()) // select ?, undef, X -> X.
807 return mergeInValue(&I, FVal);
808 if (FVal.isUndefined()) // select ?, X, undef -> X.
809 return mergeInValue(&I, TVal);
810 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000811}
812
Chris Lattner2a0433b2009-11-02 05:55:40 +0000813// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000814void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000815 LatticeVal V1State = getValueState(I.getOperand(0));
816 LatticeVal V2State = getValueState(I.getOperand(1));
817
Chris Lattneref36dfd2004-11-15 05:03:30 +0000818 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000819 if (IV.isOverdefined()) return;
820
Chris Lattner2a0433b2009-11-02 05:55:40 +0000821 if (V1State.isConstant() && V2State.isConstant())
822 return markConstant(IV, &I,
823 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
824 V2State.getConstant()));
825
826 // If something is undef, wait for it to resolve.
827 if (!V1State.isOverdefined() && !V2State.isOverdefined())
828 return;
829
830 // Otherwise, one of our operands is overdefined. Try to produce something
831 // better than overdefined with some tricks.
832
833 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
834 // operand is overdefined.
835 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
836 LatticeVal *NonOverdefVal = 0;
837 if (!V1State.isOverdefined())
838 NonOverdefVal = &V1State;
839 else if (!V2State.isOverdefined())
840 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000841
Chris Lattner2a0433b2009-11-02 05:55:40 +0000842 if (NonOverdefVal) {
843 if (NonOverdefVal->isUndefined()) {
844 // Could annihilate value.
845 if (I.getOpcode() == Instruction::And)
846 markConstant(IV, &I, Constant::getNullValue(I.getType()));
847 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
848 markConstant(IV, &I, Constant::getAllOnesValue(PT));
849 else
850 markConstant(IV, &I,
851 Constant::getAllOnesValue(I.getType()));
852 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000853 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000854
855 if (I.getOpcode() == Instruction::And) {
856 // X and 0 = 0
857 if (NonOverdefVal->getConstant()->isNullValue())
858 return markConstant(IV, &I, NonOverdefVal->getConstant());
859 } else {
860 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
861 if (CI->isAllOnesValue()) // X or -1 = -1
862 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000863 }
864 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000865 }
Chris Lattnera177c672004-12-11 23:15:19 +0000866
867
Chris Lattner2a0433b2009-11-02 05:55:40 +0000868 // If both operands are PHI nodes, it is possible that this instruction has
869 // a constant value, despite the fact that the PHI node doesn't. Check for
870 // this condition now.
871 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
872 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
873 if (PN1->getParent() == PN2->getParent()) {
874 // Since the two PHI nodes are in the same basic block, they must have
875 // entries for the same predecessors. Walk the predecessor list, and
876 // if all of the incoming values are constants, and the result of
877 // evaluating this expression with all incoming value pairs is the
878 // same, then this expression is a constant even though the PHI node
879 // is not a constant!
880 LatticeVal Result;
881 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
882 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
883 BasicBlock *InBlock = PN1->getIncomingBlock(i);
884 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000885
Chris Lattner2a0433b2009-11-02 05:55:40 +0000886 if (In1.isOverdefined() || In2.isOverdefined()) {
887 Result.markOverdefined();
888 break; // Cannot fold this operation over the PHI nodes!
889 }
890
891 if (In1.isConstant() && In2.isConstant()) {
892 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
893 In2.getConstant());
894 if (Result.isUndefined())
895 Result.markConstant(V);
896 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000897 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000898 break;
Chris Lattner38871e42009-11-02 03:03:42 +0000899 }
Chris Lattner1daee8b2004-01-12 03:57:30 +0000900 }
901 }
902
Chris Lattner2a0433b2009-11-02 05:55:40 +0000903 // If we found a constant value here, then we know the instruction is
904 // constant despite the fact that the PHI nodes are overdefined.
905 if (Result.isConstant()) {
906 markConstant(IV, &I, Result.getConstant());
907 // Remember that this instruction is virtually using the PHI node
908 // operands.
909 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
910 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
911 return;
912 }
913
914 if (Result.isUndefined())
915 return;
916
917 // Okay, this really is overdefined now. Since we might have
918 // speculatively thought that this was not overdefined before, and
919 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
920 // make sure to clean out any entries that we put there, for
921 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +0000922 RemoveFromOverdefinedPHIs(&I, PN1);
923 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000924 }
925
926 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +0000927}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000928
Chris Lattner2f096252009-11-02 02:33:50 +0000929// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000930void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000931 LatticeVal V1State = getValueState(I.getOperand(0));
932 LatticeVal V2State = getValueState(I.getOperand(1));
933
Reid Spencere4d87aa2006-12-23 06:05:41 +0000934 LatticeVal &IV = ValueState[&I];
935 if (IV.isOverdefined()) return;
936
Chris Lattner2a0433b2009-11-02 05:55:40 +0000937 if (V1State.isConstant() && V2State.isConstant())
938 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
939 V1State.getConstant(),
940 V2State.getConstant()));
941
942 // If operands are still undefined, wait for it to resolve.
943 if (!V1State.isOverdefined() && !V2State.isOverdefined())
944 return;
945
946 // If something is overdefined, use some tricks to avoid ending up and over
947 // defined if we can.
948
949 // If both operands are PHI nodes, it is possible that this instruction has
950 // a constant value, despite the fact that the PHI node doesn't. Check for
951 // this condition now.
952 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
953 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
954 if (PN1->getParent() == PN2->getParent()) {
955 // Since the two PHI nodes are in the same basic block, they must have
956 // entries for the same predecessors. Walk the predecessor list, and
957 // if all of the incoming values are constants, and the result of
958 // evaluating this expression with all incoming value pairs is the
959 // same, then this expression is a constant even though the PHI node
960 // is not a constant!
961 LatticeVal Result;
962 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
963 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
964 BasicBlock *InBlock = PN1->getIncomingBlock(i);
965 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000966
Chris Lattner2a0433b2009-11-02 05:55:40 +0000967 if (In1.isOverdefined() || In2.isOverdefined()) {
968 Result.markOverdefined();
969 break; // Cannot fold this operation over the PHI nodes!
970 }
971
972 if (In1.isConstant() && In2.isConstant()) {
973 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
974 In1.getConstant(),
975 In2.getConstant());
976 if (Result.isUndefined())
977 Result.markConstant(V);
978 else if (Result.isConstant() && Result.getConstant() != V) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000979 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000980 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000981 }
982 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000983 }
984
Chris Lattner2a0433b2009-11-02 05:55:40 +0000985 // If we found a constant value here, then we know the instruction is
986 // constant despite the fact that the PHI nodes are overdefined.
987 if (Result.isConstant()) {
988 markConstant(&I, Result.getConstant());
989 // Remember that this instruction is virtually using the PHI node
990 // operands.
991 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
992 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
993 return;
994 }
995
996 if (Result.isUndefined())
997 return;
998
999 // Okay, this really is overdefined now. Since we might have
1000 // speculatively thought that this was not overdefined before, and
1001 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1002 // make sure to clean out any entries that we put there, for
1003 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +00001004 RemoveFromOverdefinedPHIs(&I, PN1);
1005 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001006 }
1007
1008 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001009}
1010
Robert Bocchino56107e22006-01-10 19:05:05 +00001011void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001012 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001013 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001014
1015#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001016 LatticeVal &ValState = getValueState(I.getOperand(0));
1017 LatticeVal &IdxState = getValueState(I.getOperand(1));
1018
1019 if (ValState.isOverdefined() || IdxState.isOverdefined())
1020 markOverdefined(&I);
1021 else if(ValState.isConstant() && IdxState.isConstant())
1022 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1023 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001024#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001025}
1026
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001027void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001028 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001029 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001030#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001031 LatticeVal &ValState = getValueState(I.getOperand(0));
1032 LatticeVal &EltState = getValueState(I.getOperand(1));
1033 LatticeVal &IdxState = getValueState(I.getOperand(2));
1034
1035 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1036 IdxState.isOverdefined())
1037 markOverdefined(&I);
1038 else if(ValState.isConstant() && EltState.isConstant() &&
1039 IdxState.isConstant())
1040 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1041 EltState.getConstant(),
1042 IdxState.getConstant()));
1043 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001044 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001045 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1046 EltState.getConstant(),
1047 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001048#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001049}
1050
Chris Lattner543abdf2006-04-08 01:19:12 +00001051void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001052 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001053 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001054#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001055 LatticeVal &V1State = getValueState(I.getOperand(0));
1056 LatticeVal &V2State = getValueState(I.getOperand(1));
1057 LatticeVal &MaskState = getValueState(I.getOperand(2));
1058
1059 if (MaskState.isUndefined() ||
1060 (V1State.isUndefined() && V2State.isUndefined()))
1061 return; // Undefined output if mask or both inputs undefined.
1062
1063 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1064 MaskState.isOverdefined()) {
1065 markOverdefined(&I);
1066 } else {
1067 // A mix of constant/undef inputs.
1068 Constant *V1 = V1State.isConstant() ?
1069 V1State.getConstant() : UndefValue::get(I.getType());
1070 Constant *V2 = V2State.isConstant() ?
1071 V2State.getConstant() : UndefValue::get(I.getType());
1072 Constant *Mask = MaskState.isConstant() ?
1073 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1074 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1075 }
Devang Patel67a821d2006-12-04 23:54:59 +00001076#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001077}
1078
Chris Lattner2f096252009-11-02 02:33:50 +00001079// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001080// can turn this into a getelementptr ConstantExpr.
1081//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001082void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner5cc66d92009-11-02 23:25:39 +00001083 if (ValueState[&I].isOverdefined()) return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001084
Chris Lattnere777ff22007-02-02 20:51:48 +00001085 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001086 Operands.reserve(I.getNumOperands());
1087
1088 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001089 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001090 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001091 return; // Operands are not resolved yet.
1092
Chris Lattner38871e42009-11-02 03:03:42 +00001093 if (State.isOverdefined())
Chris Lattner5cc66d92009-11-02 23:25:39 +00001094 return markOverdefined(&I);
Chris Lattner38871e42009-11-02 03:03:42 +00001095
Chris Lattner2a88bb72002-08-30 23:39:00 +00001096 assert(State.isConstant() && "Unknown state!");
1097 Operands.push_back(State.getConstant());
1098 }
1099
1100 Constant *Ptr = Operands[0];
Chris Lattner2a0433b2009-11-02 05:55:40 +00001101 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1102 Operands.size()-1));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001103}
Brian Gaeked0fde302003-11-11 22:41:34 +00001104
Chris Lattner2a0433b2009-11-02 05:55:40 +00001105void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001106 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1107 return;
Chris Lattner2a0433b2009-11-02 05:55:40 +00001108
Chris Lattnerdd336d12004-12-11 05:15:59 +00001109 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001110 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001111 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1112
Chris Lattner2a0433b2009-11-02 05:55:40 +00001113 // Get the value we are storing into the global, then merge it.
1114 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001115 if (I->second.isOverdefined())
1116 TrackedGlobals.erase(I); // No need to keep tracking this!
1117}
1118
1119
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001120// Handle load instructions. If the operand is a constant pointer to a constant
1121// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001122void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001123 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001124 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner2a0433b2009-11-02 05:55:40 +00001125
Chris Lattneref36dfd2004-11-15 05:03:30 +00001126 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001127 if (IV.isOverdefined()) return;
1128
Chris Lattner2a0433b2009-11-02 05:55:40 +00001129 if (!PtrVal.isConstant() || I.isVolatile())
1130 return markOverdefined(IV, &I);
1131
Chris Lattner5638dc62009-11-02 06:06:14 +00001132 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001133
Chris Lattner2a0433b2009-11-02 05:55:40 +00001134 // load null -> null
1135 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1136 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1137
1138 // Transform load (constant global) into the value loaded.
1139 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001140 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001141 // If we are tracking this global, merge in the known value for it.
1142 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1143 TrackedGlobals.find(GV);
1144 if (It != TrackedGlobals.end()) {
1145 mergeInValue(IV, &I, It->second);
1146 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001147 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001148 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001149 }
1150
Chris Lattner5638dc62009-11-02 06:06:14 +00001151 // Transform load from a constant into a constant if possible.
1152 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1153 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001154
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001155 // Otherwise we cannot say for certain what value this load will produce.
1156 // Bail out.
1157 markOverdefined(IV, &I);
1158}
Chris Lattner58b7b082004-04-13 19:43:54 +00001159
Chris Lattner59acc7d2004-12-10 08:02:06 +00001160void SCCPSolver::visitCallSite(CallSite CS) {
1161 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001162 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001163
1164 // The common case is that we aren't tracking the callee, either because we
1165 // are not doing interprocedural analysis or the callee is indirect, or is
1166 // external. Handle these cases first.
Chris Lattner14532d02009-11-03 03:42:51 +00001167 if (F == 0 || F->isDeclaration()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001168CallOverdefined:
1169 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001170 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001171
1172 // Otherwise, if we have a single return value case, and if the function is
1173 // a declaration, maybe we can constant fold it.
Chris Lattner14532d02009-11-03 03:42:51 +00001174 if (F && F->isDeclaration() && !isa<StructType>(I->getType()) &&
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001175 canConstantFoldCallTo(F)) {
1176
1177 SmallVector<Constant*, 8> Operands;
1178 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1179 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001180 LatticeVal State = getValueState(*AI);
Chris Lattner38871e42009-11-02 03:03:42 +00001181
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001182 if (State.isUndefined())
1183 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001184 if (State.isOverdefined())
1185 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001186 assert(State.isConstant() && "Unknown state!");
1187 Operands.push_back(State.getConstant());
1188 }
1189
1190 // If we can constant fold this, mark the result of the call as a
1191 // constant.
Chris Lattner38871e42009-11-02 03:03:42 +00001192 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1193 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001194 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001195
1196 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +00001197 return markOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001198 }
1199
Chris Lattner2396cc32009-11-03 19:24:51 +00001200 // If this is a local function that doesn't have its address taken, mark its
1201 // entry block executable and merge in the actual arguments to the call into
1202 // the formal arguments of the function.
1203 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1204 MarkBlockExecutable(F->begin());
1205
1206 // Propagate information from this call site into the callee.
1207 CallSite::arg_iterator CAI = CS.arg_begin();
1208 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1209 AI != E; ++AI, ++CAI) {
1210 // If this argument is byval, and if the function is not readonly, there
1211 // will be an implicit copy formed of the input aggregate.
1212 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1213 markOverdefined(AI);
1214 continue;
1215 }
1216
1217 mergeInValue(AI, getValueState(*CAI));
1218 }
1219 }
1220
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001221 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001222 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1223 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001224 // If so, propagate the return value of the callee into this call result.
1225 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001226 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001227 // Check to see if we're tracking this callee, if not, handle it in the
1228 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001229 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1230 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001231 if (TMRVI == TrackedMultipleRetVals.end())
1232 goto CallOverdefined;
Torok Edwin2b6183d2009-10-20 15:15:09 +00001233
1234 // Need to mark as overdefined, otherwise it stays undefined which
1235 // creates extractvalue undef, <idx>
1236 markOverdefined(I);
Chris Lattner38871e42009-11-02 03:03:42 +00001237
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001238 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001239 // into this call site. We do this by walking all the uses. Single-index
1240 // ExtractValueInst uses can be tracked; anything more complicated is
1241 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001242 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1243 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001244 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1245 if (EVI->getNumIndices() == 1) {
1246 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001247 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001248 continue;
1249 }
1250 }
1251 // The aggregate value is used in a way not handled here. Assume nothing.
1252 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001253 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001254 } else {
1255 // Otherwise we're not tracking this callee, so handle it in the
1256 // common path above.
1257 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001258 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001259}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001260
Chris Lattner82bec2c2004-11-15 04:44:20 +00001261void SCCPSolver::Solve() {
1262 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001263 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001264 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001265 // Process the overdefined instruction's work list first, which drives other
1266 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001267 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001268 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001269
Dan Gohman87325772009-08-17 15:25:05 +00001270 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001271
Chris Lattner82bec2c2004-11-15 04:44:20 +00001272 // "I" got into the work list because it either made the transition from
1273 // bottom to constant
1274 //
1275 // Anything on this worklist that is overdefined need not be visited
1276 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001277 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001278 //
1279 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1280 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001281 if (Instruction *I = dyn_cast<Instruction>(*UI))
1282 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001283 }
Chris Lattner2f096252009-11-02 02:33:50 +00001284
1285 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001286 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001287 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001288
Dan Gohman87325772009-08-17 15:25:05 +00001289 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001290
Chris Lattner2a0433b2009-11-02 05:55:40 +00001291 // "I" got into the work list because it made the transition from undef to
1292 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001293 //
1294 // Anything on this worklist that is overdefined need not be visited
1295 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001296 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001297 //
1298 if (!getValueState(I).isOverdefined())
1299 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1300 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001301 if (Instruction *I = dyn_cast<Instruction>(*UI))
1302 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001303 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001304
Chris Lattner2f096252009-11-02 02:33:50 +00001305 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001306 while (!BBWorkList.empty()) {
1307 BasicBlock *BB = BBWorkList.back();
1308 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001309
Dan Gohman87325772009-08-17 15:25:05 +00001310 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001311
Chris Lattner82bec2c2004-11-15 04:44:20 +00001312 // Notify all instructions in this basic block that they are newly
1313 // executable.
1314 visit(BB);
1315 }
1316 }
1317}
1318
Chris Lattner3bad2532006-12-20 06:21:33 +00001319/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001320/// that branches on undef values cannot reach any of their successors.
1321/// However, this is not a safe assumption. After we solve dataflow, this
1322/// method should be use to handle this. If this returns true, the solver
1323/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001324///
1325/// This method handles this by finding an unresolved branch and marking it one
1326/// of the edges from the block as being feasible, even though the condition
1327/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1328/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001329/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001330/// constraints on the condition of the branch, as that would impact other users
1331/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001332///
1333/// This scan also checks for values that use undefs, whose results are actually
1334/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1335/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1336/// even if X isn't defined.
1337bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001338 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1339 if (!BBExecutable.count(BB))
1340 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001341
1342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1343 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001344 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001345
1346 LatticeVal &LV = getValueState(I);
1347 if (!LV.isUndefined()) continue;
1348
1349 // Get the lattice values of the first two operands for use below.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001350 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001351 LatticeVal Op1LV;
1352 if (I->getNumOperands() == 2) {
1353 // If this is a two-operand instruction, and if both operands are
1354 // undefs, the result stays undef.
1355 Op1LV = getValueState(I->getOperand(1));
1356 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1357 continue;
1358 }
1359
1360 // If this is an instructions whose result is defined even if the input is
1361 // not fully defined, propagate the information.
1362 const Type *ITy = I->getType();
1363 switch (I->getOpcode()) {
1364 default: break; // Leave the instruction as an undef.
1365 case Instruction::ZExt:
1366 // After a zero extend, we know the top part is zero. SExt doesn't have
1367 // to be handled here, because we don't know whether the top part is 1's
1368 // or 0's.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001369 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001370 return true;
1371 case Instruction::Mul:
1372 case Instruction::And:
1373 // undef * X -> 0. X could be zero.
1374 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001375 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001376 return true;
1377
1378 case Instruction::Or:
1379 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001380 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001381 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001382
1383 case Instruction::SDiv:
1384 case Instruction::UDiv:
1385 case Instruction::SRem:
1386 case Instruction::URem:
1387 // X / undef -> undef. No change.
1388 // X % undef -> undef. No change.
1389 if (Op1LV.isUndefined()) break;
1390
1391 // undef / X -> 0. X could be maxint.
1392 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001393 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001394 return true;
1395
1396 case Instruction::AShr:
1397 // undef >>s X -> undef. No change.
1398 if (Op0LV.isUndefined()) break;
1399
1400 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1401 if (Op0LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001402 markForcedConstant(I, Op0LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001403 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001404 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001405 return true;
1406 case Instruction::LShr:
1407 case Instruction::Shl:
1408 // undef >> X -> undef. No change.
1409 // undef << X -> undef. No change.
1410 if (Op0LV.isUndefined()) break;
1411
1412 // X >> undef -> 0. X could be 0.
1413 // X << undef -> 0. X could be 0.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001414 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001415 return true;
1416 case Instruction::Select:
1417 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1418 if (Op0LV.isUndefined()) {
1419 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1420 Op1LV = getValueState(I->getOperand(2));
1421 } else if (Op1LV.isUndefined()) {
1422 // c ? undef : undef -> undef. No change.
1423 Op1LV = getValueState(I->getOperand(2));
1424 if (Op1LV.isUndefined())
1425 break;
1426 // Otherwise, c ? undef : x -> x.
1427 } else {
1428 // Leave Op1LV as Operand(1)'s LatticeValue.
1429 }
1430
1431 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001432 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001433 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001434 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001435 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001436 case Instruction::Call:
1437 // If a call has an undef result, it is because it is constant foldable
1438 // but one of the inputs was undef. Just force the result to
1439 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001440 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001441 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001442 }
1443 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001444
1445 TerminatorInst *TI = BB->getTerminator();
1446 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1447 if (!BI->isConditional()) continue;
1448 if (!getValueState(BI->getCondition()).isUndefined())
1449 continue;
1450 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001451 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001452 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001453 if (!getValueState(SI->getCondition()).isUndefined())
1454 continue;
1455 } else {
1456 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001457 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001458
Chris Lattner05bb7892008-01-28 00:32:30 +00001459 // If the edge to the second successor isn't thought to be feasible yet,
1460 // mark it so now. We pick the second one so that this goes to some
1461 // enumerated value in a switch instead of going to the default destination.
1462 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001463 continue;
1464
1465 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1466 // and return. This will make other blocks reachable, which will allow new
1467 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001468 markEdgeExecutable(BB, TI->getSuccessor(1));
1469
1470 // This must be a conditional branch of switch on undef. At this point,
1471 // force the old terminator to branch to the first successor. This is
1472 // required because we are now influencing the dataflow of the function with
1473 // the assumption that this edge is taken. If we leave the branch condition
1474 // as undef, then further analysis could think the undef went another way
1475 // leading to an inconsistent set of conclusions.
1476 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001477 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner05bb7892008-01-28 00:32:30 +00001478 } else {
1479 SwitchInst *SI = cast<SwitchInst>(TI);
1480 SI->setCondition(SI->getCaseValue(1));
1481 }
1482
Chris Lattnerd2d86702006-10-22 05:59:17 +00001483 return true;
1484 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001485
Chris Lattnerd2d86702006-10-22 05:59:17 +00001486 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001487}
1488
Chris Lattner82bec2c2004-11-15 04:44:20 +00001489
1490namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001491 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001492 //
Chris Lattner14051812004-11-15 07:15:04 +00001493 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001494 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001495 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001496 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001497 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001498 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001499
Chris Lattner14051812004-11-15 07:15:04 +00001500 // runOnFunction - Run the Sparse Conditional Constant Propagation
1501 // algorithm, and return true if the function was modified.
1502 //
1503 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001504
Chris Lattner14051812004-11-15 07:15:04 +00001505 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1506 AU.setPreservesCFG();
1507 }
1508 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001509} // end anonymous namespace
1510
Dan Gohman844731a2008-05-13 00:00:25 +00001511char SCCP::ID = 0;
1512static RegisterPass<SCCP>
1513X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001514
Chris Lattner2f096252009-11-02 02:33:50 +00001515// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001516FunctionPass *llvm::createSCCPPass() {
1517 return new SCCP();
1518}
1519
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001520static void DeleteInstructionInBlock(BasicBlock *BB) {
1521 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1522 ++NumDeadBlocks;
1523
1524 // Delete the instructions backwards, as it has a reduced likelihood of
1525 // having to update as many def-use and use-def chains.
1526 while (!isa<TerminatorInst>(BB->begin())) {
1527 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1528
1529 if (!I->use_empty())
1530 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1531 BB->getInstList().erase(I);
1532 ++NumInstRemoved;
1533 }
1534}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001535
Chris Lattner82bec2c2004-11-15 04:44:20 +00001536// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1537// and return true if the function was modified.
1538//
1539bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001540 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner5638dc62009-11-02 06:06:14 +00001541 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001542
1543 // Mark the first block of the function as being executable.
1544 Solver.MarkBlockExecutable(F.begin());
1545
Chris Lattner7e529e42004-11-15 05:45:33 +00001546 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001547 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001548 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001549
Chris Lattner82bec2c2004-11-15 04:44:20 +00001550 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001551 bool ResolvedUndefs = true;
1552 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001553 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001554 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001555 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001556 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001557
Chris Lattner7e529e42004-11-15 05:45:33 +00001558 bool MadeChanges = false;
1559
1560 // If we decided that there are basic blocks that are dead in this function,
1561 // delete their contents now. Note that we cannot actually delete the blocks,
1562 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001563
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001564 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001565 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001566 DeleteInstructionInBlock(BB);
1567 MadeChanges = true;
1568 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001569 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001570
1571 // Iterate over all of the instructions in a function, replacing them with
1572 // constants if we have found them to be of constant values.
1573 //
1574 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1575 Instruction *Inst = BI++;
1576 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1577 continue;
1578
Chris Lattner8db50122009-11-02 02:54:24 +00001579 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1580 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001581 continue;
1582
1583 Constant *Const = IV.isConstant()
1584 ? IV.getConstant() : UndefValue::get(Inst->getType());
1585 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1586
1587 // Replaces all of the uses of a variable with uses of the constant.
1588 Inst->replaceAllUsesWith(Const);
1589
1590 // Delete the instruction.
1591 Inst->eraseFromParent();
1592
1593 // Hey, we just changed something!
1594 MadeChanges = true;
1595 ++NumInstRemoved;
1596 }
1597 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001598
1599 return MadeChanges;
1600}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001601
1602namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001603 //===--------------------------------------------------------------------===//
1604 //
1605 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1606 /// Constant Propagation.
1607 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001608 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001609 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001610 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001611 bool runOnModule(Module &M);
1612 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001613} // end anonymous namespace
1614
Dan Gohman844731a2008-05-13 00:00:25 +00001615char IPSCCP::ID = 0;
1616static RegisterPass<IPSCCP>
1617Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1618
Chris Lattner2f096252009-11-02 02:33:50 +00001619// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001620ModulePass *llvm::createIPSCCPPass() {
1621 return new IPSCCP();
1622}
1623
1624
1625static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001626 // Delete any dead constantexpr klingons.
1627 GV->removeDeadConstantUsers();
1628
Chris Lattner59acc7d2004-12-10 08:02:06 +00001629 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1630 UI != E; ++UI)
1631 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001632 if (SI->getOperand(0) == GV || SI->isVolatile())
1633 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001634 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1635 // Make sure we are calling the function, not passing the address.
Chris Lattnerb2710042009-11-01 06:11:53 +00001636 if (UI.getOperandNo() != 0)
Nick Lewyckyaf386132008-11-03 03:49:14 +00001637 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001638 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1639 if (LI->isVolatile())
1640 return true;
Chris Lattnerb2710042009-11-01 06:11:53 +00001641 } else if (isa<BlockAddress>(*UI)) {
1642 // blockaddress doesn't take the address of the function, it takes addr
1643 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001644 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001645 return true;
1646 }
1647 return false;
1648}
1649
1650bool IPSCCP::runOnModule(Module &M) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001651 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner59acc7d2004-12-10 08:02:06 +00001652
1653 // Loop over all functions, marking arguments to those with their addresses
1654 // taken or that are external as overdefined.
1655 //
Chris Lattnerff3ca152009-11-02 06:34:04 +00001656 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1657 if (F->isDeclaration())
1658 continue;
1659
Chris Lattner14532d02009-11-03 03:42:51 +00001660 // If this is a strong or ODR definition of this function, then we can
1661 // propagate information about its result into callsites of it.
1662 if (!F->mayBeOverridden() &&
1663 !isa<StructType>(F->getReturnType()))
Chris Lattner59acc7d2004-12-10 08:02:06 +00001664 Solver.AddTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001665
1666 // If this function only has direct calls that we can see, we can track its
1667 // arguments and return value aggressively, and can assume it is not called
1668 // unless we see evidence to the contrary.
Chris Lattner2396cc32009-11-03 19:24:51 +00001669 if (F->hasLocalLinkage() && !AddressIsTaken(F)) {
1670 Solver.AddArgumentTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001671 continue;
Chris Lattner2396cc32009-11-03 19:24:51 +00001672 }
Chris Lattner14532d02009-11-03 03:42:51 +00001673
1674 // Assume the function is called.
1675 Solver.MarkBlockExecutable(F->begin());
1676
1677 // Assume nothing about the incoming arguments.
1678 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1679 AI != E; ++AI)
1680 Solver.markOverdefined(AI);
Chris Lattnerff3ca152009-11-02 06:34:04 +00001681 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001682
Chris Lattnerdd336d12004-12-11 05:15:59 +00001683 // Loop over global variables. We inform the solver about any internal global
1684 // variables that do not have their 'addresses taken'. If they don't have
1685 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001686 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1687 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001688 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001689 Solver.TrackValueOfGlobalVariable(G);
1690
Chris Lattner59acc7d2004-12-10 08:02:06 +00001691 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001692 bool ResolvedUndefs = true;
1693 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001694 Solver.Solve();
1695
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001696 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001697 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001698 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001699 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001700 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001701
1702 bool MadeChanges = false;
1703
1704 // Iterate over all of the instructions in the module, replacing them with
1705 // constants if we have found them to be of constant values.
1706 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001707 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001708
Chris Lattner59acc7d2004-12-10 08:02:06 +00001709 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001710 if (Solver.isBlockExecutable(F->begin())) {
1711 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1712 AI != E; ++AI) {
1713 if (AI->use_empty()) continue;
1714
1715 LatticeVal IV = Solver.getLatticeValueFor(AI);
1716 if (IV.isOverdefined()) continue;
1717
1718 Constant *CST = IV.isConstant() ?
1719 IV.getConstant() : UndefValue::get(AI->getType());
1720 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1721
1722 // Replaces all of the uses of a variable with uses of the
1723 // constant.
1724 AI->replaceAllUsesWith(CST);
1725 ++IPNumArgsElimed;
1726 }
Chris Lattner8db50122009-11-02 02:54:24 +00001727 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001728
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001729 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001730 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001731 DeleteInstructionInBlock(BB);
1732 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001733
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001734 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001735 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1736 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001737 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001738 TI->getSuccessor(i)->removePredecessor(BB);
1739 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001740 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001741 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001742 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001743
Chris Lattner864737b2004-12-11 05:32:19 +00001744 if (&*BB != &F->front())
1745 BlocksToErase.push_back(BB);
1746 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001747 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001748 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001749 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001750
1751 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1752 Instruction *Inst = BI++;
1753 if (Inst->getType()->isVoidTy())
1754 continue;
1755
Chris Lattner8db50122009-11-02 02:54:24 +00001756 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1757 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001758 continue;
1759
1760 Constant *Const = IV.isConstant()
1761 ? IV.getConstant() : UndefValue::get(Inst->getType());
1762 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1763
1764 // Replaces all of the uses of a variable with uses of the
1765 // constant.
1766 Inst->replaceAllUsesWith(Const);
1767
1768 // Delete the instruction.
1769 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1770 Inst->eraseFromParent();
1771
1772 // Hey, we just changed something!
1773 MadeChanges = true;
1774 ++IPNumInstRemoved;
1775 }
1776 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001777
1778 // Now that all instructions in the function are constant folded, erase dead
1779 // blocks, because we can now use ConstantFoldTerminator to get rid of
1780 // in-edges.
1781 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1782 // If there are any PHI nodes in this successor, drop entries for BB now.
1783 BasicBlock *DeadBB = BlocksToErase[i];
1784 while (!DeadBB->use_empty()) {
1785 Instruction *I = cast<Instruction>(DeadBB->use_back());
1786 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001787 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001788 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001789 // if this is a branch or switch on undef. Fold it manually as a
1790 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001791#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001792 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1793 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1794 "Branch should be foldable!");
1795 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1796 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1797 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001798 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001799 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001800#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001801
1802 // Make this an uncond branch to the first successor.
1803 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001804 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001805
1806 // Remove entries in successor phi nodes to remove edges.
1807 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1808 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1809
1810 // Remove the old terminator.
1811 TI->eraseFromParent();
1812 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001813 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001814
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001815 // Finally, delete the basic block.
1816 F->getBasicBlockList().erase(DeadBB);
1817 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001818 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001819 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001820
1821 // If we inferred constant or undef return values for a function, we replaced
1822 // all call uses with the inferred value. This means we don't need to bother
1823 // actually returning anything from the function. Replace all return
1824 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001825 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001826 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001827 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner14532d02009-11-03 03:42:51 +00001828 E = RV.end(); I != E; ++I) {
1829 Function *F = I->first;
1830 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1831 continue;
1832
1833 // We can only do this if we know that nothing else can call the function.
1834 if (!F->hasLocalLinkage() || AddressIsTaken(F))
1835 continue;
1836
1837 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1838 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1839 if (!isa<UndefValue>(RI->getOperand(0)))
1840 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1841 }
1842
Chris Lattnerdd336d12004-12-11 05:15:59 +00001843 // If we infered constant or undef values for globals variables, we can delete
1844 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001845 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1846 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001847 E = TG.end(); I != E; ++I) {
1848 GlobalVariable *GV = I->first;
1849 assert(!I->second.isOverdefined() &&
1850 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001851 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001852 while (!GV->use_empty()) {
1853 StoreInst *SI = cast<StoreInst>(GV->use_back());
1854 SI->eraseFromParent();
1855 }
1856 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001857 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001858 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001859
Chris Lattner59acc7d2004-12-10 08:02:06 +00001860 return MadeChanges;
1861}