blob: d068b15f2631b556b8058769f4148299c22f8660 [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-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 Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-06-27 23:38:11 +000017//
Chris Lattner347389d2001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Davide Italianof54f2f02016-05-05 21:05:36 +000020#include "llvm/Transforms/IPO/SCCP.h"
Chris Lattner067d6072007-02-02 20:38:30 +000021#include "llvm/ADT/DenseMap.h"
Chris Lattner65938fc2008-08-23 23:36:38 +000022#include "llvm/ADT/DenseSet.h"
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000023#include "llvm/ADT/PointerIntPair.h"
Chris Lattner809aee22009-11-02 06:11:23 +000024#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000025#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000026#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ConstantFolding.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000028#include "llvm/Analysis/GlobalsModRef.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000034#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Support/Debug.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Transforms/IPO.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000041#include "llvm/Transforms/Scalar.h"
Davide Italiano98f7e0e2016-05-18 15:18:25 +000042#include "llvm/Transforms/Scalar/SCCP.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Transforms/Utils/Local.h"
Chris Lattner347389d2001-06-27 23:38:11 +000044#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000046
Chandler Carruth964daaa2014-04-22 02:55:47 +000047#define DEBUG_TYPE "sccp"
48
Chris Lattner79a42ac2006-12-19 21:40:18 +000049STATISTIC(NumInstRemoved, "Number of instructions removed");
50STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
51
Nick Lewycky35e92c72008-03-08 07:48:41 +000052STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000053STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
54STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
55
Chris Lattner7d325382002-04-29 21:26:08 +000056namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000057/// LatticeVal class - This class represents the different lattice values that
58/// an LLVM value may occupy. It is a simple class with value semantics.
59///
Chris Lattner2dd09db2009-09-02 06:11:42 +000060class LatticeVal {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000061 enum LatticeValueTy {
Davide Italiano0f03ce02016-07-10 00:35:15 +000062 /// unknown - This LLVM Value has no known value yet.
63 unknown,
Jakub Staszak632a3552012-01-18 21:16:33 +000064
Chris Lattner1847f6d2006-12-20 06:21:33 +000065 /// constant - This LLVM Value has a specific constant value.
66 constant,
67
68 /// forcedconstant - This LLVM Value was thought to be undef until
69 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
70 /// with another (different) constant, it goes to overdefined, instead of
71 /// asserting.
72 forcedconstant,
Jakub Staszak632a3552012-01-18 21:16:33 +000073
Chris Lattner1847f6d2006-12-20 06:21:33 +000074 /// overdefined - This instruction is not known to be constant, and we know
75 /// it has a value.
76 overdefined
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000077 };
78
79 /// Val: This stores the current lattice value along with the Constant* for
80 /// the constant if this is a 'constant' or 'forcedconstant' value.
81 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Jakub Staszak632a3552012-01-18 21:16:33 +000082
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000083 LatticeValueTy getLatticeValue() const {
84 return Val.getInt();
85 }
Jakub Staszak632a3552012-01-18 21:16:33 +000086
Chris Lattner347389d2001-06-27 23:38:11 +000087public:
Davide Italiano0f03ce02016-07-10 00:35:15 +000088 LatticeVal() : Val(nullptr, unknown) {}
Jakub Staszak632a3552012-01-18 21:16:33 +000089
Davide Italiano0f03ce02016-07-10 00:35:15 +000090 bool isUnknown() const { return getLatticeValue() == unknown; }
Chris Lattner7ccf1a62009-11-02 03:03:42 +000091 bool isConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000092 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
93 }
Chris Lattner7ccf1a62009-11-02 03:03:42 +000094 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Jakub Staszak632a3552012-01-18 21:16:33 +000095
Chris Lattner7ccf1a62009-11-02 03:03:42 +000096 Constant *getConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000097 assert(isConstant() && "Cannot get the constant of a non-constant!");
98 return Val.getPointer();
99 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000100
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000101 /// markOverdefined - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000102 bool markOverdefined() {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000103 if (isOverdefined())
104 return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000105
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000106 Val.setInt(overdefined);
107 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000108 }
109
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000110 /// markConstant - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000111 bool markConstant(Constant *V) {
Chris Lattnere1d5cd92009-11-03 16:50:11 +0000112 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000113 assert(getConstant() == V && "Marking constant with different value");
114 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000115 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000116
Davide Italiano0f03ce02016-07-10 00:35:15 +0000117 if (isUnknown()) {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000118 Val.setInt(constant);
119 assert(V && "Marking constant with NULL");
120 Val.setPointer(V);
121 } else {
Jakub Staszak632a3552012-01-18 21:16:33 +0000122 assert(getLatticeValue() == forcedconstant &&
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000123 "Cannot move from overdefined to constant!");
124 // Stay at forcedconstant if the constant is the same.
125 if (V == getConstant()) return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000126
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000127 // Otherwise, we go to overdefined. Assumptions made based on the
128 // forced value are possibly wrong. Assuming this is another constant
129 // could expose a contradiction.
130 Val.setInt(overdefined);
131 }
132 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000133 }
134
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000135 /// getConstantInt - If this is a constant with a ConstantInt value, return it
136 /// otherwise return null.
137 ConstantInt *getConstantInt() const {
138 if (isConstant())
139 return dyn_cast<ConstantInt>(getConstant());
Craig Topperf40110f2014-04-25 05:29:35 +0000140 return nullptr;
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000141 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000142
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000143 void markForcedConstant(Constant *V) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000144 assert(isUnknown() && "Can't force a defined value!");
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000145 Val.setInt(forcedconstant);
146 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000147 }
Chris Lattner347389d2001-06-27 23:38:11 +0000148};
Chris Lattnere405ed92009-11-02 02:47:51 +0000149} // end anonymous namespace.
150
151
152namespace {
Chris Lattner347389d2001-06-27 23:38:11 +0000153
Chris Lattner347389d2001-06-27 23:38:11 +0000154//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000155//
Chris Lattner074be1f2004-11-15 04:44:20 +0000156/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
157/// Constant Propagation.
158///
159class SCCPSolver : public InstVisitor<SCCPSolver> {
Mehdi Amini46a43552015-03-04 18:43:29 +0000160 const DataLayout &DL;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000161 const TargetLibraryInfo *TLI;
Nick Lewycky77cb8e62011-07-25 21:16:04 +0000162 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattnerf5484032009-11-02 05:55:40 +0000163 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000164
Chris Lattner156b8c72009-11-03 23:40:48 +0000165 /// StructValueState - This maintains ValueState for values that have
166 /// StructType, for example for formal arguments, calls, insertelement, etc.
167 ///
168 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
Jakub Staszak632a3552012-01-18 21:16:33 +0000169
Chris Lattner91dbae62004-12-11 05:15:59 +0000170 /// GlobalValue - If we are tracking any values for the contents of a global
171 /// variable, we keep a mapping from the constant accessor to the element of
172 /// the global, to the currently known value. If the value becomes
173 /// overdefined, it's entry is simply removed from this map.
Chris Lattner067d6072007-02-02 20:38:30 +0000174 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000175
Devang Patela7a20752008-03-11 05:46:42 +0000176 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000177 /// value out of a function, it will have an entry in this map, indicating
178 /// what the known return value for the function is.
Devang Patela7a20752008-03-11 05:46:42 +0000179 DenseMap<Function*, LatticeVal> TrackedRetVals;
180
181 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
182 /// that return multiple values.
Chris Lattner65938fc2008-08-23 23:36:38 +0000183 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak632a3552012-01-18 21:16:33 +0000184
Chris Lattner156b8c72009-11-03 23:40:48 +0000185 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
186 /// represented here for efficient lookup.
187 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattnerb4394642004-12-10 08:02:06 +0000188
Chris Lattner2c427232009-11-03 20:52:57 +0000189 /// TrackingIncomingArguments - This is the set of functions for whose
190 /// arguments we make optimistic assumptions about and try to prove as
191 /// constants.
Chris Lattnercde8de52009-11-03 19:24:51 +0000192 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000193
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000194 /// The reason for two worklists is that overdefined is the lowest state
195 /// on the lattice, and moving things to overdefined as fast as possible
196 /// makes SCCP converge much faster.
197 ///
198 /// By having a separate worklist, we accomplish this because everything
199 /// possibly overdefined will become overdefined at the soonest possible
200 /// point.
Chris Lattner65938fc2008-08-23 23:36:38 +0000201 SmallVector<Value*, 64> OverdefinedInstWorkList;
202 SmallVector<Value*, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000203
204
Chris Lattner65938fc2008-08-23 23:36:38 +0000205 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000206
207 /// KnownFeasibleEdges - Entries in this set are edges which have already had
208 /// PHI nodes retriggered.
Chris Lattner65938fc2008-08-23 23:36:38 +0000209 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
210 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000211public:
Mehdi Amini46a43552015-03-04 18:43:29 +0000212 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
213 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000214
Chris Lattner074be1f2004-11-15 04:44:20 +0000215 /// MarkBlockExecutable - This method can be used by clients to mark all of
216 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000217 ///
218 /// This returns true if the block was not considered live before.
219 bool MarkBlockExecutable(BasicBlock *BB) {
David Blaikie70573dc2014-11-19 07:49:26 +0000220 if (!BBExecutable.insert(BB).second)
221 return false;
Nick Lewycky5cd95382013-06-26 00:30:18 +0000222 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000223 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000224 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000225 }
226
Chris Lattner91dbae62004-12-11 05:15:59 +0000227 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000228 /// inform the SCCPSolver that it should track loads and stores to the
229 /// specified global variable if it can. This is only legal to call if
230 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000231 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000232 // We only track the contents of scalar globals.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000233 if (GV->getValueType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000234 LatticeVal &IV = TrackedGlobals[GV];
235 if (!isa<UndefValue>(GV->getInitializer()))
236 IV.markConstant(GV->getInitializer());
237 }
238 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000239
240 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
241 /// and out of the specified function (which cannot have its address taken),
242 /// this method must be called.
243 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000244 // Add an entry, F -> undef.
Chris Lattner229907c2011-07-18 04:54:35 +0000245 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000246 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000247 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000248 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
249 LatticeVal()));
250 } else
251 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000252 }
253
Chris Lattnercde8de52009-11-03 19:24:51 +0000254 void AddArgumentTrackedFunction(Function *F) {
255 TrackingIncomingArguments.insert(F);
256 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000257
Chris Lattner074be1f2004-11-15 04:44:20 +0000258 /// Solve - Solve for constants and executable blocks.
259 ///
260 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000261
Chris Lattner1847f6d2006-12-20 06:21:33 +0000262 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000263 /// that branches on undef values cannot reach any of their successors.
264 /// However, this is not a safe assumption. After we solve dataflow, this
265 /// method should be use to handle this. If this returns true, the solver
266 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000267 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000268
Chris Lattneradd44f32008-08-23 23:39:31 +0000269 bool isBlockExecutable(BasicBlock *BB) const {
270 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000271 }
272
Davide Italiano00802692016-07-12 19:54:19 +0000273 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
274 std::vector<LatticeVal> StructValues;
275 StructType *STy = dyn_cast<StructType>(V->getType());
276 assert(STy && "getStructLatticeValueFor() can be called only on structs");
277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
278 auto I = StructValueState.find(std::make_pair(V, i));
279 assert(I != StructValueState.end() && "Value not in valuemap!");
280 StructValues.push_back(I->second);
281 }
282 return StructValues;
283 }
284
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000285 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattnerf5484032009-11-02 05:55:40 +0000286 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000287 assert(I != ValueState.end() && "V is not in valuemap!");
288 return I->second;
Chris Lattner074be1f2004-11-15 04:44:20 +0000289 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000290
Devang Patela7a20752008-03-11 05:46:42 +0000291 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner99e12952004-12-11 02:53:57 +0000292 ///
Devang Patela7a20752008-03-11 05:46:42 +0000293 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
294 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000295 }
296
Chris Lattner91dbae62004-12-11 05:15:59 +0000297 /// getTrackedGlobals - Get and return the set of inferred initializers for
298 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000299 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000300 return TrackedGlobals;
301 }
302
Davide Italiano15ff2d62016-07-20 20:17:13 +0000303 /// getMRVFunctionsTracked - Get the set of functions which return multiple
304 /// values tracked by the pass.
305 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
306 return MRVFunctionsTracked;
307 }
308
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000309 void markOverdefined(Value *V) {
Davide Italiano63266b62016-07-19 18:31:07 +0000310 assert(!V->getType()->isStructTy() &&
311 "structs should use markAnythingOverdefined");
Chris Lattnerc33fd462007-03-04 04:50:21 +0000312 markOverdefined(ValueState[V], V);
313 }
Chris Lattner99e12952004-12-11 02:53:57 +0000314
Chris Lattner156b8c72009-11-03 23:40:48 +0000315 /// markAnythingOverdefined - Mark the specified value overdefined. This
316 /// works with both scalars and structs.
317 void markAnythingOverdefined(Value *V) {
Chris Lattner229907c2011-07-18 04:54:35 +0000318 if (StructType *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000319 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
320 markOverdefined(getStructValueState(V, i), V);
321 else
322 markOverdefined(V);
323 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000324
Davide Italiano15ff2d62016-07-20 20:17:13 +0000325 // isStructLatticeConstant - Return true if all the lattice values
326 // corresponding to elements of the structure are not overdefined,
327 // false otherwise.
328 bool isStructLatticeConstant(Function *F, StructType *STy) {
329 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
330 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
331 assert(It != TrackedMultipleRetVals.end());
332 LatticeVal LV = It->second;
333 if (LV.isOverdefined())
334 return false;
335 }
336 return true;
337 }
338
Chris Lattner347389d2001-06-27 23:38:11 +0000339private:
Davide Italiano390b7ea2016-07-13 19:33:25 +0000340 // pushToWorkList - Helper for markConstant/markForcedConstant
341 void pushToWorkList(LatticeVal &IV, Value *V) {
342 if (IV.isOverdefined())
343 return OverdefinedInstWorkList.push_back(V);
344 InstWorkList.push_back(V);
345 }
346
Chris Lattnerd79334d2004-07-15 23:36:43 +0000347 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000348 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000349 // the users of the instruction are updated later.
350 //
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000351 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
352 if (!IV.markConstant(C)) return;
David Greene389fc3b2010-01-05 01:27:15 +0000353 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000354 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000355 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000356
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000357 void markConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000358 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerb4394642004-12-10 08:02:06 +0000359 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000360 }
361
Chris Lattnerf5484032009-11-02 05:55:40 +0000362 void markForcedConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000363 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000364 LatticeVal &IV = ValueState[V];
365 IV.markForcedConstant(C);
David Greene389fc3b2010-01-05 01:27:15 +0000366 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000367 pushToWorkList(IV, V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000368 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000369
370
Chris Lattnerd79334d2004-07-15 23:36:43 +0000371 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000372 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000373 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000374 void markOverdefined(LatticeVal &IV, Value *V) {
375 if (!IV.markOverdefined()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000376
David Greene389fc3b2010-01-05 01:27:15 +0000377 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000378 if (Function *F = dyn_cast<Function>(V))
David Greene389fc3b2010-01-05 01:27:15 +0000379 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000380 else
David Greene389fc3b2010-01-05 01:27:15 +0000381 dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000382 // Only instructions go on the work list
383 OverdefinedInstWorkList.push_back(V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000384 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000385
Chris Lattnerf5484032009-11-02 05:55:40 +0000386 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000387 if (IV.isOverdefined() || MergeWithV.isUnknown())
Chris Lattnerb4394642004-12-10 08:02:06 +0000388 return; // Noop.
389 if (MergeWithV.isOverdefined())
Davide Italiano21850012016-07-13 19:23:30 +0000390 return markOverdefined(IV, V);
391 if (IV.isUnknown())
392 return markConstant(IV, V, MergeWithV.getConstant());
393 if (IV.getConstant() != MergeWithV.getConstant())
394 return markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000395 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000396
Chris Lattnerf5484032009-11-02 05:55:40 +0000397 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Davide Italiano63266b62016-07-19 18:31:07 +0000398 assert(!V->getType()->isStructTy() &&
399 "non-structs should use markConstant");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000400 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000401 }
402
Chris Lattner347389d2001-06-27 23:38:11 +0000403
Chris Lattnerf5484032009-11-02 05:55:40 +0000404 /// getValueState - Return the LatticeVal object that corresponds to the
405 /// value. This function handles the case when the value hasn't been seen yet
406 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000407 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000408 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000409
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000410 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
411 ValueState.insert(std::make_pair(V, LatticeVal()));
412 LatticeVal &LV = I.first->second;
413
414 if (!I.second)
415 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000416
Chris Lattner1847f6d2006-12-20 06:21:33 +0000417 if (Constant *C = dyn_cast<Constant>(V)) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000418 // Undef values remain unknown.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000419 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000420 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000421 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000422
Chris Lattnera3c39d32009-11-02 02:33:50 +0000423 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000424 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000425 }
426
Chris Lattner156b8c72009-11-03 23:40:48 +0000427 /// getStructValueState - Return the LatticeVal object that corresponds to the
428 /// value/field pair. This function handles the case when the value hasn't
429 /// been seen yet by properly seeding constants etc.
430 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000431 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000432 assert(i < cast<StructType>(V->getType())->getNumElements() &&
433 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000434
435 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
436 bool> I = StructValueState.insert(
437 std::make_pair(std::make_pair(V, i), LatticeVal()));
438 LatticeVal &LV = I.first->second;
439
440 if (!I.second)
441 return LV; // Common case, already in the map.
442
Chris Lattner156b8c72009-11-03 23:40:48 +0000443 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000444 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000445
Craig Topperf40110f2014-04-25 05:29:35 +0000446 if (!Elt)
Chris Lattner156b8c72009-11-03 23:40:48 +0000447 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000448 else if (isa<UndefValue>(Elt))
Davide Italiano0f03ce02016-07-10 00:35:15 +0000449 ; // Undef values remain unknown.
Chris Lattnerfa775002012-01-26 02:32:04 +0000450 else
451 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000452 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000453
Chris Lattner156b8c72009-11-03 23:40:48 +0000454 // All others are underdefined by default.
455 return LV;
456 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000457
Chris Lattner156b8c72009-11-03 23:40:48 +0000458
Chris Lattnerf5484032009-11-02 05:55:40 +0000459 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
460 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000461 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
462 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
463 return; // This edge is already known to be executable!
464
Chris Lattner809aee22009-11-02 06:11:23 +0000465 if (!MarkBlockExecutable(Dest)) {
466 // If the destination is already executable, we just made an *edge*
467 // feasible that wasn't before. Revisit the PHI nodes in the block
468 // because they have potentially new operands.
David Greene389fc3b2010-01-05 01:27:15 +0000469 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Nick Lewycky5cd95382013-06-26 00:30:18 +0000470 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000471
Chris Lattner809aee22009-11-02 06:11:23 +0000472 PHINode *PN;
473 for (BasicBlock::iterator I = Dest->begin();
474 (PN = dyn_cast<PHINode>(I)); ++I)
475 visitPHINode(*PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000476 }
Chris Lattner347389d2001-06-27 23:38:11 +0000477 }
478
Chris Lattner074be1f2004-11-15 04:44:20 +0000479 // getFeasibleSuccessors - Return a vector of booleans to indicate which
480 // successors are reachable from a given terminator instruction.
481 //
Craig Topperb94011f2013-07-14 04:42:23 +0000482 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000483
484 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000485 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000486 //
487 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
488
489 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000490 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000491 // information, we need to update the specified user of this instruction.
492 //
Chris Lattnerfb141812009-11-03 03:42:51 +0000493 void OperandChangedState(Instruction *I) {
494 if (BBExecutable.count(I->getParent())) // Inst is executable?
495 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000496 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000497
Chris Lattner074be1f2004-11-15 04:44:20 +0000498private:
499 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000500
Chris Lattnera3c39d32009-11-02 02:33:50 +0000501 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000502 // operand made a transition, or the instruction is newly executable. Change
503 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000504 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000505
506 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000507 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000508 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000509
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000510 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000511 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000512 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000513 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000514 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000515 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000516 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000517 void visitExtractValueInst(ExtractValueInst &EVI);
518 void visitInsertValueInst(InsertValueInst &IVI);
Bill Wendlingfae14752011-08-12 20:24:12 +0000519 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000520 void visitFuncletPadInst(FuncletPadInst &FPI) {
521 markAnythingOverdefined(&FPI);
522 }
523 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
David Majnemereb518bd2015-08-04 08:21:40 +0000524 markAnythingOverdefined(&CPI);
525 visitTerminatorInst(CPI);
526 }
Chris Lattner6e560792002-04-18 15:13:15 +0000527
Chris Lattnera3c39d32009-11-02 02:33:50 +0000528 // Instructions that cannot be folded away.
Chris Lattnerf5484032009-11-02 05:55:40 +0000529 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000530 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000531 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandeze2971492009-10-24 04:23:03 +0000532 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000533 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000534 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000535 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000536 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000537 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000538 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000539 void visitCallSite (CallSite CS);
Davide Italianoa7f5e882016-05-04 23:27:13 +0000540 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
541 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
542 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Tim Northover6bf04e42014-06-13 14:54:09 +0000543 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
544 markAnythingOverdefined(&I);
545 }
Eli Friedman366bcce2011-08-02 21:35:16 +0000546 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
Victor Hernandez8acf2952009-10-23 21:09:37 +0000547 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner156b8c72009-11-03 23:40:48 +0000548 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000549
Chris Lattner113f4f42002-06-25 16:13:24 +0000550 void visitInstruction(Instruction &I) {
Chris Lattnera3c39d32009-11-02 02:33:50 +0000551 // If a new instruction is added to LLVM that we don't handle.
Nick Lewycky5cd95382013-06-26 00:30:18 +0000552 dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
Chris Lattner156b8c72009-11-03 23:40:48 +0000553 markAnythingOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000554 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000555};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000556
Duncan Sands2be91fc2007-07-20 08:56:21 +0000557} // end anonymous namespace
558
559
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000560// getFeasibleSuccessors - Return a vector of booleans to indicate which
561// successors are reachable from a given terminator instruction.
562//
Chris Lattner074be1f2004-11-15 04:44:20 +0000563void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000564 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000565 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000566 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000567 if (BI->isUnconditional()) {
568 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000569 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000570 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000571
Chris Lattnerf5484032009-11-02 05:55:40 +0000572 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000573 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000574 if (!CI) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000575 // Overdefined condition variables, and branches on unfoldable constant
576 // conditions, mean the branch could go either way.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000577 if (!BCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000578 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000579 return;
580 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000581
Chris Lattner6df5cec2009-11-02 02:30:06 +0000582 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000583 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000584 return;
585 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000586
David Majnemer654e1302015-07-31 17:58:14 +0000587 // Unwinding instructions successors are always executable.
588 if (TI.isExceptional()) {
589 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattneree8b9512009-10-29 01:21:20 +0000590 return;
591 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000592
Chris Lattneree8b9512009-10-29 01:21:20 +0000593 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000594 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000595 Succs[0] = true;
596 return;
597 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000598 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000599 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000600
Davide Italiano0f03ce02016-07-10 00:35:15 +0000601 if (!CI) { // Overdefined or unknown condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000602 // All destinations are executable!
Davide Italiano0f03ce02016-07-10 00:35:15 +0000603 if (!SCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000604 Succs.assign(TI.getNumSuccessors(), true);
605 return;
606 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000607
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000608 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000609 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000610 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000611
Chris Lattneree8b9512009-10-29 01:21:20 +0000612 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
613 if (isa<IndirectBrInst>(&TI)) {
614 // Just mark all destinations executable!
615 Succs.assign(TI.getNumSuccessors(), true);
616 return;
617 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000618
Chris Lattneree8b9512009-10-29 01:21:20 +0000619#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000620 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000621#endif
622 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000623}
624
625
Chris Lattner13b52e72002-05-02 21:18:01 +0000626// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000627// block to the 'To' basic block is currently feasible.
Chris Lattner13b52e72002-05-02 21:18:01 +0000628//
Chris Lattner074be1f2004-11-15 04:44:20 +0000629bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000630 assert(BBExecutable.count(To) && "Dest should always be alive!");
631
632 // Make sure the source basic block is executable!!
633 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000634
Chris Lattnera3c39d32009-11-02 02:33:50 +0000635 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000636 TerminatorInst *TI = From->getTerminator();
637 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
638 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000639 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000640
Chris Lattnerf5484032009-11-02 05:55:40 +0000641 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000642
Chris Lattner6df5cec2009-11-02 02:30:06 +0000643 // Overdefined condition variables mean the branch could go either way,
644 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000645 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000646 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000647 return !BCValue.isUnknown();
Jakub Staszak632a3552012-01-18 21:16:33 +0000648
Chris Lattner6df5cec2009-11-02 02:30:06 +0000649 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000650 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000651 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000652
David Majnemer654e1302015-07-31 17:58:14 +0000653 // Unwinding instructions successors are always executable.
654 if (TI->isExceptional())
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000655 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000656
Chris Lattneree8b9512009-10-29 01:21:20 +0000657 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000658 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000659 return true;
660
Chris Lattnerf5484032009-11-02 05:55:40 +0000661 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000662 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000663
Craig Topperf40110f2014-04-25 05:29:35 +0000664 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000665 return !SCValue.isUnknown();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000666
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000667 return SI->findCaseValue(CI).getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000668 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000669
Chris Lattneree8b9512009-10-29 01:21:20 +0000670 // Just mark all destinations executable!
671 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman3de2ddc2011-05-21 19:13:10 +0000672 if (isa<IndirectBrInst>(TI))
Chris Lattneree8b9512009-10-29 01:21:20 +0000673 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000674
Chris Lattneree8b9512009-10-29 01:21:20 +0000675#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000676 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000677#endif
Davide Italianodd04fee2015-11-25 21:03:36 +0000678 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattner13b52e72002-05-02 21:18:01 +0000679}
Chris Lattner347389d2001-06-27 23:38:11 +0000680
Chris Lattnera3c39d32009-11-02 02:33:50 +0000681// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000682// operand made a transition, or the instruction is newly executable. Change
683// the value type of I to reflect these changes if appropriate. This method
684// makes sure to do the following actions:
685//
686// 1. If a phi node merges two constants in, and has conflicting value coming
687// from different branches, or if the PHI node merges in an overdefined
688// value, then the PHI node becomes overdefined.
689// 2. If a phi node merges only constants in, and they all agree on value, the
690// PHI node becomes a constant value equal to that.
691// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
692// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
693// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
694// 6. If a conditional branch has a value that is constant, make the selected
695// destination executable
696// 7. If a conditional branch has a value that is overdefined, make all
697// successors executable.
698//
Chris Lattner074be1f2004-11-15 04:44:20 +0000699void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000700 // If this PN returns a struct, just mark the result overdefined.
701 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000702 if (PN.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000703 return markAnythingOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000704
Eli Friedman0a309292011-11-11 01:16:15 +0000705 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000706 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000707
Chris Lattner7a7b1142004-03-16 19:49:59 +0000708 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
709 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000710 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000711 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000712
Chris Lattner6e560792002-04-18 15:13:15 +0000713 // Look at all of the executable operands of the PHI node. If any of them
714 // are overdefined, the PHI becomes overdefined as well. If they are all
715 // constant, and they agree with each other, the PHI becomes the identical
716 // constant. If they are constant and don't agree, the PHI is overdefined.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000717 // If there are no executable operands, the PHI remains unknown.
Chris Lattner6e560792002-04-18 15:13:15 +0000718 //
Craig Topperf40110f2014-04-25 05:29:35 +0000719 Constant *OperandVal = nullptr;
Chris Lattnercccc5c72003-04-25 02:50:03 +0000720 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000721 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +0000722 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000723
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000724 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
725 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000726
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000727 if (IV.isOverdefined()) // PHI node becomes overdefined!
728 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000729
Craig Topperf40110f2014-04-25 05:29:35 +0000730 if (!OperandVal) { // Grab the first value.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000731 OperandVal = IV.getConstant();
732 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000733 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000734
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000735 // There is already a reachable operand. If we conflict with it,
736 // then the PHI node becomes overdefined. If we agree with it, we
737 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000738
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000739 // Check to see if there are two different constants merging, if so, the PHI
740 // node is overdefined.
741 if (IV.getConstant() != OperandVal)
742 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000743 }
744
Chris Lattner6e560792002-04-18 15:13:15 +0000745 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000746 // arguments that agree with each other(and OperandVal is the constant) or
747 // OperandVal is null because there are no defined incoming arguments. If
Davide Italiano0f03ce02016-07-10 00:35:15 +0000748 // this is the case, the PHI remains unknown.
Chris Lattner347389d2001-06-27 23:38:11 +0000749 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000750 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000751 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000752}
753
Chris Lattnerb4394642004-12-10 08:02:06 +0000754void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000755 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000756
Chris Lattnerb4394642004-12-10 08:02:06 +0000757 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000758 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000759
Devang Patela7a20752008-03-11 05:46:42 +0000760 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000761 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000762 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000763 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000764 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000765 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000766 return;
767 }
768 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000769
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000770 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000771 if (!TrackedMultipleRetVals.empty()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000772 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000773 if (MRVFunctionsTracked.count(F))
774 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
775 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
776 getStructValueState(ResultOp, i));
Jakub Staszak632a3552012-01-18 21:16:33 +0000777
Chris Lattnerb4394642004-12-10 08:02:06 +0000778 }
779}
780
Chris Lattner074be1f2004-11-15 04:44:20 +0000781void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000782 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000783 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000784
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000785 BasicBlock *BB = TI.getParent();
786
Chris Lattnera3c39d32009-11-02 02:33:50 +0000787 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000788 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000789 if (SuccFeasible[i])
790 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000791}
792
Chris Lattner074be1f2004-11-15 04:44:20 +0000793void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000794 LatticeVal OpSt = getValueState(I.getOperand(0));
795 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000796 markOverdefined(&I);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000797 else if (OpSt.isConstant()) {
Davide Italianod555bde2016-07-08 19:13:40 +0000798 // Fold the constant as we build.
Davide Italiano63c4ce82016-07-11 18:21:29 +0000799 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
800 I.getType(), DL);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000801 if (isa<UndefValue>(C))
802 return;
803 // Propagate constant value
804 markConstant(&I, C);
805 }
Chris Lattner6e560792002-04-18 15:13:15 +0000806}
807
Chris Lattner156b8c72009-11-03 23:40:48 +0000808
Dan Gohman041f9d02008-06-20 01:15:44 +0000809void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000810 // If this returns a struct, mark all elements over defined, we don't track
811 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000812 if (EVI.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000813 return markAnythingOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000814
Chris Lattner156b8c72009-11-03 23:40:48 +0000815 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000816 if (EVI.getNumIndices() != 1)
817 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000818
Chris Lattner156b8c72009-11-03 23:40:48 +0000819 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000820 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000821 unsigned i = *EVI.idx_begin();
822 LatticeVal EltVal = getStructValueState(AggVal, i);
823 mergeInValue(getValueState(&EVI), &EVI, EltVal);
824 } else {
825 // Otherwise, must be extracting from an array.
826 return markOverdefined(&EVI);
827 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000828}
829
830void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattner229907c2011-07-18 04:54:35 +0000831 StructType *STy = dyn_cast<StructType>(IVI.getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000832 if (!STy)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000833 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000834
Chris Lattner156b8c72009-11-03 23:40:48 +0000835 // If this has more than one index, we can't handle it, drive all results to
836 // undef.
837 if (IVI.getNumIndices() != 1)
838 return markAnythingOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000839
Chris Lattner156b8c72009-11-03 23:40:48 +0000840 Value *Aggr = IVI.getAggregateOperand();
841 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000842
Chris Lattner156b8c72009-11-03 23:40:48 +0000843 // Compute the result based on what we're inserting.
844 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
845 // This passes through all values that aren't the inserted element.
846 if (i != Idx) {
847 LatticeVal EltVal = getStructValueState(Aggr, i);
848 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
849 continue;
850 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000851
Chris Lattner156b8c72009-11-03 23:40:48 +0000852 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000853 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000854 // We don't track structs in structs.
855 markOverdefined(getStructValueState(&IVI, i), &IVI);
856 else {
857 LatticeVal InVal = getValueState(Val);
858 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
859 }
860 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000861}
862
Chris Lattner074be1f2004-11-15 04:44:20 +0000863void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000864 // If this select returns a struct, just mark the result overdefined.
865 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000866 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000867 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000868
Chris Lattnerf5484032009-11-02 05:55:40 +0000869 LatticeVal CondValue = getValueState(I.getCondition());
Davide Italiano0f03ce02016-07-10 00:35:15 +0000870 if (CondValue.isUnknown())
Chris Lattner06a0ed12006-02-08 02:38:11 +0000871 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000872
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000873 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000874 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
875 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000876 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000877 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000878
Chris Lattner06a0ed12006-02-08 02:38:11 +0000879 // Otherwise, the condition is overdefined or a constant we can't evaluate.
880 // See if we can produce something better than overdefined based on the T/F
881 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000882 LatticeVal TVal = getValueState(I.getTrueValue());
883 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000884
Chris Lattner06a0ed12006-02-08 02:38:11 +0000885 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000886 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000887 TVal.getConstant() == FVal.getConstant())
888 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000889
Davide Italiano0f03ce02016-07-10 00:35:15 +0000890 if (TVal.isUnknown()) // select ?, undef, X -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000891 return mergeInValue(&I, FVal);
Davide Italiano0f03ce02016-07-10 00:35:15 +0000892 if (FVal.isUnknown()) // select ?, X, undef -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000893 return mergeInValue(&I, TVal);
894 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000895}
896
Chris Lattnerf5484032009-11-02 05:55:40 +0000897// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000898void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000899 LatticeVal V1State = getValueState(I.getOperand(0));
900 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000901
Chris Lattner4f031622004-11-15 05:03:30 +0000902 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000903 if (IV.isOverdefined()) return;
904
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000905 if (V1State.isConstant() && V2State.isConstant()) {
906 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
907 V2State.getConstant());
908 // X op Y -> undef.
909 if (isa<UndefValue>(C))
910 return;
911 return markConstant(IV, &I, C);
912 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000913
Chris Lattnerf5484032009-11-02 05:55:40 +0000914 // If something is undef, wait for it to resolve.
915 if (!V1State.isOverdefined() && !V2State.isOverdefined())
916 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000917
Chris Lattnerf5484032009-11-02 05:55:40 +0000918 // Otherwise, one of our operands is overdefined. Try to produce something
919 // better than overdefined with some tricks.
Jakub Staszak632a3552012-01-18 21:16:33 +0000920
Chris Lattnerf5484032009-11-02 05:55:40 +0000921 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
922 // operand is overdefined.
923 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
Craig Topperf40110f2014-04-25 05:29:35 +0000924 LatticeVal *NonOverdefVal = nullptr;
Chris Lattnerf5484032009-11-02 05:55:40 +0000925 if (!V1State.isOverdefined())
926 NonOverdefVal = &V1State;
927 else if (!V2State.isOverdefined())
928 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +0000929
Chris Lattnerf5484032009-11-02 05:55:40 +0000930 if (NonOverdefVal) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000931 if (NonOverdefVal->isUnknown()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000932 // Could annihilate value.
933 if (I.getOpcode() == Instruction::And)
934 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner229907c2011-07-18 04:54:35 +0000935 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattnerf5484032009-11-02 05:55:40 +0000936 markConstant(IV, &I, Constant::getAllOnesValue(PT));
937 else
938 markConstant(IV, &I,
939 Constant::getAllOnesValue(I.getType()));
940 return;
Chris Lattnercbc01612004-12-11 23:15:19 +0000941 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000942
Chris Lattnerf5484032009-11-02 05:55:40 +0000943 if (I.getOpcode() == Instruction::And) {
944 // X and 0 = 0
945 if (NonOverdefVal->getConstant()->isNullValue())
946 return markConstant(IV, &I, NonOverdefVal->getConstant());
947 } else {
948 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
949 if (CI->isAllOnesValue()) // X or -1 = -1
950 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +0000951 }
952 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000953 }
Chris Lattnercbc01612004-12-11 23:15:19 +0000954
955
Chris Lattnerf5484032009-11-02 05:55:40 +0000956 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000957}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000958
Chris Lattnera3c39d32009-11-02 02:33:50 +0000959// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000960void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000961 LatticeVal V1State = getValueState(I.getOperand(0));
962 LatticeVal V2State = getValueState(I.getOperand(1));
963
Reid Spencer266e42b2006-12-23 06:05:41 +0000964 LatticeVal &IV = ValueState[&I];
965 if (IV.isOverdefined()) return;
966
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000967 if (V1State.isConstant() && V2State.isConstant()) {
968 Constant *C = ConstantExpr::getCompare(
969 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
970 if (isa<UndefValue>(C))
971 return;
972 return markConstant(IV, &I, C);
973 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000974
Davide Italiano0f03ce02016-07-10 00:35:15 +0000975 // If operands are still unknown, wait for it to resolve.
Chris Lattnerf5484032009-11-02 05:55:40 +0000976 if (!V1State.isOverdefined() && !V2State.isOverdefined())
977 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000978
Chris Lattnerf5484032009-11-02 05:55:40 +0000979 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000980}
981
Robert Bocchinobd518d12006-01-10 19:05:05 +0000982void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000983 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000984 return markOverdefined(&I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000985}
986
Robert Bocchino6dce2502006-01-17 20:06:55 +0000987void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000988 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000989 return markOverdefined(&I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000990}
991
Chris Lattner17bd6052006-04-08 01:19:12 +0000992void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000993 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000994 return markOverdefined(&I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000995}
996
Chris Lattnera3c39d32009-11-02 02:33:50 +0000997// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000998// can turn this into a getelementptr ConstantExpr.
999//
Chris Lattner074be1f2004-11-15 04:44:20 +00001000void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001001 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001002
Chris Lattner0e7ec672007-02-02 20:51:48 +00001003 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001004 Operands.reserve(I.getNumOperands());
1005
1006 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001007 LatticeVal State = getValueState(I.getOperand(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001008 if (State.isUnknown())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001009 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001010
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001011 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001012 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001013
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001014 assert(State.isConstant() && "Unknown state!");
1015 Operands.push_back(State.getConstant());
1016 }
1017
1018 Constant *Ptr = Operands[0];
Craig Toppere1d12942014-08-27 05:25:25 +00001019 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001020 Constant *C =
1021 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1022 if (isa<UndefValue>(C))
1023 return;
1024 markConstant(&I, C);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001025}
Brian Gaeke960707c2003-11-11 22:41:34 +00001026
Chris Lattnerf5484032009-11-02 05:55:40 +00001027void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001028 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001029 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001030 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001031
Chris Lattner91dbae62004-12-11 05:15:59 +00001032 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1033 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001034
Chris Lattner91dbae62004-12-11 05:15:59 +00001035 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001036 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001037 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1038
Chris Lattnerf5484032009-11-02 05:55:40 +00001039 // Get the value we are storing into the global, then merge it.
1040 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001041 if (I->second.isOverdefined())
1042 TrackedGlobals.erase(I); // No need to keep tracking this!
1043}
1044
1045
Chris Lattner49f74522004-01-12 04:29:41 +00001046// Handle load instructions. If the operand is a constant pointer to a constant
1047// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001048void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001049 // If this load is of a struct, just mark the result overdefined.
David Majnemerf3b99dd2016-01-07 19:30:13 +00001050 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001051 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001052
Chris Lattnerf5484032009-11-02 05:55:40 +00001053 LatticeVal PtrVal = getValueState(I.getOperand(0));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001054 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001055
Chris Lattner4f031622004-11-15 05:03:30 +00001056 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001057 if (IV.isOverdefined()) return;
1058
Chris Lattnerf5484032009-11-02 05:55:40 +00001059 if (!PtrVal.isConstant() || I.isVolatile())
1060 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001061
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001062 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001063
David Majnemerbae94572016-01-07 19:25:39 +00001064 // load null is undefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001065 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
David Majnemerbae94572016-01-07 19:25:39 +00001066 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001067
Chris Lattnerf5484032009-11-02 05:55:40 +00001068 // Transform load (constant global) into the value loaded.
1069 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001070 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001071 // If we are tracking this global, merge in the known value for it.
1072 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1073 TrackedGlobals.find(GV);
1074 if (It != TrackedGlobals.end()) {
1075 mergeInValue(IV, &I, It->second);
1076 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001077 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001078 }
Chris Lattner49f74522004-01-12 04:29:41 +00001079 }
1080
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001081 // Transform load from a constant into a constant if possible.
Eduard Burtescu14239212016-01-22 01:17:26 +00001082 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001083 if (isa<UndefValue>(C))
1084 return;
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001085 return markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001086 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001087
Chris Lattner49f74522004-01-12 04:29:41 +00001088 // Otherwise we cannot say for certain what value this load will produce.
1089 // Bail out.
1090 markOverdefined(IV, &I);
1091}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001092
Chris Lattnerb4394642004-12-10 08:02:06 +00001093void SCCPSolver::visitCallSite(CallSite CS) {
1094 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001095 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001096
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001097 // The common case is that we aren't tracking the callee, either because we
1098 // are not doing interprocedural analysis or the callee is indirect, or is
1099 // external. Handle these cases first.
Craig Topperf40110f2014-04-25 05:29:35 +00001100 if (!F || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001101CallOverdefined:
1102 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001103 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001104
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001105 // Otherwise, if we have a single return value case, and if the function is
1106 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001107 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001108 canConstantFoldCallTo(F)) {
Jakub Staszak632a3552012-01-18 21:16:33 +00001109
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001110 SmallVector<Constant*, 8> Operands;
1111 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1112 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001113 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001114
Davide Italiano0f03ce02016-07-10 00:35:15 +00001115 if (State.isUnknown())
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001116 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001117 if (State.isOverdefined())
1118 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001119 assert(State.isConstant() && "Unknown state!");
1120 Operands.push_back(State.getConstant());
1121 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001122
David Majnemer2098b86f2014-11-07 08:54:19 +00001123 if (getValueState(I).isOverdefined())
1124 return;
1125
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001126 // If we can constant fold this, mark the result of the call as a
1127 // constant.
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001128 if (Constant *C = ConstantFoldCall(F, Operands, TLI)) {
1129 // call -> undef.
1130 if (isa<UndefValue>(C))
1131 return;
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001132 return markConstant(I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001133 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001134 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001135
1136 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner156b8c72009-11-03 23:40:48 +00001137 return markAnythingOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001138 }
1139
Chris Lattnercde8de52009-11-03 19:24:51 +00001140 // If this is a local function that doesn't have its address taken, mark its
1141 // entry block executable and merge in the actual arguments to the call into
1142 // the formal arguments of the function.
1143 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001144 MarkBlockExecutable(&F->front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001145
Chris Lattnercde8de52009-11-03 19:24:51 +00001146 // Propagate information from this call site into the callee.
1147 CallSite::arg_iterator CAI = CS.arg_begin();
1148 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1149 AI != E; ++AI, ++CAI) {
1150 // If this argument is byval, and if the function is not readonly, there
1151 // will be an implicit copy formed of the input aggregate.
1152 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001153 markOverdefined(&*AI);
Chris Lattnercde8de52009-11-03 19:24:51 +00001154 continue;
1155 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001156
Chris Lattner229907c2011-07-18 04:54:35 +00001157 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001158 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1159 LatticeVal CallArg = getStructValueState(*CAI, i);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001160 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
Chris Lattner762b56f2009-11-04 18:57:42 +00001161 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001162 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001163 mergeInValue(&*AI, getValueState(*CAI));
Chris Lattner156b8c72009-11-03 23:40:48 +00001164 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001165 }
1166 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001167
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001168 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattner229907c2011-07-18 04:54:35 +00001169 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001170 if (!MRVFunctionsTracked.count(F))
1171 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001172
Chris Lattner156b8c72009-11-03 23:40:48 +00001173 // If we are tracking this callee, propagate the result of the function
1174 // into this call site.
1175 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001176 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001177 TrackedMultipleRetVals[std::make_pair(F, i)]);
1178 } else {
1179 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1180 if (TFRVI == TrackedRetVals.end())
1181 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001182
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001183 // If so, propagate the return value of the callee into this call result.
1184 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001185 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001186}
Chris Lattner074be1f2004-11-15 04:44:20 +00001187
Chris Lattner074be1f2004-11-15 04:44:20 +00001188void SCCPSolver::Solve() {
1189 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001190 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001191 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001192 // Process the overdefined instruction's work list first, which drives other
1193 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001194 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001195 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001196
David Greene389fc3b2010-01-05 01:27:15 +00001197 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001198
Chris Lattner074be1f2004-11-15 04:44:20 +00001199 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001200 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001201 //
1202 // Anything on this worklist that is overdefined need not be visited
1203 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001204 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001205 //
Chandler Carruthcdf47882014-03-09 03:16:01 +00001206 for (User *U : I->users())
1207 if (Instruction *UI = dyn_cast<Instruction>(U))
1208 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001209 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001210
Chris Lattnera3c39d32009-11-02 02:33:50 +00001211 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001212 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001213 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001214
David Greene389fc3b2010-01-05 01:27:15 +00001215 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001216
Chris Lattnerf5484032009-11-02 05:55:40 +00001217 // "I" got into the work list because it made the transition from undef to
1218 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001219 //
1220 // Anything on this worklist that is overdefined need not be visited
1221 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001222 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001223 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001224 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001225 for (User *U : I->users())
1226 if (Instruction *UI = dyn_cast<Instruction>(U))
1227 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001228 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001229
Chris Lattnera3c39d32009-11-02 02:33:50 +00001230 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001231 while (!BBWorkList.empty()) {
1232 BasicBlock *BB = BBWorkList.back();
1233 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001234
David Greene389fc3b2010-01-05 01:27:15 +00001235 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001236
Chris Lattner074be1f2004-11-15 04:44:20 +00001237 // Notify all instructions in this basic block that they are newly
1238 // executable.
1239 visit(BB);
1240 }
1241 }
1242}
1243
Chris Lattner1847f6d2006-12-20 06:21:33 +00001244/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001245/// that branches on undef values cannot reach any of their successors.
1246/// However, this is not a safe assumption. After we solve dataflow, this
1247/// method should be use to handle this. If this returns true, the solver
1248/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001249///
1250/// This method handles this by finding an unresolved branch and marking it one
1251/// of the edges from the block as being feasible, even though the condition
1252/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1253/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001254/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001255/// constraints on the condition of the branch, as that would impact other users
1256/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001257///
1258/// This scan also checks for values that use undefs, whose results are actually
1259/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1260/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1261/// even if X isn't defined.
1262bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001263 for (BasicBlock &BB : F) {
1264 if (!BBExecutable.count(&BB))
Chris Lattneraf170962006-10-22 05:59:17 +00001265 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001266
Benjamin Kramer135f7352016-06-26 12:28:59 +00001267 for (Instruction &I : BB) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001268 // Look for instructions which produce undef values.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001269 if (I.getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001270
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001271 if (StructType *STy = dyn_cast<StructType>(I.getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001272 // Only a few things that can be structs matter for undef.
1273
1274 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001275 if (CallSite CS = CallSite(&I))
Eli Friedman1815b682011-09-20 23:28:51 +00001276 if (Function *F = CS.getCalledFunction())
1277 if (MRVFunctionsTracked.count(F))
1278 continue;
1279
1280 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001281 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001282 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1283 continue;
1284
1285 // Send the results of everything else to overdefined. We could be
1286 // more precise than this but it isn't worth bothering.
1287 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001288 LatticeVal &LV = getStructValueState(&I, i);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001289 if (LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001290 markOverdefined(LV, &I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001291 }
1292 continue;
1293 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001294
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001295 LatticeVal &LV = getValueState(&I);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001296 if (!LV.isUnknown()) continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001297
Eli Friedmand7749be2011-08-17 18:10:43 +00001298 // extractvalue is safe; check here because the argument is a struct.
1299 if (isa<ExtractValueInst>(I))
1300 continue;
1301
1302 // Compute the operand LatticeVals, for convenience below.
1303 // Anything taking a struct is conservatively assumed to require
1304 // overdefined markings.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001305 if (I.getOperand(0)->getType()->isStructTy()) {
1306 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001307 return true;
1308 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001309 LatticeVal Op0LV = getValueState(I.getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001310 LatticeVal Op1LV;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001311 if (I.getNumOperands() == 2) {
1312 if (I.getOperand(1)->getType()->isStructTy()) {
1313 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001314 return true;
1315 }
1316
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001317 Op1LV = getValueState(I.getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001318 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001319 // If this is an instructions whose result is defined even if the input is
1320 // not fully defined, propagate the information.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001321 Type *ITy = I.getType();
1322 switch (I.getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001323 case Instruction::Add:
1324 case Instruction::Sub:
1325 case Instruction::Trunc:
1326 case Instruction::FPTrunc:
1327 case Instruction::BitCast:
1328 break; // Any undef -> undef
1329 case Instruction::FSub:
1330 case Instruction::FAdd:
1331 case Instruction::FMul:
1332 case Instruction::FDiv:
1333 case Instruction::FRem:
1334 // Floating-point binary operation: be conservative.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001335 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001336 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001337 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001338 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001339 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001340 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001341 case Instruction::SExt:
1342 case Instruction::FPToUI:
1343 case Instruction::FPToSI:
1344 case Instruction::FPExt:
1345 case Instruction::PtrToInt:
1346 case Instruction::IntToPtr:
1347 case Instruction::SIToFP:
1348 case Instruction::UIToFP:
1349 // undef -> 0; some outputs are impossible
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001350 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001351 return true;
1352 case Instruction::Mul:
1353 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001354 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001355 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001356 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001357 // undef * X -> 0. X could be zero.
1358 // undef & X -> 0. X could be zero.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001359 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001360 return true;
1361
1362 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001363 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001364 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001365 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001366 // undef | X -> -1. X could be -1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001367 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001368 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001369
Eli Friedman0793eb42011-08-16 22:06:31 +00001370 case Instruction::Xor:
1371 // undef ^ undef -> 0; strictly speaking, this is not strictly
1372 // necessary, but we try to be nice to people who expect this
1373 // behavior in simple cases
Davide Italiano0f03ce02016-07-10 00:35:15 +00001374 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001375 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001376 return true;
1377 }
1378 // undef ^ X -> undef
1379 break;
1380
Chris Lattner1847f6d2006-12-20 06:21:33 +00001381 case Instruction::SDiv:
1382 case Instruction::UDiv:
1383 case Instruction::SRem:
1384 case Instruction::URem:
1385 // X / undef -> undef. No change.
1386 // X % undef -> undef. No change.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001387 if (Op1LV.isUnknown()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001388
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001389 // X / 0 -> undef. No change.
1390 // X % 0 -> undef. No change.
1391 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1392 break;
1393
Chris Lattner1847f6d2006-12-20 06:21:33 +00001394 // undef / X -> 0. X could be maxint.
1395 // undef % X -> 0. X could be 1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001396 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001397 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +00001398
Chris Lattner1847f6d2006-12-20 06:21:33 +00001399 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001400 // X >>a undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001401 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001402
David Majnemer96f0d382016-05-12 03:07:40 +00001403 // Shifting by the bitwidth or more is undefined.
1404 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001405 if (auto *ShiftAmt = Op1LV.getConstantInt())
1406 if (ShiftAmt->getLimitedValue() >=
1407 ShiftAmt->getType()->getScalarSizeInBits())
1408 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001409 }
1410
Eli Friedman0793eb42011-08-16 22:06:31 +00001411 // undef >>a X -> all ones
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001412 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001413 return true;
1414 case Instruction::LShr:
1415 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001416 // X << undef -> undef.
1417 // X >> undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001418 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001419
David Majnemer96f0d382016-05-12 03:07:40 +00001420 // Shifting by the bitwidth or more is undefined.
1421 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001422 if (auto *ShiftAmt = Op1LV.getConstantInt())
1423 if (ShiftAmt->getLimitedValue() >=
1424 ShiftAmt->getType()->getScalarSizeInBits())
1425 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001426 }
1427
Eli Friedman0793eb42011-08-16 22:06:31 +00001428 // undef << X -> 0
1429 // undef >> X -> 0
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001430 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001431 return true;
1432 case Instruction::Select:
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001433 Op1LV = getValueState(I.getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001434 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001435 if (Op0LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001436 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001437 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001438 } else if (Op1LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001439 // c ? undef : undef -> undef. No change.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001440 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001441 if (Op1LV.isUnknown())
Chris Lattner1847f6d2006-12-20 06:21:33 +00001442 break;
1443 // Otherwise, c ? undef : x -> x.
1444 } else {
1445 // Leave Op1LV as Operand(1)'s LatticeValue.
1446 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001447
Chris Lattner1847f6d2006-12-20 06:21:33 +00001448 if (Op1LV.isConstant())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001449 markForcedConstant(&I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001450 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001451 markOverdefined(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001452 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001453 case Instruction::Load:
1454 // A load here means one of two things: a load of undef from a global,
1455 // a load from an unknown pointer. Either way, having it return undef
1456 // is okay.
1457 break;
1458 case Instruction::ICmp:
1459 // X == undef -> undef. Other comparisons get more complicated.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001460 if (cast<ICmpInst>(&I)->isEquality())
Eli Friedman0793eb42011-08-16 22:06:31 +00001461 break;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001462 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001463 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001464 case Instruction::Call:
1465 case Instruction::Invoke: {
1466 // There are two reasons a call can have an undef result
1467 // 1. It could be tracked.
1468 // 2. It could be constant-foldable.
1469 // Because of the way we solve return values, tracked calls must
1470 // never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001471 if (Function *F = CallSite(&I).getCalledFunction())
Eli Friedman1815b682011-09-20 23:28:51 +00001472 if (TrackedRetVals.count(F))
1473 break;
1474
1475 // If the call is constant-foldable, we mark it overdefined because
1476 // we do not know what return values are valid.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001477 markOverdefined(&I);
Eli Friedman1815b682011-09-20 23:28:51 +00001478 return true;
1479 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001480 default:
1481 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001482 // overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001483 markOverdefined(&I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001484 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001485 }
1486 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001487
Chris Lattneradca6082010-04-05 22:14:48 +00001488 // Check to see if we have a branch or switch on an undefined value. If so
1489 // we force the branch to go one way or the other to make the successor
1490 // values live. It doesn't really matter which way we force it.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001491 TerminatorInst *TI = BB.getTerminator();
Chris Lattneraf170962006-10-22 05:59:17 +00001492 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1493 if (!BI->isConditional()) continue;
Davide Italiano0f03ce02016-07-10 00:35:15 +00001494 if (!getValueState(BI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001495 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001496
Chris Lattneradca6082010-04-05 22:14:48 +00001497 // If the input to SCCP is actually branch on undef, fix the undef to
1498 // false.
1499 if (isa<UndefValue>(BI->getCondition())) {
1500 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Benjamin Kramer135f7352016-06-26 12:28:59 +00001501 markEdgeExecutable(&BB, TI->getSuccessor(1));
Chris Lattneradca6082010-04-05 22:14:48 +00001502 return true;
1503 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001504
Chris Lattneradca6082010-04-05 22:14:48 +00001505 // Otherwise, it is a branch on a symbolic value which is currently
1506 // considered to be undef. Handle this by forcing the input value to the
1507 // branch to false.
1508 markForcedConstant(BI->getCondition(),
1509 ConstantInt::getFalse(TI->getContext()));
1510 return true;
1511 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001512
Chris Lattneradca6082010-04-05 22:14:48 +00001513 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Davide Italiano094dadd2016-07-15 18:33:16 +00001514 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001515 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001516
Chris Lattneradca6082010-04-05 22:14:48 +00001517 // If the input to SCCP is actually switch on undef, fix the undef to
1518 // the first constant.
1519 if (isa<UndefValue>(SI->getCondition())) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001520 SI->setCondition(SI->case_begin().getCaseValue());
Benjamin Kramer135f7352016-06-26 12:28:59 +00001521 markEdgeExecutable(&BB, SI->case_begin().getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001522 return true;
1523 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001524
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001525 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001526 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001527 }
Chris Lattneraf170962006-10-22 05:59:17 +00001528 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001529
Chris Lattneraf170962006-10-22 05:59:17 +00001530 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001531}
1532
Davide Italiano6f735882016-07-14 20:25:54 +00001533static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
Davide Italiano296e9782016-07-13 23:20:04 +00001534 Constant *Const = nullptr;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001535 if (V->getType()->isStructTy()) {
1536 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
Davide Italiano296e9782016-07-13 23:20:04 +00001537 if (std::any_of(IVs.begin(), IVs.end(),
1538 [](LatticeVal &LV) { return LV.isOverdefined(); }))
1539 return false;
1540 std::vector<Constant *> ConstVals;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001541 StructType *ST = dyn_cast<StructType>(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001542 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1543 LatticeVal V = IVs[i];
1544 ConstVals.push_back(V.isConstant()
1545 ? V.getConstant()
1546 : UndefValue::get(ST->getElementType(i)));
1547 }
1548 Const = ConstantStruct::get(ST, ConstVals);
1549 } else {
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001550 LatticeVal IV = Solver.getLatticeValueFor(V);
Davide Italiano296e9782016-07-13 23:20:04 +00001551 if (IV.isOverdefined())
1552 return false;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001553 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001554 }
1555 assert(Const && "Constant is nullptr here!");
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001556 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
Davide Italiano296e9782016-07-13 23:20:04 +00001557
1558 // Replaces all of the uses of a variable with uses of the constant.
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001559 V->replaceAllUsesWith(Const);
Davide Italiano6ed6d772016-07-14 01:27:29 +00001560 return true;
1561}
1562
Davide Italiano6f735882016-07-14 20:25:54 +00001563static bool tryToReplaceInstWithConstant(SCCPSolver &Solver, Instruction *Inst,
Davide Italiano6ed6d772016-07-14 01:27:29 +00001564 bool shouldEraseFromParent) {
1565 if (!tryToReplaceWithConstant(Solver, Inst))
1566 return false;
Davide Italiano296e9782016-07-13 23:20:04 +00001567
1568 // Delete the instruction.
1569 if (shouldEraseFromParent)
1570 Inst->eraseFromParent();
1571 return true;
1572}
1573
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001574// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner074be1f2004-11-15 04:44:20 +00001575// and return true if the function was modified.
1576//
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001577static bool runSCCP(Function &F, const DataLayout &DL,
1578 const TargetLibraryInfo *TLI) {
David Greene389fc3b2010-01-05 01:27:15 +00001579 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001580 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001581
1582 // Mark the first block of the function as being executable.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001583 Solver.MarkBlockExecutable(&F.front());
Chris Lattner074be1f2004-11-15 04:44:20 +00001584
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001585 // Mark all arguments to the function as being overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001586 for (Argument &AI : F.args())
1587 Solver.markAnythingOverdefined(&AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001588
Chris Lattner074be1f2004-11-15 04:44:20 +00001589 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001590 bool ResolvedUndefs = true;
1591 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001592 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001593 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001594 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001595 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001596
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001597 bool MadeChanges = false;
1598
1599 // If we decided that there are basic blocks that are dead in this function,
1600 // delete their contents now. Note that we cannot actually delete the blocks,
1601 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001602
Benjamin Kramer135f7352016-06-26 12:28:59 +00001603 for (BasicBlock &BB : F) {
1604 if (!Solver.isBlockExecutable(&BB)) {
1605 DEBUG(dbgs() << " BasicBlock Dead:" << BB);
David Majnemer88542a02016-01-24 06:26:47 +00001606
1607 ++NumDeadBlocks;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001608 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer88542a02016-01-24 06:26:47 +00001609
Chris Lattnere405ed92009-11-02 02:47:51 +00001610 MadeChanges = true;
1611 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001612 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001613
Chris Lattnere405ed92009-11-02 02:47:51 +00001614 // Iterate over all of the instructions in a function, replacing them with
1615 // constants if we have found them to be of constant values.
1616 //
Benjamin Kramer135f7352016-06-26 12:28:59 +00001617 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001618 Instruction *Inst = &*BI++;
Chris Lattnere405ed92009-11-02 02:47:51 +00001619 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1620 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001621
Davide Italiano296e9782016-07-13 23:20:04 +00001622 if (tryToReplaceInstWithConstant(Solver, Inst,
1623 true /* shouldEraseFromParent */)) {
1624 // Hey, we just changed something!
1625 MadeChanges = true;
1626 ++NumInstRemoved;
Davide Italiano00802692016-07-12 19:54:19 +00001627 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001628 }
1629 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001630
1631 return MadeChanges;
1632}
Chris Lattnerb4394642004-12-10 08:02:06 +00001633
Sean Silva36e0d012016-08-09 00:28:15 +00001634PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001635 const DataLayout &DL = F.getParent()->getDataLayout();
1636 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1637 if (!runSCCP(F, DL, &TLI))
1638 return PreservedAnalyses::all();
Davide Italiano484b5ab2016-05-29 00:31:15 +00001639
1640 auto PA = PreservedAnalyses();
1641 PA.preserve<GlobalsAA>();
1642 return PA;
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001643}
1644
1645namespace {
1646//===--------------------------------------------------------------------===//
1647//
1648/// SCCP Class - This class uses the SCCPSolver to implement a per-function
1649/// Sparse Conditional Constant Propagator.
1650///
Davide Italiano46f249b2016-05-19 15:58:02 +00001651class SCCPLegacyPass : public FunctionPass {
1652public:
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001653 void getAnalysisUsage(AnalysisUsage &AU) const override {
1654 AU.addRequired<TargetLibraryInfoWrapperPass>();
1655 AU.addPreserved<GlobalsAAWrapperPass>();
1656 }
1657 static char ID; // Pass identification, replacement for typeid
1658 SCCPLegacyPass() : FunctionPass(ID) {
1659 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1660 }
1661
1662 // runOnFunction - Run the Sparse Conditional Constant Propagation
1663 // algorithm, and return true if the function was modified.
1664 //
1665 bool runOnFunction(Function &F) override {
1666 if (skipFunction(F))
1667 return false;
1668 const DataLayout &DL = F.getParent()->getDataLayout();
1669 const TargetLibraryInfo *TLI =
1670 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1671 return runSCCP(F, DL, TLI);
1672 }
1673};
1674} // end anonymous namespace
1675
1676char SCCPLegacyPass::ID = 0;
1677INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1678 "Sparse Conditional Constant Propagation", false, false)
1679INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1680INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1681 "Sparse Conditional Constant Propagation", false, false)
1682
1683// createSCCPPass - This is the public interface to this file.
1684FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1685
Gabor Greif9027ffb2010-03-24 10:29:52 +00001686static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001687 // Delete any dead constantexpr klingons.
1688 GV->removeDeadConstantUsers();
1689
Chandler Carruthcdf47882014-03-09 03:16:01 +00001690 for (const Use &U : GV->uses()) {
1691 const User *UR = U.getUser();
1692 if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001693 if (SI->getOperand(0) == GV || SI->isVolatile())
1694 return true; // Storing addr of GV.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001695 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001696 // Make sure we are calling the function, not passing the address.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001697 ImmutableCallSite CS(cast<Instruction>(UR));
1698 if (!CS.isCallee(&U))
Nick Lewyckyd73806a2008-11-03 03:49:14 +00001699 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001700 } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001701 if (LI->isVolatile())
1702 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001703 } else if (isa<BlockAddress>(UR)) {
Chris Lattner1a8b80e2009-11-01 06:11:53 +00001704 // blockaddress doesn't take the address of the function, it takes addr
1705 // of label.
Chris Lattner91dbae62004-12-11 05:15:59 +00001706 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001707 return true;
1708 }
Gabor Greif9027ffb2010-03-24 10:29:52 +00001709 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001710 return false;
1711}
1712
Davide Italiano15ff2d62016-07-20 20:17:13 +00001713static void findReturnsToZap(Function &F,
1714 SmallPtrSet<Function *, 32> &AddressTakenFunctions,
1715 SmallVector<ReturnInst *, 8> &ReturnsToZap) {
1716 // We can only do this if we know that nothing else can call the function.
1717 if (!F.hasLocalLinkage() || AddressTakenFunctions.count(&F))
1718 return;
1719
1720 for (BasicBlock &BB : F)
1721 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1722 if (!isa<UndefValue>(RI->getOperand(0)))
1723 ReturnsToZap.push_back(RI);
1724}
1725
Davide Italianof54f2f02016-05-05 21:05:36 +00001726static bool runIPSCCP(Module &M, const DataLayout &DL,
1727 const TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001728 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001729
Chris Lattner363226d2010-08-12 22:25:23 +00001730 // AddressTakenFunctions - This set keeps track of the address-taken functions
1731 // that are in the input. As IPSCCP runs through and simplifies code,
1732 // functions that were address taken can end up losing their
1733 // address-taken-ness. Because of this, we keep track of their addresses from
1734 // the first pass so we can use them for the later simplification pass.
1735 SmallPtrSet<Function*, 32> AddressTakenFunctions;
Jakub Staszak632a3552012-01-18 21:16:33 +00001736
Chris Lattnerb4394642004-12-10 08:02:06 +00001737 // Loop over all functions, marking arguments to those with their addresses
1738 // taken or that are external as overdefined.
1739 //
Davide Italianoe7c56c52016-05-14 20:59:09 +00001740 for (Function &F : M) {
1741 if (F.isDeclaration())
Chris Lattner47837c52009-11-02 06:34:04 +00001742 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001743
Sanjoy Das5ce32722016-04-08 00:48:30 +00001744 // If this is an exact definition of this function, then we can propagate
1745 // information about its result into callsites of it.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001746 if (F.hasExactDefinition())
1747 Solver.AddTrackedFunction(&F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001748
Chris Lattnerfb141812009-11-03 03:42:51 +00001749 // If this function only has direct calls that we can see, we can track its
1750 // arguments and return value aggressively, and can assume it is not called
1751 // unless we see evidence to the contrary.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001752 if (F.hasLocalLinkage()) {
1753 if (AddressIsTaken(&F))
1754 AddressTakenFunctions.insert(&F);
Chris Lattner363226d2010-08-12 22:25:23 +00001755 else {
Davide Italianoe7c56c52016-05-14 20:59:09 +00001756 Solver.AddArgumentTrackedFunction(&F);
Chris Lattner363226d2010-08-12 22:25:23 +00001757 continue;
1758 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001759 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001760
1761 // Assume the function is called.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001762 Solver.MarkBlockExecutable(&F.front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001763
Chris Lattnerfb141812009-11-03 03:42:51 +00001764 // Assume nothing about the incoming arguments.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001765 for (Argument &AI : F.args())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001766 Solver.markAnythingOverdefined(&AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001767 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001768
Chris Lattner91dbae62004-12-11 05:15:59 +00001769 // Loop over global variables. We inform the solver about any internal global
1770 // variables that do not have their 'addresses taken'. If they don't have
1771 // their addresses taken, we can propagate constants through them.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001772 for (GlobalVariable &G : M.globals())
1773 if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
1774 Solver.TrackValueOfGlobalVariable(&G);
Chris Lattner91dbae62004-12-11 05:15:59 +00001775
Chris Lattnerb4394642004-12-10 08:02:06 +00001776 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001777 bool ResolvedUndefs = true;
1778 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001779 Solver.Solve();
1780
David Greene389fc3b2010-01-05 01:27:15 +00001781 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001782 ResolvedUndefs = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001783 for (Function &F : M)
1784 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001785 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001786
1787 bool MadeChanges = false;
1788
1789 // Iterate over all of the instructions in the module, replacing them with
1790 // constants if we have found them to be of constant values.
1791 //
Chris Lattner65938fc2008-08-23 23:36:38 +00001792 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001793
Benjamin Kramer135f7352016-06-26 12:28:59 +00001794 for (Function &F : M) {
1795 if (F.isDeclaration())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001796 continue;
1797
Benjamin Kramer135f7352016-06-26 12:28:59 +00001798 if (Solver.isBlockExecutable(&F.front())) {
1799 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
1800 ++AI) {
Davide Italiano7dac0272016-07-14 02:51:41 +00001801 if (AI->use_empty())
1802 continue;
Davide Italiano6ed6d772016-07-14 01:27:29 +00001803 if (tryToReplaceWithConstant(Solver, &*AI))
1804 ++IPNumArgsElimed;
Chris Lattnere82b0872009-11-02 03:25:55 +00001805 }
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001806 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001807
Benjamin Kramer135f7352016-06-26 12:28:59 +00001808 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001809 if (!Solver.isBlockExecutable(&*BB)) {
David Majnemer88542a02016-01-24 06:26:47 +00001810 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001811
David Majnemer88542a02016-01-24 06:26:47 +00001812 ++NumDeadBlocks;
David Majnemere14e7bc2016-06-25 08:19:55 +00001813 NumInstRemoved +=
1814 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
David Majnemer88542a02016-01-24 06:26:47 +00001815
1816 MadeChanges = true;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001817
Benjamin Kramer135f7352016-06-26 12:28:59 +00001818 if (&*BB != &F.front())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001819 BlocksToErase.push_back(&*BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001820 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001821 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001822
Chris Lattnere405ed92009-11-02 02:47:51 +00001823 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001824 Instruction *Inst = &*BI++;
Davide Italiano7dac0272016-07-14 02:51:41 +00001825 if (Inst->getType()->isVoidTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001826 continue;
Davide Italiano296e9782016-07-13 23:20:04 +00001827 if (tryToReplaceInstWithConstant(
1828 Solver, Inst,
1829 !isa<CallInst>(Inst) &&
1830 !isa<TerminatorInst>(Inst) /* shouldEraseFromParent */)) {
1831 // Hey, we just changed something!
1832 MadeChanges = true;
1833 ++IPNumInstRemoved;
1834 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001835 }
1836 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001837
1838 // Now that all instructions in the function are constant folded, erase dead
1839 // blocks, because we can now use ConstantFoldTerminator to get rid of
1840 // in-edges.
1841 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1842 // If there are any PHI nodes in this successor, drop entries for BB now.
1843 BasicBlock *DeadBB = BlocksToErase[i];
Chandler Carruthcdf47882014-03-09 03:16:01 +00001844 for (Value::user_iterator UI = DeadBB->user_begin(),
1845 UE = DeadBB->user_end();
1846 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001847 // Grab the user and then increment the iterator early, as the user
1848 // will be deleted. Step past all adjacent uses from the same user.
1849 Instruction *I = dyn_cast<Instruction>(*UI);
1850 do { ++UI; } while (UI != UE && *UI == I);
1851
Dan Gohmand15302a2009-11-20 20:19:14 +00001852 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001853 if (!I) continue;
1854
Chris Lattnerbae4b642004-12-10 22:29:08 +00001855 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001856 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001857 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001858 // if this is a branch or switch on undef. Fold it manually as a
1859 // branch to the first successor.
Devang Patel45f1ae02008-11-21 01:52:59 +00001860#ifndef NDEBUG
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001861 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1862 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1863 "Branch should be foldable!");
1864 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1865 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1866 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001867 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001868 }
Devang Patel45f1ae02008-11-21 01:52:59 +00001869#endif
Jakub Staszak632a3552012-01-18 21:16:33 +00001870
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001871 // Make this an uncond branch to the first successor.
1872 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greife9ecc682008-04-06 20:25:17 +00001873 BranchInst::Create(TI->getSuccessor(0), TI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001874
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001875 // Remove entries in successor phi nodes to remove edges.
1876 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1877 TI->getSuccessor(i)->removePredecessor(TI->getParent());
Jakub Staszak632a3552012-01-18 21:16:33 +00001878
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001879 // Remove the old terminator.
1880 TI->eraseFromParent();
1881 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001882 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001883
Chris Lattnerbae4b642004-12-10 22:29:08 +00001884 // Finally, delete the basic block.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001885 F.getBasicBlockList().erase(DeadBB);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001886 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001887 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001888 }
Chris Lattner99e12952004-12-11 02:53:57 +00001889
1890 // If we inferred constant or undef return values for a function, we replaced
1891 // all call uses with the inferred value. This means we don't need to bother
1892 // actually returning anything from the function. Replace all return
1893 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001894 //
1895 // Do this in two stages: first identify the functions we should process, then
1896 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001897 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001898 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001899 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001900 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00001901
Devang Patela7a20752008-03-11 05:46:42 +00001902 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Benjamin Kramer135f7352016-06-26 12:28:59 +00001903 for (const auto &I : RV) {
1904 Function *F = I.first;
1905 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
Chris Lattnerfb141812009-11-03 03:42:51 +00001906 continue;
Davide Italiano15ff2d62016-07-20 20:17:13 +00001907 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1908 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001909
Davide Italiano15ff2d62016-07-20 20:17:13 +00001910 for (const auto &F : Solver.getMRVFunctionsTracked()) {
1911 assert(F->getReturnType()->isStructTy() &&
1912 "The return type should be a struct");
1913 StructType *STy = cast<StructType>(F->getReturnType());
1914 if (Solver.isStructLatticeConstant(F, STy))
1915 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001916 }
1917
1918 // Zap all returns which we've identified as zap to change.
1919 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1920 Function *F = ReturnsToZap[i]->getParent()->getParent();
1921 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00001922 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001923
Chad Rosierbb2a6da2012-03-28 00:35:33 +00001924 // If we inferred constant or undef values for globals variables, we can
1925 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001926 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1927 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001928 E = TG.end(); I != E; ++I) {
1929 GlobalVariable *GV = I->first;
1930 assert(!I->second.isOverdefined() &&
1931 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00001932 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00001933 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001934 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00001935 SI->eraseFromParent();
1936 }
1937 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001938 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001939 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001940
Chris Lattnerb4394642004-12-10 08:02:06 +00001941 return MadeChanges;
1942}
Davide Italianof54f2f02016-05-05 21:05:36 +00001943
Sean Silvafd03ac62016-08-09 00:28:38 +00001944PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
Davide Italianof54f2f02016-05-05 21:05:36 +00001945 const DataLayout &DL = M.getDataLayout();
1946 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
1947 if (!runIPSCCP(M, DL, &TLI))
1948 return PreservedAnalyses::all();
1949 return PreservedAnalyses::none();
1950}
1951
1952namespace {
1953//===--------------------------------------------------------------------===//
1954//
1955/// IPSCCP Class - This class implements interprocedural Sparse Conditional
1956/// Constant Propagation.
1957///
Davide Italiano46f249b2016-05-19 15:58:02 +00001958class IPSCCPLegacyPass : public ModulePass {
1959public:
Davide Italianof54f2f02016-05-05 21:05:36 +00001960 static char ID;
1961
1962 IPSCCPLegacyPass() : ModulePass(ID) {
1963 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1964 }
1965
1966 bool runOnModule(Module &M) override {
1967 if (skipModule(M))
1968 return false;
1969 const DataLayout &DL = M.getDataLayout();
1970 const TargetLibraryInfo *TLI =
1971 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1972 return runIPSCCP(M, DL, TLI);
1973 }
1974
1975 void getAnalysisUsage(AnalysisUsage &AU) const override {
1976 AU.addRequired<TargetLibraryInfoWrapperPass>();
1977 }
1978};
1979} // end anonymous namespace
1980
1981char IPSCCPLegacyPass::ID = 0;
1982INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
1983 "Interprocedural Sparse Conditional Constant Propagation",
1984 false, false)
1985INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1986INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
1987 "Interprocedural Sparse Conditional Constant Propagation",
1988 false, false)
1989
1990// createIPSCCPPass - This is the public interface to this file.
1991ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }