blob: 4822cf7cce0fee560a66da4c7cb1cc6e7ce99f2b [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
Xin Tong34888c02017-04-10 00:33:25 +0000143 /// getBlockAddress - If this is a constant with a BlockAddress value, return
144 /// it, otherwise return null.
145 BlockAddress *getBlockAddress() const {
146 if (isConstant())
147 return dyn_cast<BlockAddress>(getConstant());
148 return nullptr;
149 }
150
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000151 void markForcedConstant(Constant *V) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000152 assert(isUnknown() && "Can't force a defined value!");
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000153 Val.setInt(forcedconstant);
154 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000155 }
Chris Lattner347389d2001-06-27 23:38:11 +0000156};
Chris Lattnere405ed92009-11-02 02:47:51 +0000157} // end anonymous namespace.
158
159
160namespace {
Chris Lattner347389d2001-06-27 23:38:11 +0000161
Chris Lattner347389d2001-06-27 23:38:11 +0000162//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000163//
Chris Lattner074be1f2004-11-15 04:44:20 +0000164/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
165/// Constant Propagation.
166///
167class SCCPSolver : public InstVisitor<SCCPSolver> {
Mehdi Amini46a43552015-03-04 18:43:29 +0000168 const DataLayout &DL;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000169 const TargetLibraryInfo *TLI;
Nick Lewycky77cb8e62011-07-25 21:16:04 +0000170 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattnerf5484032009-11-02 05:55:40 +0000171 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000172
Chris Lattner156b8c72009-11-03 23:40:48 +0000173 /// StructValueState - This maintains ValueState for values that have
174 /// StructType, for example for formal arguments, calls, insertelement, etc.
175 ///
176 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
Jakub Staszak632a3552012-01-18 21:16:33 +0000177
Chris Lattner91dbae62004-12-11 05:15:59 +0000178 /// GlobalValue - If we are tracking any values for the contents of a global
179 /// variable, we keep a mapping from the constant accessor to the element of
180 /// the global, to the currently known value. If the value becomes
181 /// overdefined, it's entry is simply removed from this map.
Chris Lattner067d6072007-02-02 20:38:30 +0000182 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000183
Devang Patela7a20752008-03-11 05:46:42 +0000184 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000185 /// value out of a function, it will have an entry in this map, indicating
186 /// what the known return value for the function is.
Devang Patela7a20752008-03-11 05:46:42 +0000187 DenseMap<Function*, LatticeVal> TrackedRetVals;
188
189 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
190 /// that return multiple values.
Chris Lattner65938fc2008-08-23 23:36:38 +0000191 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak632a3552012-01-18 21:16:33 +0000192
Chris Lattner156b8c72009-11-03 23:40:48 +0000193 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
194 /// represented here for efficient lookup.
195 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattnerb4394642004-12-10 08:02:06 +0000196
Chris Lattner2c427232009-11-03 20:52:57 +0000197 /// TrackingIncomingArguments - This is the set of functions for whose
198 /// arguments we make optimistic assumptions about and try to prove as
199 /// constants.
Chris Lattnercde8de52009-11-03 19:24:51 +0000200 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000201
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000202 /// The reason for two worklists is that overdefined is the lowest state
203 /// on the lattice, and moving things to overdefined as fast as possible
204 /// makes SCCP converge much faster.
205 ///
206 /// By having a separate worklist, we accomplish this because everything
207 /// possibly overdefined will become overdefined at the soonest possible
208 /// point.
Chris Lattner65938fc2008-08-23 23:36:38 +0000209 SmallVector<Value*, 64> OverdefinedInstWorkList;
210 SmallVector<Value*, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000211
212
Chris Lattner65938fc2008-08-23 23:36:38 +0000213 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000214
215 /// KnownFeasibleEdges - Entries in this set are edges which have already had
216 /// PHI nodes retriggered.
Chris Lattner65938fc2008-08-23 23:36:38 +0000217 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
218 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000219public:
Mehdi Amini46a43552015-03-04 18:43:29 +0000220 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
221 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000222
Chris Lattner074be1f2004-11-15 04:44:20 +0000223 /// MarkBlockExecutable - This method can be used by clients to mark all of
224 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000225 ///
226 /// This returns true if the block was not considered live before.
227 bool MarkBlockExecutable(BasicBlock *BB) {
David Blaikie70573dc2014-11-19 07:49:26 +0000228 if (!BBExecutable.insert(BB).second)
229 return false;
Nick Lewycky5cd95382013-06-26 00:30:18 +0000230 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000231 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000232 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000233 }
234
Chris Lattner91dbae62004-12-11 05:15:59 +0000235 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000236 /// inform the SCCPSolver that it should track loads and stores to the
237 /// specified global variable if it can. This is only legal to call if
238 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000239 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000240 // We only track the contents of scalar globals.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000241 if (GV->getValueType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000242 LatticeVal &IV = TrackedGlobals[GV];
243 if (!isa<UndefValue>(GV->getInitializer()))
244 IV.markConstant(GV->getInitializer());
245 }
246 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000247
248 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
249 /// and out of the specified function (which cannot have its address taken),
250 /// this method must be called.
251 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000252 // Add an entry, F -> undef.
Davide Italianoe3bdd612016-12-01 08:36:12 +0000253 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000254 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000255 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000256 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
257 LatticeVal()));
258 } else
259 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000260 }
261
Chris Lattnercde8de52009-11-03 19:24:51 +0000262 void AddArgumentTrackedFunction(Function *F) {
263 TrackingIncomingArguments.insert(F);
264 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000265
Chris Lattner074be1f2004-11-15 04:44:20 +0000266 /// Solve - Solve for constants and executable blocks.
267 ///
268 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000269
Chris Lattner1847f6d2006-12-20 06:21:33 +0000270 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000271 /// that branches on undef values cannot reach any of their successors.
272 /// However, this is not a safe assumption. After we solve dataflow, this
273 /// method should be use to handle this. If this returns true, the solver
274 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000275 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000276
Chris Lattneradd44f32008-08-23 23:39:31 +0000277 bool isBlockExecutable(BasicBlock *BB) const {
278 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000279 }
280
Davide Italiano00802692016-07-12 19:54:19 +0000281 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
282 std::vector<LatticeVal> StructValues;
Davide Italianoe3bdd612016-12-01 08:36:12 +0000283 auto *STy = dyn_cast<StructType>(V->getType());
Davide Italiano00802692016-07-12 19:54:19 +0000284 assert(STy && "getStructLatticeValueFor() can be called only on structs");
285 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
286 auto I = StructValueState.find(std::make_pair(V, i));
287 assert(I != StructValueState.end() && "Value not in valuemap!");
288 StructValues.push_back(I->second);
289 }
290 return StructValues;
291 }
292
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +0000293 LatticeVal getLatticeValueFor(Value *V) const {
294 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
295 assert(I != ValueState.end() && "V is not in valuemap!");
296 return I->second;
Chris Lattner074be1f2004-11-15 04:44:20 +0000297 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000298
Devang Patela7a20752008-03-11 05:46:42 +0000299 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner99e12952004-12-11 02:53:57 +0000300 ///
Devang Patela7a20752008-03-11 05:46:42 +0000301 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
302 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000303 }
304
Chris Lattner91dbae62004-12-11 05:15:59 +0000305 /// getTrackedGlobals - Get and return the set of inferred initializers for
306 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000307 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000308 return TrackedGlobals;
309 }
310
Davide Italiano15ff2d62016-07-20 20:17:13 +0000311 /// getMRVFunctionsTracked - Get the set of functions which return multiple
312 /// values tracked by the pass.
313 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
314 return MRVFunctionsTracked;
315 }
316
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000317 /// markOverdefined - Mark the specified value overdefined. This
Chris Lattner156b8c72009-11-03 23:40:48 +0000318 /// works with both scalars and structs.
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000319 void markOverdefined(Value *V) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000320 if (auto *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000321 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
322 markOverdefined(getStructValueState(V, i), V);
323 else
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000324 markOverdefined(ValueState[V], V);
Chris Lattner156b8c72009-11-03 23:40:48 +0000325 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000326
Davide Italiano15ff2d62016-07-20 20:17:13 +0000327 // isStructLatticeConstant - Return true if all the lattice values
328 // corresponding to elements of the structure are not overdefined,
329 // false otherwise.
330 bool isStructLatticeConstant(Function *F, StructType *STy) {
331 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
332 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
333 assert(It != TrackedMultipleRetVals.end());
334 LatticeVal LV = It->second;
335 if (LV.isOverdefined())
336 return false;
337 }
338 return true;
339 }
340
Chris Lattner347389d2001-06-27 23:38:11 +0000341private:
Davide Italiano0a1476c2016-12-11 21:19:03 +0000342 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
Davide Italiano390b7ea2016-07-13 19:33:25 +0000343 void pushToWorkList(LatticeVal &IV, Value *V) {
344 if (IV.isOverdefined())
345 return OverdefinedInstWorkList.push_back(V);
346 InstWorkList.push_back(V);
347 }
348
Chris Lattnerd79334d2004-07-15 23:36:43 +0000349 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000350 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000351 // the users of the instruction are updated later.
352 //
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000353 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
354 if (!IV.markConstant(C)) return;
David Greene389fc3b2010-01-05 01:27:15 +0000355 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000356 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000357 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000358
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000359 void markConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000360 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerb4394642004-12-10 08:02:06 +0000361 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000362 }
363
Chris Lattnerf5484032009-11-02 05:55:40 +0000364 void markForcedConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000365 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000366 LatticeVal &IV = ValueState[V];
367 IV.markForcedConstant(C);
David Greene389fc3b2010-01-05 01:27:15 +0000368 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000369 pushToWorkList(IV, V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000370 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000371
372
Chris Lattnerd79334d2004-07-15 23:36:43 +0000373 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000374 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000375 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000376 void markOverdefined(LatticeVal &IV, Value *V) {
377 if (!IV.markOverdefined()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000378
David Greene389fc3b2010-01-05 01:27:15 +0000379 DEBUG(dbgs() << "markOverdefined: ";
Davide Italianoe3bdd612016-12-01 08:36:12 +0000380 if (auto *F = dyn_cast<Function>(V))
David Greene389fc3b2010-01-05 01:27:15 +0000381 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000382 else
David Greene389fc3b2010-01-05 01:27:15 +0000383 dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000384 // Only instructions go on the work list
Davide Italiano0a1476c2016-12-11 21:19:03 +0000385 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000386 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000387
Chris Lattnerf5484032009-11-02 05:55:40 +0000388 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000389 if (IV.isOverdefined() || MergeWithV.isUnknown())
Chris Lattnerb4394642004-12-10 08:02:06 +0000390 return; // Noop.
391 if (MergeWithV.isOverdefined())
Davide Italiano21850012016-07-13 19:23:30 +0000392 return markOverdefined(IV, V);
393 if (IV.isUnknown())
394 return markConstant(IV, V, MergeWithV.getConstant());
395 if (IV.getConstant() != MergeWithV.getConstant())
396 return markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000397 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000398
Chris Lattnerf5484032009-11-02 05:55:40 +0000399 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Davide Italiano63266b62016-07-19 18:31:07 +0000400 assert(!V->getType()->isStructTy() &&
401 "non-structs should use markConstant");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000402 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000403 }
404
Chris Lattner347389d2001-06-27 23:38:11 +0000405
Chris Lattnerf5484032009-11-02 05:55:40 +0000406 /// getValueState - Return the LatticeVal object that corresponds to the
407 /// value. This function handles the case when the value hasn't been seen yet
408 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000409 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000410 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000411
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000412 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
413 ValueState.insert(std::make_pair(V, LatticeVal()));
414 LatticeVal &LV = I.first->second;
415
416 if (!I.second)
417 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000418
Davide Italianoe3bdd612016-12-01 08:36:12 +0000419 if (auto *C = dyn_cast<Constant>(V)) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000420 // Undef values remain unknown.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000421 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000422 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000423 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000424
Chris Lattnera3c39d32009-11-02 02:33:50 +0000425 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000426 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000427 }
428
Chris Lattner156b8c72009-11-03 23:40:48 +0000429 /// getStructValueState - Return the LatticeVal object that corresponds to the
430 /// value/field pair. This function handles the case when the value hasn't
431 /// been seen yet by properly seeding constants etc.
432 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000433 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000434 assert(i < cast<StructType>(V->getType())->getNumElements() &&
435 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000436
437 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
438 bool> I = StructValueState.insert(
439 std::make_pair(std::make_pair(V, i), LatticeVal()));
440 LatticeVal &LV = I.first->second;
441
442 if (!I.second)
443 return LV; // Common case, already in the map.
444
Davide Italianoe3bdd612016-12-01 08:36:12 +0000445 if (auto *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000446 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000447
Craig Topperf40110f2014-04-25 05:29:35 +0000448 if (!Elt)
Chris Lattner156b8c72009-11-03 23:40:48 +0000449 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000450 else if (isa<UndefValue>(Elt))
Davide Italiano0f03ce02016-07-10 00:35:15 +0000451 ; // Undef values remain unknown.
Chris Lattnerfa775002012-01-26 02:32:04 +0000452 else
453 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000454 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000455
Chris Lattner156b8c72009-11-03 23:40:48 +0000456 // All others are underdefined by default.
457 return LV;
458 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000459
Chris Lattner156b8c72009-11-03 23:40:48 +0000460
Chris Lattnerf5484032009-11-02 05:55:40 +0000461 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
462 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000463 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
464 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
465 return; // This edge is already known to be executable!
466
Chris Lattner809aee22009-11-02 06:11:23 +0000467 if (!MarkBlockExecutable(Dest)) {
468 // If the destination is already executable, we just made an *edge*
469 // feasible that wasn't before. Revisit the PHI nodes in the block
470 // because they have potentially new operands.
David Greene389fc3b2010-01-05 01:27:15 +0000471 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Nick Lewycky5cd95382013-06-26 00:30:18 +0000472 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000473
Chris Lattner809aee22009-11-02 06:11:23 +0000474 PHINode *PN;
475 for (BasicBlock::iterator I = Dest->begin();
476 (PN = dyn_cast<PHINode>(I)); ++I)
477 visitPHINode(*PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000478 }
Chris Lattner347389d2001-06-27 23:38:11 +0000479 }
480
Chris Lattner074be1f2004-11-15 04:44:20 +0000481 // getFeasibleSuccessors - Return a vector of booleans to indicate which
482 // successors are reachable from a given terminator instruction.
483 //
Craig Topperb94011f2013-07-14 04:42:23 +0000484 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000485
486 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000487 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000488 //
489 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
490
491 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000492 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000493 // information, we need to update the specified user of this instruction.
494 //
Chris Lattnerfb141812009-11-03 03:42:51 +0000495 void OperandChangedState(Instruction *I) {
496 if (BBExecutable.count(I->getParent())) // Inst is executable?
497 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000498 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000499
Chris Lattner074be1f2004-11-15 04:44:20 +0000500private:
501 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000502
Chris Lattnera3c39d32009-11-02 02:33:50 +0000503 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000504 // operand made a transition, or the instruction is newly executable. Change
505 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000506 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000507
508 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000509 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000510 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000511
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000512 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000513 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000514 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000515 void visitCmpInst(CmpInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000516 void visitExtractValueInst(ExtractValueInst &EVI);
517 void visitInsertValueInst(InsertValueInst &IVI);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000518 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000519 markOverdefined(&CPI);
David Majnemereb518bd2015-08-04 08:21:40 +0000520 visitTerminatorInst(CPI);
521 }
Chris Lattner6e560792002-04-18 15:13:15 +0000522
Chris Lattnera3c39d32009-11-02 02:33:50 +0000523 // Instructions that cannot be folded away.
Chris Lattnerf5484032009-11-02 05:55:40 +0000524 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000525 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000526 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandeze2971492009-10-24 04:23:03 +0000527 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000528 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000529 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000530 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000531 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000532 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000533 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000534 void visitCallSite (CallSite CS);
Davide Italianoa7f5e882016-05-04 23:27:13 +0000535 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
536 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
537 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000538 void visitInstruction(Instruction &I) {
Davide Italiano0b1190a2017-06-16 20:27:17 +0000539 // All the instructions we don't do any special handling for just
540 // go to overdefined.
Davide Italiano463bebc2016-12-13 05:56:04 +0000541 DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
Davide Italiano0b1190a2017-06-16 20:27:17 +0000542 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000543 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000544};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000545
Duncan Sands2be91fc2007-07-20 08:56:21 +0000546} // end anonymous namespace
547
548
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000549// getFeasibleSuccessors - Return a vector of booleans to indicate which
550// successors are reachable from a given terminator instruction.
551//
Chris Lattner074be1f2004-11-15 04:44:20 +0000552void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000553 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000554 Succs.resize(TI.getNumSuccessors());
Davide Italianoe3bdd612016-12-01 08:36:12 +0000555 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000556 if (BI->isUnconditional()) {
557 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000558 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000559 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000560
Chris Lattnerf5484032009-11-02 05:55:40 +0000561 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000562 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000563 if (!CI) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000564 // Overdefined condition variables, and branches on unfoldable constant
565 // conditions, mean the branch could go either way.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000566 if (!BCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000567 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000568 return;
569 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000570
Chris Lattner6df5cec2009-11-02 02:30:06 +0000571 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000572 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000573 return;
574 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000575
David Majnemer654e1302015-07-31 17:58:14 +0000576 // Unwinding instructions successors are always executable.
577 if (TI.isExceptional()) {
578 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattneree8b9512009-10-29 01:21:20 +0000579 return;
580 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000581
Davide Italianoe3bdd612016-12-01 08:36:12 +0000582 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000583 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000584 Succs[0] = true;
585 return;
586 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000587 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000588 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000589
Davide Italiano0f03ce02016-07-10 00:35:15 +0000590 if (!CI) { // Overdefined or unknown condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000591 // All destinations are executable!
Davide Italiano0f03ce02016-07-10 00:35:15 +0000592 if (!SCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000593 Succs.assign(TI.getNumSuccessors(), true);
594 return;
595 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000596
Chandler Carruth927d8e62017-04-12 07:27:28 +0000597 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000598 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000599 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000600
Xin Tong34888c02017-04-10 00:33:25 +0000601 // In case of indirect branch and its address is a blockaddress, we mark
602 // the target as executable.
603 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
604 // Casts are folded by visitCastInst.
605 LatticeVal IBRValue = getValueState(IBR->getAddress());
606 BlockAddress *Addr = IBRValue.getBlockAddress();
607 if (!Addr) { // Overdefined or unknown condition?
608 // All destinations are executable!
609 if (!IBRValue.isUnknown())
610 Succs.assign(TI.getNumSuccessors(), true);
611 return;
612 }
613
614 BasicBlock* T = Addr->getBasicBlock();
615 assert(Addr->getFunction() == T->getParent() &&
616 "Block address of a different function ?");
617 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
618 // This is the target.
619 if (IBR->getDestination(i) == T) {
620 Succs[i] = true;
621 return;
622 }
623 }
624
625 // If we didn't find our destination in the IBR successor list, then we
626 // have undefined behavior. Its ok to assume no successor is executable.
Chris Lattneree8b9512009-10-29 01:21:20 +0000627 return;
628 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000629
Davide Italiano33af6fe2016-12-01 08:48:14 +0000630 DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
Chris Lattneree8b9512009-10-29 01:21:20 +0000631 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000632}
633
634
Chris Lattner13b52e72002-05-02 21:18:01 +0000635// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000636// block to the 'To' basic block is currently feasible.
Chris Lattner13b52e72002-05-02 21:18:01 +0000637//
Chris Lattner074be1f2004-11-15 04:44:20 +0000638bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000639 assert(BBExecutable.count(To) && "Dest should always be alive!");
640
641 // Make sure the source basic block is executable!!
642 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000643
Chris Lattnera3c39d32009-11-02 02:33:50 +0000644 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000645 TerminatorInst *TI = From->getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +0000646 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000647 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000648 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000649
Chris Lattnerf5484032009-11-02 05:55:40 +0000650 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000651
Chris Lattner6df5cec2009-11-02 02:30:06 +0000652 // Overdefined condition variables mean the branch could go either way,
653 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000654 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000655 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000656 return !BCValue.isUnknown();
Jakub Staszak632a3552012-01-18 21:16:33 +0000657
Chris Lattner6df5cec2009-11-02 02:30:06 +0000658 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000659 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000660 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000661
David Majnemer654e1302015-07-31 17:58:14 +0000662 // Unwinding instructions successors are always executable.
663 if (TI->isExceptional())
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000664 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000665
Davide Italianoe3bdd612016-12-01 08:36:12 +0000666 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000667 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000668 return true;
669
Chris Lattnerf5484032009-11-02 05:55:40 +0000670 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000671 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000672
Craig Topperf40110f2014-04-25 05:29:35 +0000673 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000674 return !SCValue.isUnknown();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000675
Chandler Carruth927d8e62017-04-12 07:27:28 +0000676 return SI->findCaseValue(CI)->getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000677 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000678
Xin Tong34888c02017-04-10 00:33:25 +0000679 // In case of indirect branch and its address is a blockaddress, we mark
680 // the target as executable.
681 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
682 LatticeVal IBRValue = getValueState(IBR->getAddress());
683 BlockAddress *Addr = IBRValue.getBlockAddress();
684
685 if (!Addr)
686 return !IBRValue.isUnknown();
687
688 // At this point, the indirectbr is branching on a blockaddress.
689 return Addr->getBasicBlock() == To;
690 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000691
Davide Italiano33af6fe2016-12-01 08:48:14 +0000692 DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
Davide Italianodd04fee2015-11-25 21:03:36 +0000693 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattner13b52e72002-05-02 21:18:01 +0000694}
Chris Lattner347389d2001-06-27 23:38:11 +0000695
Chris Lattnera3c39d32009-11-02 02:33:50 +0000696// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000697// operand made a transition, or the instruction is newly executable. Change
698// the value type of I to reflect these changes if appropriate. This method
699// makes sure to do the following actions:
700//
701// 1. If a phi node merges two constants in, and has conflicting value coming
702// from different branches, or if the PHI node merges in an overdefined
703// value, then the PHI node becomes overdefined.
704// 2. If a phi node merges only constants in, and they all agree on value, the
705// PHI node becomes a constant value equal to that.
706// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
707// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
708// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
709// 6. If a conditional branch has a value that is constant, make the selected
710// destination executable
711// 7. If a conditional branch has a value that is overdefined, make all
712// successors executable.
713//
Chris Lattner074be1f2004-11-15 04:44:20 +0000714void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000715 // If this PN returns a struct, just mark the result overdefined.
716 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000717 if (PN.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000718 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000719
Eli Friedman0a309292011-11-11 01:16:15 +0000720 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000721 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000722
Chris Lattner7a7b1142004-03-16 19:49:59 +0000723 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
724 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000725 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000726 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000727
Chris Lattner6e560792002-04-18 15:13:15 +0000728 // Look at all of the executable operands of the PHI node. If any of them
729 // are overdefined, the PHI becomes overdefined as well. If they are all
730 // constant, and they agree with each other, the PHI becomes the identical
731 // constant. If they are constant and don't agree, the PHI is overdefined.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000732 // If there are no executable operands, the PHI remains unknown.
Chris Lattner6e560792002-04-18 15:13:15 +0000733 //
Craig Topperf40110f2014-04-25 05:29:35 +0000734 Constant *OperandVal = nullptr;
Chris Lattnercccc5c72003-04-25 02:50:03 +0000735 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000736 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +0000737 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000738
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000739 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
740 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000741
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000742 if (IV.isOverdefined()) // PHI node becomes overdefined!
743 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000744
Craig Topperf40110f2014-04-25 05:29:35 +0000745 if (!OperandVal) { // Grab the first value.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000746 OperandVal = IV.getConstant();
747 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000748 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000749
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000750 // There is already a reachable operand. If we conflict with it,
751 // then the PHI node becomes overdefined. If we agree with it, we
752 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000753
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000754 // Check to see if there are two different constants merging, if so, the PHI
755 // node is overdefined.
756 if (IV.getConstant() != OperandVal)
757 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000758 }
759
Chris Lattner6e560792002-04-18 15:13:15 +0000760 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000761 // arguments that agree with each other(and OperandVal is the constant) or
762 // OperandVal is null because there are no defined incoming arguments. If
Davide Italiano0f03ce02016-07-10 00:35:15 +0000763 // this is the case, the PHI remains unknown.
Chris Lattner347389d2001-06-27 23:38:11 +0000764 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000765 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000766 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000767}
768
Chris Lattnerb4394642004-12-10 08:02:06 +0000769void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000770 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000771
Chris Lattnerb4394642004-12-10 08:02:06 +0000772 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000773 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000774
Devang Patela7a20752008-03-11 05:46:42 +0000775 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000776 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000777 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000778 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000779 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000780 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000781 return;
782 }
783 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000784
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000785 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000786 if (!TrackedMultipleRetVals.empty()) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000787 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000788 if (MRVFunctionsTracked.count(F))
789 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
790 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
791 getStructValueState(ResultOp, i));
Jakub Staszak632a3552012-01-18 21:16:33 +0000792
Chris Lattnerb4394642004-12-10 08:02:06 +0000793 }
794}
795
Chris Lattner074be1f2004-11-15 04:44:20 +0000796void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000797 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000798 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000799
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000800 BasicBlock *BB = TI.getParent();
801
Chris Lattnera3c39d32009-11-02 02:33:50 +0000802 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000803 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000804 if (SuccFeasible[i])
805 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000806}
807
Chris Lattner074be1f2004-11-15 04:44:20 +0000808void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000809 LatticeVal OpSt = getValueState(I.getOperand(0));
810 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000811 markOverdefined(&I);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000812 else if (OpSt.isConstant()) {
Davide Italianod555bde2016-07-08 19:13:40 +0000813 // Fold the constant as we build.
Davide Italiano63c4ce82016-07-11 18:21:29 +0000814 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
815 I.getType(), DL);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000816 if (isa<UndefValue>(C))
817 return;
818 // Propagate constant value
819 markConstant(&I, C);
820 }
Chris Lattner6e560792002-04-18 15:13:15 +0000821}
822
Chris Lattner156b8c72009-11-03 23:40:48 +0000823
Dan Gohman041f9d02008-06-20 01:15:44 +0000824void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000825 // If this returns a struct, mark all elements over defined, we don't track
826 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000827 if (EVI.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000828 return markOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000829
Chris Lattner156b8c72009-11-03 23:40:48 +0000830 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000831 if (EVI.getNumIndices() != 1)
832 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000833
Chris Lattner156b8c72009-11-03 23:40:48 +0000834 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000835 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000836 unsigned i = *EVI.idx_begin();
837 LatticeVal EltVal = getStructValueState(AggVal, i);
838 mergeInValue(getValueState(&EVI), &EVI, EltVal);
839 } else {
840 // Otherwise, must be extracting from an array.
841 return markOverdefined(&EVI);
842 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000843}
844
845void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000846 auto *STy = dyn_cast<StructType>(IVI.getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000847 if (!STy)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000848 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000849
Chris Lattner156b8c72009-11-03 23:40:48 +0000850 // If this has more than one index, we can't handle it, drive all results to
851 // undef.
852 if (IVI.getNumIndices() != 1)
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000853 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000854
Chris Lattner156b8c72009-11-03 23:40:48 +0000855 Value *Aggr = IVI.getAggregateOperand();
856 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000857
Chris Lattner156b8c72009-11-03 23:40:48 +0000858 // Compute the result based on what we're inserting.
859 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
860 // This passes through all values that aren't the inserted element.
861 if (i != Idx) {
862 LatticeVal EltVal = getStructValueState(Aggr, i);
863 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
864 continue;
865 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000866
Chris Lattner156b8c72009-11-03 23:40:48 +0000867 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000868 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000869 // We don't track structs in structs.
870 markOverdefined(getStructValueState(&IVI, i), &IVI);
871 else {
872 LatticeVal InVal = getValueState(Val);
873 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
874 }
875 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000876}
877
Chris Lattner074be1f2004-11-15 04:44:20 +0000878void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000879 // If this select returns a struct, just mark the result overdefined.
880 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000881 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000882 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000883
Chris Lattnerf5484032009-11-02 05:55:40 +0000884 LatticeVal CondValue = getValueState(I.getCondition());
Davide Italiano0f03ce02016-07-10 00:35:15 +0000885 if (CondValue.isUnknown())
Chris Lattner06a0ed12006-02-08 02:38:11 +0000886 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000887
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000888 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000889 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
890 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000891 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000892 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000893
Chris Lattner06a0ed12006-02-08 02:38:11 +0000894 // Otherwise, the condition is overdefined or a constant we can't evaluate.
895 // See if we can produce something better than overdefined based on the T/F
896 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000897 LatticeVal TVal = getValueState(I.getTrueValue());
898 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000899
Chris Lattner06a0ed12006-02-08 02:38:11 +0000900 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000901 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000902 TVal.getConstant() == FVal.getConstant())
903 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000904
Davide Italiano0f03ce02016-07-10 00:35:15 +0000905 if (TVal.isUnknown()) // select ?, undef, X -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000906 return mergeInValue(&I, FVal);
Davide Italiano0f03ce02016-07-10 00:35:15 +0000907 if (FVal.isUnknown()) // select ?, X, undef -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000908 return mergeInValue(&I, TVal);
909 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000910}
911
Chris Lattnerf5484032009-11-02 05:55:40 +0000912// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000913void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000914 LatticeVal V1State = getValueState(I.getOperand(0));
915 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000916
Chris Lattner4f031622004-11-15 05:03:30 +0000917 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000918 if (IV.isOverdefined()) return;
919
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000920 if (V1State.isConstant() && V2State.isConstant()) {
921 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
922 V2State.getConstant());
923 // X op Y -> undef.
924 if (isa<UndefValue>(C))
925 return;
926 return markConstant(IV, &I, C);
927 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000928
Chris Lattnerf5484032009-11-02 05:55:40 +0000929 // If something is undef, wait for it to resolve.
930 if (!V1State.isOverdefined() && !V2State.isOverdefined())
931 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000932
Chris Lattnerf5484032009-11-02 05:55:40 +0000933 // Otherwise, one of our operands is overdefined. Try to produce something
934 // better than overdefined with some tricks.
Davide Italiano6c2c3e02017-01-19 23:07:51 +0000935 // If this is 0 / Y, it doesn't matter that the second operand is
936 // overdefined, and we can replace it with zero.
937 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
938 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
939 return markConstant(IV, &I, V1State.getConstant());
940
Davide Italiano93c6c182017-01-19 21:07:42 +0000941 // If this is:
942 // -> AND/MUL with 0
943 // -> OR with -1
944 // it doesn't matter that the other operand is overdefined.
Davide Italiano824d6952016-12-09 03:08:42 +0000945 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
946 I.getOpcode() == Instruction::Or) {
Craig Topperf40110f2014-04-25 05:29:35 +0000947 LatticeVal *NonOverdefVal = nullptr;
Chris Lattnerf5484032009-11-02 05:55:40 +0000948 if (!V1State.isOverdefined())
949 NonOverdefVal = &V1State;
950 else if (!V2State.isOverdefined())
951 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +0000952
Chris Lattnerf5484032009-11-02 05:55:40 +0000953 if (NonOverdefVal) {
Davide Italianoe7ffae92016-11-22 22:11:25 +0000954 if (NonOverdefVal->isUnknown())
Chris Lattnerf5484032009-11-02 05:55:40 +0000955 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000956
Davide Italiano824d6952016-12-09 03:08:42 +0000957 if (I.getOpcode() == Instruction::And ||
958 I.getOpcode() == Instruction::Mul) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000959 // X and 0 = 0
Davide Italiano824d6952016-12-09 03:08:42 +0000960 // X * 0 = 0
Chris Lattnerf5484032009-11-02 05:55:40 +0000961 if (NonOverdefVal->getConstant()->isNullValue())
962 return markConstant(IV, &I, NonOverdefVal->getConstant());
963 } else {
Davide Italianoe7ffae92016-11-22 22:11:25 +0000964 // X or -1 = -1
Chris Lattnerf5484032009-11-02 05:55:40 +0000965 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
Craig Topper79ab6432017-07-06 18:39:47 +0000966 if (CI->isMinusOne())
Chris Lattnerf5484032009-11-02 05:55:40 +0000967 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +0000968 }
969 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000970 }
Chris Lattnercbc01612004-12-11 23:15:19 +0000971
972
Chris Lattnerf5484032009-11-02 05:55:40 +0000973 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000974}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000975
Chris Lattnera3c39d32009-11-02 02:33:50 +0000976// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000977void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000978 LatticeVal V1State = getValueState(I.getOperand(0));
979 LatticeVal V2State = getValueState(I.getOperand(1));
980
Reid Spencer266e42b2006-12-23 06:05:41 +0000981 LatticeVal &IV = ValueState[&I];
982 if (IV.isOverdefined()) return;
983
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000984 if (V1State.isConstant() && V2State.isConstant()) {
985 Constant *C = ConstantExpr::getCompare(
986 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
987 if (isa<UndefValue>(C))
988 return;
989 return markConstant(IV, &I, C);
990 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000991
Davide Italiano0f03ce02016-07-10 00:35:15 +0000992 // If operands are still unknown, wait for it to resolve.
Chris Lattnerf5484032009-11-02 05:55:40 +0000993 if (!V1State.isOverdefined() && !V2State.isOverdefined())
994 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000995
Chris Lattnerf5484032009-11-02 05:55:40 +0000996 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000997}
998
Chris Lattnera3c39d32009-11-02 02:33:50 +0000999// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001000// can turn this into a getelementptr ConstantExpr.
1001//
Chris Lattner074be1f2004-11-15 04:44:20 +00001002void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001003 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001004
Chris Lattner0e7ec672007-02-02 20:51:48 +00001005 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001006 Operands.reserve(I.getNumOperands());
1007
1008 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001009 LatticeVal State = getValueState(I.getOperand(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001010 if (State.isUnknown())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001011 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001012
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001013 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001014 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001015
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001016 assert(State.isConstant() && "Unknown state!");
1017 Operands.push_back(State.getConstant());
1018 }
1019
1020 Constant *Ptr = Operands[0];
Craig Toppere1d12942014-08-27 05:25:25 +00001021 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001022 Constant *C =
1023 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1024 if (isa<UndefValue>(C))
1025 return;
1026 markConstant(&I, C);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001027}
Brian Gaeke960707c2003-11-11 22:41:34 +00001028
Chris Lattnerf5484032009-11-02 05:55:40 +00001029void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001030 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001031 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001032 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001033
Chris Lattner91dbae62004-12-11 05:15:59 +00001034 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1035 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001036
Chris Lattner91dbae62004-12-11 05:15:59 +00001037 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001038 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001039 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1040
Chris Lattnerf5484032009-11-02 05:55:40 +00001041 // Get the value we are storing into the global, then merge it.
1042 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001043 if (I->second.isOverdefined())
1044 TrackedGlobals.erase(I); // No need to keep tracking this!
1045}
1046
1047
Chris Lattner49f74522004-01-12 04:29:41 +00001048// Handle load instructions. If the operand is a constant pointer to a constant
1049// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001050void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001051 // If this load is of a struct, just mark the result overdefined.
David Majnemerf3b99dd2016-01-07 19:30:13 +00001052 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001053 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001054
Chris Lattnerf5484032009-11-02 05:55:40 +00001055 LatticeVal PtrVal = getValueState(I.getOperand(0));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001056 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001057
Chris Lattner4f031622004-11-15 05:03:30 +00001058 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001059 if (IV.isOverdefined()) return;
1060
Chris Lattnerf5484032009-11-02 05:55:40 +00001061 if (!PtrVal.isConstant() || I.isVolatile())
1062 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001063
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001064 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001065
David Majnemerbae94572016-01-07 19:25:39 +00001066 // load null is undefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001067 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
David Majnemerbae94572016-01-07 19:25:39 +00001068 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001069
Chris Lattnerf5484032009-11-02 05:55:40 +00001070 // Transform load (constant global) into the value loaded.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001071 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001072 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001073 // If we are tracking this global, merge in the known value for it.
1074 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1075 TrackedGlobals.find(GV);
1076 if (It != TrackedGlobals.end()) {
1077 mergeInValue(IV, &I, It->second);
1078 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001079 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001080 }
Chris Lattner49f74522004-01-12 04:29:41 +00001081 }
1082
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001083 // Transform load from a constant into a constant if possible.
Eduard Burtescu14239212016-01-22 01:17:26 +00001084 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001085 if (isa<UndefValue>(C))
1086 return;
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001087 return markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001088 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001089
Chris Lattner49f74522004-01-12 04:29:41 +00001090 // Otherwise we cannot say for certain what value this load will produce.
1091 // Bail out.
1092 markOverdefined(IV, &I);
1093}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001094
Chris Lattnerb4394642004-12-10 08:02:06 +00001095void SCCPSolver::visitCallSite(CallSite CS) {
1096 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001097 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001098
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001099 // The common case is that we aren't tracking the callee, either because we
1100 // are not doing interprocedural analysis or the callee is indirect, or is
1101 // external. Handle these cases first.
Craig Topperf40110f2014-04-25 05:29:35 +00001102 if (!F || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001103CallOverdefined:
1104 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001105 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001106
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001107 // Otherwise, if we have a single return value case, and if the function is
1108 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001109 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Andrew Kaylor647025f2017-06-09 23:18:11 +00001110 canConstantFoldCallTo(CS, F)) {
Jakub Staszak632a3552012-01-18 21:16:33 +00001111
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001112 SmallVector<Constant*, 8> Operands;
1113 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1114 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001115 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001116
Davide Italiano0f03ce02016-07-10 00:35:15 +00001117 if (State.isUnknown())
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001118 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001119 if (State.isOverdefined())
1120 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001121 assert(State.isConstant() && "Unknown state!");
1122 Operands.push_back(State.getConstant());
1123 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001124
David Majnemer2098b86f2014-11-07 08:54:19 +00001125 if (getValueState(I).isOverdefined())
1126 return;
1127
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001128 // If we can constant fold this, mark the result of the call as a
1129 // constant.
Andrew Kaylor647025f2017-06-09 23:18:11 +00001130 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001131 // call -> undef.
1132 if (isa<UndefValue>(C))
1133 return;
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001134 return markConstant(I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001135 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001136 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001137
1138 // Otherwise, we don't know anything about this call, mark it overdefined.
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001139 return markOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001140 }
1141
Chris Lattnercde8de52009-11-03 19:24:51 +00001142 // If this is a local function that doesn't have its address taken, mark its
1143 // entry block executable and merge in the actual arguments to the call into
1144 // the formal arguments of the function.
1145 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001146 MarkBlockExecutable(&F->front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001147
Chris Lattnercde8de52009-11-03 19:24:51 +00001148 // Propagate information from this call site into the callee.
1149 CallSite::arg_iterator CAI = CS.arg_begin();
1150 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1151 AI != E; ++AI, ++CAI) {
1152 // If this argument is byval, and if the function is not readonly, there
1153 // will be an implicit copy formed of the input aggregate.
1154 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001155 markOverdefined(&*AI);
Chris Lattnercde8de52009-11-03 19:24:51 +00001156 continue;
1157 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001158
Davide Italianoe3bdd612016-12-01 08:36:12 +00001159 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001160 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1161 LatticeVal CallArg = getStructValueState(*CAI, i);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001162 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
Chris Lattner762b56f2009-11-04 18:57:42 +00001163 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001164 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001165 mergeInValue(&*AI, getValueState(*CAI));
Chris Lattner156b8c72009-11-03 23:40:48 +00001166 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001167 }
1168 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001169
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001170 // If this is a single/zero retval case, see if we're tracking the function.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001171 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001172 if (!MRVFunctionsTracked.count(F))
1173 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001174
Chris Lattner156b8c72009-11-03 23:40:48 +00001175 // If we are tracking this callee, propagate the result of the function
1176 // into this call site.
1177 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001178 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001179 TrackedMultipleRetVals[std::make_pair(F, i)]);
1180 } else {
1181 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1182 if (TFRVI == TrackedRetVals.end())
1183 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001184
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001185 // If so, propagate the return value of the callee into this call result.
1186 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001187 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001188}
Chris Lattner074be1f2004-11-15 04:44:20 +00001189
Chris Lattner074be1f2004-11-15 04:44:20 +00001190void SCCPSolver::Solve() {
1191 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001192 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001193 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001194 // Process the overdefined instruction's work list first, which drives other
1195 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001196 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001197 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001198
David Greene389fc3b2010-01-05 01:27:15 +00001199 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001200
Chris Lattner074be1f2004-11-15 04:44:20 +00001201 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001202 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001203 //
1204 // Anything on this worklist that is overdefined need not be visited
1205 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001206 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001207 //
Chandler Carruthcdf47882014-03-09 03:16:01 +00001208 for (User *U : I->users())
Davide Italianoe3bdd612016-12-01 08:36:12 +00001209 if (auto *UI = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +00001210 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001211 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001212
Chris Lattnera3c39d32009-11-02 02:33:50 +00001213 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001214 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001215 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001216
David Greene389fc3b2010-01-05 01:27:15 +00001217 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001218
Chris Lattnerf5484032009-11-02 05:55:40 +00001219 // "I" got into the work list because it made the transition from undef to
1220 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001221 //
1222 // Anything on this worklist that is overdefined need not be visited
1223 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001224 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001225 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001226 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001227 for (User *U : I->users())
Davide Italianoe3bdd612016-12-01 08:36:12 +00001228 if (auto *UI = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +00001229 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001230 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001231
Chris Lattnera3c39d32009-11-02 02:33:50 +00001232 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001233 while (!BBWorkList.empty()) {
1234 BasicBlock *BB = BBWorkList.back();
1235 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001236
David Greene389fc3b2010-01-05 01:27:15 +00001237 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001238
Chris Lattner074be1f2004-11-15 04:44:20 +00001239 // Notify all instructions in this basic block that they are newly
1240 // executable.
1241 visit(BB);
1242 }
1243 }
1244}
1245
Chris Lattner1847f6d2006-12-20 06:21:33 +00001246/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001247/// that branches on undef values cannot reach any of their successors.
1248/// However, this is not a safe assumption. After we solve dataflow, this
1249/// method should be use to handle this. If this returns true, the solver
1250/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001251///
1252/// This method handles this by finding an unresolved branch and marking it one
1253/// of the edges from the block as being feasible, even though the condition
1254/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1255/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001256/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001257/// constraints on the condition of the branch, as that would impact other users
1258/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001259///
1260/// This scan also checks for values that use undefs, whose results are actually
1261/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1262/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1263/// even if X isn't defined.
1264bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001265 for (BasicBlock &BB : F) {
1266 if (!BBExecutable.count(&BB))
Chris Lattneraf170962006-10-22 05:59:17 +00001267 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001268
Benjamin Kramer135f7352016-06-26 12:28:59 +00001269 for (Instruction &I : BB) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001270 // Look for instructions which produce undef values.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001271 if (I.getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001272
Davide Italianoe3bdd612016-12-01 08:36:12 +00001273 if (auto *STy = dyn_cast<StructType>(I.getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001274 // Only a few things that can be structs matter for undef.
1275
1276 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001277 if (CallSite CS = CallSite(&I))
Eli Friedman1815b682011-09-20 23:28:51 +00001278 if (Function *F = CS.getCalledFunction())
1279 if (MRVFunctionsTracked.count(F))
1280 continue;
1281
1282 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001283 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001284 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1285 continue;
1286
1287 // Send the results of everything else to overdefined. We could be
1288 // more precise than this but it isn't worth bothering.
1289 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001290 LatticeVal &LV = getStructValueState(&I, i);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001291 if (LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001292 markOverdefined(LV, &I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001293 }
1294 continue;
1295 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001296
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001297 LatticeVal &LV = getValueState(&I);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001298 if (!LV.isUnknown()) continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001299
Eli Friedmand7749be2011-08-17 18:10:43 +00001300 // extractvalue is safe; check here because the argument is a struct.
1301 if (isa<ExtractValueInst>(I))
1302 continue;
1303
1304 // Compute the operand LatticeVals, for convenience below.
1305 // Anything taking a struct is conservatively assumed to require
1306 // overdefined markings.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001307 if (I.getOperand(0)->getType()->isStructTy()) {
1308 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001309 return true;
1310 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001311 LatticeVal Op0LV = getValueState(I.getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001312 LatticeVal Op1LV;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001313 if (I.getNumOperands() == 2) {
1314 if (I.getOperand(1)->getType()->isStructTy()) {
1315 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001316 return true;
1317 }
1318
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001319 Op1LV = getValueState(I.getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001320 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001321 // If this is an instructions whose result is defined even if the input is
1322 // not fully defined, propagate the information.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001323 Type *ITy = I.getType();
1324 switch (I.getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001325 case Instruction::Add:
1326 case Instruction::Sub:
1327 case Instruction::Trunc:
1328 case Instruction::FPTrunc:
1329 case Instruction::BitCast:
1330 break; // Any undef -> undef
1331 case Instruction::FSub:
1332 case Instruction::FAdd:
1333 case Instruction::FMul:
1334 case Instruction::FDiv:
1335 case Instruction::FRem:
1336 // Floating-point binary operation: be conservative.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001337 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001338 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001339 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001340 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001341 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001342 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001343 case Instruction::SExt:
1344 case Instruction::FPToUI:
1345 case Instruction::FPToSI:
1346 case Instruction::FPExt:
1347 case Instruction::PtrToInt:
1348 case Instruction::IntToPtr:
1349 case Instruction::SIToFP:
1350 case Instruction::UIToFP:
1351 // undef -> 0; some outputs are impossible
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001352 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001353 return true;
1354 case Instruction::Mul:
1355 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001356 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001357 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001358 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001359 // undef * X -> 0. X could be zero.
1360 // undef & X -> 0. X could be zero.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001361 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001362 return true;
1363
1364 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001365 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001366 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001367 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001368 // undef | X -> -1. X could be -1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001369 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001370 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001371
Eli Friedman0793eb42011-08-16 22:06:31 +00001372 case Instruction::Xor:
1373 // undef ^ undef -> 0; strictly speaking, this is not strictly
1374 // necessary, but we try to be nice to people who expect this
1375 // behavior in simple cases
Davide Italiano0f03ce02016-07-10 00:35:15 +00001376 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001377 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001378 return true;
1379 }
1380 // undef ^ X -> undef
1381 break;
1382
Chris Lattner1847f6d2006-12-20 06:21:33 +00001383 case Instruction::SDiv:
1384 case Instruction::UDiv:
1385 case Instruction::SRem:
1386 case Instruction::URem:
1387 // X / undef -> undef. No change.
1388 // X % undef -> undef. No change.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001389 if (Op1LV.isUnknown()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001390
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001391 // X / 0 -> undef. No change.
1392 // X % 0 -> undef. No change.
1393 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1394 break;
1395
Chris Lattner1847f6d2006-12-20 06:21:33 +00001396 // undef / X -> 0. X could be maxint.
1397 // undef % X -> 0. X could be 1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001398 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001399 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +00001400
Chris Lattner1847f6d2006-12-20 06:21:33 +00001401 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001402 // X >>a undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001403 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001404
David Majnemer96f0d382016-05-12 03:07:40 +00001405 // Shifting by the bitwidth or more is undefined.
1406 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001407 if (auto *ShiftAmt = Op1LV.getConstantInt())
1408 if (ShiftAmt->getLimitedValue() >=
1409 ShiftAmt->getType()->getScalarSizeInBits())
1410 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001411 }
1412
Davide Italiano54c683f2016-12-08 22:28:53 +00001413 // undef >>a X -> 0
1414 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001415 return true;
1416 case Instruction::LShr:
1417 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001418 // X << undef -> undef.
1419 // X >> undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001420 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001421
David Majnemer96f0d382016-05-12 03:07:40 +00001422 // Shifting by the bitwidth or more is undefined.
1423 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001424 if (auto *ShiftAmt = Op1LV.getConstantInt())
1425 if (ShiftAmt->getLimitedValue() >=
1426 ShiftAmt->getType()->getScalarSizeInBits())
1427 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001428 }
1429
Eli Friedman0793eb42011-08-16 22:06:31 +00001430 // undef << X -> 0
1431 // undef >> X -> 0
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001432 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001433 return true;
1434 case Instruction::Select:
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001435 Op1LV = getValueState(I.getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001436 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001437 if (Op0LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001438 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001439 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001440 } else if (Op1LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001441 // c ? undef : undef -> undef. No change.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001442 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001443 if (Op1LV.isUnknown())
Chris Lattner1847f6d2006-12-20 06:21:33 +00001444 break;
1445 // Otherwise, c ? undef : x -> x.
1446 } else {
1447 // Leave Op1LV as Operand(1)'s LatticeValue.
1448 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001449
Chris Lattner1847f6d2006-12-20 06:21:33 +00001450 if (Op1LV.isConstant())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001451 markForcedConstant(&I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001452 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001453 markOverdefined(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001454 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001455 case Instruction::Load:
1456 // A load here means one of two things: a load of undef from a global,
1457 // a load from an unknown pointer. Either way, having it return undef
1458 // is okay.
1459 break;
1460 case Instruction::ICmp:
1461 // X == undef -> undef. Other comparisons get more complicated.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001462 if (cast<ICmpInst>(&I)->isEquality())
Eli Friedman0793eb42011-08-16 22:06:31 +00001463 break;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001464 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001465 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001466 case Instruction::Call:
1467 case Instruction::Invoke: {
1468 // There are two reasons a call can have an undef result
1469 // 1. It could be tracked.
1470 // 2. It could be constant-foldable.
1471 // Because of the way we solve return values, tracked calls must
1472 // never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001473 if (Function *F = CallSite(&I).getCalledFunction())
Eli Friedman1815b682011-09-20 23:28:51 +00001474 if (TrackedRetVals.count(F))
1475 break;
1476
1477 // If the call is constant-foldable, we mark it overdefined because
1478 // we do not know what return values are valid.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001479 markOverdefined(&I);
Eli Friedman1815b682011-09-20 23:28:51 +00001480 return true;
1481 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001482 default:
1483 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001484 // overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001485 markOverdefined(&I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001486 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001487 }
1488 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001489
Chris Lattneradca6082010-04-05 22:14:48 +00001490 // Check to see if we have a branch or switch on an undefined value. If so
1491 // we force the branch to go one way or the other to make the successor
1492 // values live. It doesn't really matter which way we force it.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001493 TerminatorInst *TI = BB.getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +00001494 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneraf170962006-10-22 05:59:17 +00001495 if (!BI->isConditional()) continue;
Davide Italiano0f03ce02016-07-10 00:35:15 +00001496 if (!getValueState(BI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001497 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001498
Chris Lattneradca6082010-04-05 22:14:48 +00001499 // If the input to SCCP is actually branch on undef, fix the undef to
1500 // false.
1501 if (isa<UndefValue>(BI->getCondition())) {
1502 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Benjamin Kramer135f7352016-06-26 12:28:59 +00001503 markEdgeExecutable(&BB, TI->getSuccessor(1));
Chris Lattneradca6082010-04-05 22:14:48 +00001504 return true;
1505 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001506
Chris Lattneradca6082010-04-05 22:14:48 +00001507 // Otherwise, it is a branch on a symbolic value which is currently
1508 // considered to be undef. Handle this by forcing the input value to the
1509 // branch to false.
1510 markForcedConstant(BI->getCondition(),
1511 ConstantInt::getFalse(TI->getContext()));
1512 return true;
1513 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001514
Xin Tong34888c02017-04-10 00:33:25 +00001515 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1516 // Indirect branch with no successor ?. Its ok to assume it branches
1517 // to no target.
1518 if (IBR->getNumSuccessors() < 1)
1519 continue;
1520
1521 if (!getValueState(IBR->getAddress()).isUnknown())
1522 continue;
1523
1524 // If the input to SCCP is actually branch on undef, fix the undef to
1525 // the first successor of the indirect branch.
1526 if (isa<UndefValue>(IBR->getAddress())) {
1527 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1528 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1529 return true;
1530 }
1531
1532 // Otherwise, it is a branch on a symbolic value which is currently
1533 // considered to be undef. Handle this by forcing the input value to the
1534 // branch to the first successor.
1535 markForcedConstant(IBR->getAddress(),
1536 BlockAddress::get(IBR->getSuccessor(0)));
1537 return true;
1538 }
1539
Davide Italianoe3bdd612016-12-01 08:36:12 +00001540 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Davide Italiano094dadd2016-07-15 18:33:16 +00001541 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001542 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001543
Chris Lattneradca6082010-04-05 22:14:48 +00001544 // If the input to SCCP is actually switch on undef, fix the undef to
1545 // the first constant.
1546 if (isa<UndefValue>(SI->getCondition())) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00001547 SI->setCondition(SI->case_begin()->getCaseValue());
1548 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001549 return true;
1550 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001551
Chandler Carruth927d8e62017-04-12 07:27:28 +00001552 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001553 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001554 }
Chris Lattneraf170962006-10-22 05:59:17 +00001555 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001556
Chris Lattneraf170962006-10-22 05:59:17 +00001557 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001558}
1559
Davide Italiano6f735882016-07-14 20:25:54 +00001560static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
Davide Italiano296e9782016-07-13 23:20:04 +00001561 Constant *Const = nullptr;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001562 if (V->getType()->isStructTy()) {
1563 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
David Majnemer0a16c222016-08-11 21:15:00 +00001564 if (any_of(IVs, [](const LatticeVal &LV) { return LV.isOverdefined(); }))
Davide Italiano296e9782016-07-13 23:20:04 +00001565 return false;
1566 std::vector<Constant *> ConstVals;
Davide Italianoe3bdd612016-12-01 08:36:12 +00001567 auto *ST = dyn_cast<StructType>(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001568 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1569 LatticeVal V = IVs[i];
1570 ConstVals.push_back(V.isConstant()
1571 ? V.getConstant()
1572 : UndefValue::get(ST->getElementType(i)));
1573 }
1574 Const = ConstantStruct::get(ST, ConstVals);
1575 } else {
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00001576 LatticeVal IV = Solver.getLatticeValueFor(V);
Davide Italiano296e9782016-07-13 23:20:04 +00001577 if (IV.isOverdefined())
1578 return false;
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00001579 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001580 }
1581 assert(Const && "Constant is nullptr here!");
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001582 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
Davide Italiano296e9782016-07-13 23:20:04 +00001583
1584 // Replaces all of the uses of a variable with uses of the constant.
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001585 V->replaceAllUsesWith(Const);
Davide Italiano6ed6d772016-07-14 01:27:29 +00001586 return true;
1587}
1588
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001589// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner074be1f2004-11-15 04:44:20 +00001590// and return true if the function was modified.
1591//
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001592static bool runSCCP(Function &F, const DataLayout &DL,
1593 const TargetLibraryInfo *TLI) {
David Greene389fc3b2010-01-05 01:27:15 +00001594 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001595 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001596
1597 // Mark the first block of the function as being executable.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001598 Solver.MarkBlockExecutable(&F.front());
Chris Lattner074be1f2004-11-15 04:44:20 +00001599
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001600 // Mark all arguments to the function as being overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001601 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001602 Solver.markOverdefined(&AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001603
Chris Lattner074be1f2004-11-15 04:44:20 +00001604 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001605 bool ResolvedUndefs = true;
1606 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001607 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001608 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001609 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001610 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001611
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001612 bool MadeChanges = false;
1613
1614 // If we decided that there are basic blocks that are dead in this function,
1615 // delete their contents now. Note that we cannot actually delete the blocks,
1616 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001617
Benjamin Kramer135f7352016-06-26 12:28:59 +00001618 for (BasicBlock &BB : F) {
1619 if (!Solver.isBlockExecutable(&BB)) {
1620 DEBUG(dbgs() << " BasicBlock Dead:" << BB);
David Majnemer88542a02016-01-24 06:26:47 +00001621
1622 ++NumDeadBlocks;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001623 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer88542a02016-01-24 06:26:47 +00001624
Chris Lattnere405ed92009-11-02 02:47:51 +00001625 MadeChanges = true;
1626 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001627 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001628
Chris Lattnere405ed92009-11-02 02:47:51 +00001629 // Iterate over all of the instructions in a function, replacing them with
1630 // constants if we have found them to be of constant values.
1631 //
Benjamin Kramer135f7352016-06-26 12:28:59 +00001632 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001633 Instruction *Inst = &*BI++;
Chris Lattnere405ed92009-11-02 02:47:51 +00001634 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1635 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001636
Sanjoy Dasff855b62016-08-24 18:10:21 +00001637 if (tryToReplaceWithConstant(Solver, Inst)) {
1638 if (isInstructionTriviallyDead(Inst))
1639 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001640 // Hey, we just changed something!
1641 MadeChanges = true;
1642 ++NumInstRemoved;
Davide Italiano00802692016-07-12 19:54:19 +00001643 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001644 }
1645 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001646
1647 return MadeChanges;
1648}
Chris Lattnerb4394642004-12-10 08:02:06 +00001649
Sean Silva36e0d012016-08-09 00:28:15 +00001650PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001651 const DataLayout &DL = F.getParent()->getDataLayout();
1652 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1653 if (!runSCCP(F, DL, &TLI))
1654 return PreservedAnalyses::all();
Davide Italiano484b5ab2016-05-29 00:31:15 +00001655
1656 auto PA = PreservedAnalyses();
1657 PA.preserve<GlobalsAA>();
1658 return PA;
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001659}
1660
1661namespace {
1662//===--------------------------------------------------------------------===//
1663//
1664/// SCCP Class - This class uses the SCCPSolver to implement a per-function
1665/// Sparse Conditional Constant Propagator.
1666///
Davide Italiano46f249b2016-05-19 15:58:02 +00001667class SCCPLegacyPass : public FunctionPass {
1668public:
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001669 void getAnalysisUsage(AnalysisUsage &AU) const override {
1670 AU.addRequired<TargetLibraryInfoWrapperPass>();
1671 AU.addPreserved<GlobalsAAWrapperPass>();
1672 }
1673 static char ID; // Pass identification, replacement for typeid
1674 SCCPLegacyPass() : FunctionPass(ID) {
1675 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1676 }
1677
1678 // runOnFunction - Run the Sparse Conditional Constant Propagation
1679 // algorithm, and return true if the function was modified.
1680 //
1681 bool runOnFunction(Function &F) override {
1682 if (skipFunction(F))
1683 return false;
1684 const DataLayout &DL = F.getParent()->getDataLayout();
1685 const TargetLibraryInfo *TLI =
1686 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1687 return runSCCP(F, DL, TLI);
1688 }
1689};
1690} // end anonymous namespace
1691
1692char SCCPLegacyPass::ID = 0;
1693INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1694 "Sparse Conditional Constant Propagation", false, false)
1695INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1696INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1697 "Sparse Conditional Constant Propagation", false, false)
1698
1699// createSCCPPass - This is the public interface to this file.
1700FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1701
Gabor Greif9027ffb2010-03-24 10:29:52 +00001702static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001703 // Delete any dead constantexpr klingons.
1704 GV->removeDeadConstantUsers();
1705
Chandler Carruthcdf47882014-03-09 03:16:01 +00001706 for (const Use &U : GV->uses()) {
1707 const User *UR = U.getUser();
Davide Italianoe3bdd612016-12-01 08:36:12 +00001708 if (const auto *SI = dyn_cast<StoreInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001709 if (SI->getOperand(0) == GV || SI->isVolatile())
1710 return true; // Storing addr of GV.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001711 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001712 // Make sure we are calling the function, not passing the address.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001713 ImmutableCallSite CS(cast<Instruction>(UR));
1714 if (!CS.isCallee(&U))
Nick Lewyckyd73806a2008-11-03 03:49:14 +00001715 return true;
Davide Italianoe3bdd612016-12-01 08:36:12 +00001716 } else if (const auto *LI = dyn_cast<LoadInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001717 if (LI->isVolatile())
1718 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001719 } else if (isa<BlockAddress>(UR)) {
Chris Lattner1a8b80e2009-11-01 06:11:53 +00001720 // blockaddress doesn't take the address of the function, it takes addr
1721 // of label.
Chris Lattner91dbae62004-12-11 05:15:59 +00001722 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001723 return true;
1724 }
Gabor Greif9027ffb2010-03-24 10:29:52 +00001725 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001726 return false;
1727}
1728
Davide Italiano15ff2d62016-07-20 20:17:13 +00001729static void findReturnsToZap(Function &F,
1730 SmallPtrSet<Function *, 32> &AddressTakenFunctions,
1731 SmallVector<ReturnInst *, 8> &ReturnsToZap) {
1732 // We can only do this if we know that nothing else can call the function.
1733 if (!F.hasLocalLinkage() || AddressTakenFunctions.count(&F))
1734 return;
1735
1736 for (BasicBlock &BB : F)
Davide Italianoe3bdd612016-12-01 08:36:12 +00001737 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001738 if (!isa<UndefValue>(RI->getOperand(0)))
1739 ReturnsToZap.push_back(RI);
1740}
1741
Davide Italianof54f2f02016-05-05 21:05:36 +00001742static bool runIPSCCP(Module &M, const DataLayout &DL,
1743 const TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001744 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001745
Chris Lattner363226d2010-08-12 22:25:23 +00001746 // AddressTakenFunctions - This set keeps track of the address-taken functions
1747 // that are in the input. As IPSCCP runs through and simplifies code,
1748 // functions that were address taken can end up losing their
1749 // address-taken-ness. Because of this, we keep track of their addresses from
1750 // the first pass so we can use them for the later simplification pass.
1751 SmallPtrSet<Function*, 32> AddressTakenFunctions;
Jakub Staszak632a3552012-01-18 21:16:33 +00001752
Chris Lattnerb4394642004-12-10 08:02:06 +00001753 // Loop over all functions, marking arguments to those with their addresses
1754 // taken or that are external as overdefined.
1755 //
Davide Italianoe7c56c52016-05-14 20:59:09 +00001756 for (Function &F : M) {
1757 if (F.isDeclaration())
Chris Lattner47837c52009-11-02 06:34:04 +00001758 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001759
Sanjoy Das5ce32722016-04-08 00:48:30 +00001760 // If this is an exact definition of this function, then we can propagate
1761 // information about its result into callsites of it.
Davide Italiano7343b9f2017-02-01 01:01:22 +00001762 // Don't touch naked functions. They may contain asm returning a
1763 // value we don't see, so we may end up interprocedurally propagating
1764 // the return value incorrectly.
Davide Italianocb68f372017-02-02 00:46:54 +00001765 if (F.hasExactDefinition() && !F.hasFnAttribute(Attribute::Naked))
Davide Italianoe7c56c52016-05-14 20:59:09 +00001766 Solver.AddTrackedFunction(&F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001767
Chris Lattnerfb141812009-11-03 03:42:51 +00001768 // If this function only has direct calls that we can see, we can track its
1769 // arguments and return value aggressively, and can assume it is not called
1770 // unless we see evidence to the contrary.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001771 if (F.hasLocalLinkage()) {
Davide Italianoc4861ad2017-05-23 23:59:23 +00001772 if (F.hasAddressTaken()) {
Davide Italianoe7c56c52016-05-14 20:59:09 +00001773 AddressTakenFunctions.insert(&F);
Davide Italianoc4861ad2017-05-23 23:59:23 +00001774 }
Chris Lattner363226d2010-08-12 22:25:23 +00001775 else {
Davide Italianoe7c56c52016-05-14 20:59:09 +00001776 Solver.AddArgumentTrackedFunction(&F);
Chris Lattner363226d2010-08-12 22:25:23 +00001777 continue;
1778 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001779 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001780
1781 // Assume the function is called.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001782 Solver.MarkBlockExecutable(&F.front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001783
Chris Lattnerfb141812009-11-03 03:42:51 +00001784 // Assume nothing about the incoming arguments.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001785 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001786 Solver.markOverdefined(&AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001787 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001788
Chris Lattner91dbae62004-12-11 05:15:59 +00001789 // Loop over global variables. We inform the solver about any internal global
1790 // variables that do not have their 'addresses taken'. If they don't have
1791 // their addresses taken, we can propagate constants through them.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001792 for (GlobalVariable &G : M.globals())
David Majnemer91c63302017-07-31 17:47:07 +00001793 if (!G.isConstant() && G.hasLocalLinkage() &&
1794 G.hasDefinitiveInitializer() && !AddressIsTaken(&G))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001795 Solver.TrackValueOfGlobalVariable(&G);
Chris Lattner91dbae62004-12-11 05:15:59 +00001796
Chris Lattnerb4394642004-12-10 08:02:06 +00001797 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001798 bool ResolvedUndefs = true;
1799 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001800 Solver.Solve();
1801
David Greene389fc3b2010-01-05 01:27:15 +00001802 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001803 ResolvedUndefs = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001804 for (Function &F : M)
1805 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001806 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001807
1808 bool MadeChanges = false;
1809
1810 // Iterate over all of the instructions in the module, replacing them with
1811 // constants if we have found them to be of constant values.
1812 //
Chris Lattner65938fc2008-08-23 23:36:38 +00001813 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001814
Benjamin Kramer135f7352016-06-26 12:28:59 +00001815 for (Function &F : M) {
1816 if (F.isDeclaration())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001817 continue;
1818
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00001819 if (Solver.isBlockExecutable(&F.front()))
Benjamin Kramer135f7352016-06-26 12:28:59 +00001820 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00001821 ++AI)
Davide Italianoec5b0252017-06-16 20:50:31 +00001822 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI))
Davide Italiano6ed6d772016-07-14 01:27:29 +00001823 ++IPNumArgsElimed;
Chris Lattnerb4394642004-12-10 08:02:06 +00001824
Benjamin Kramer135f7352016-06-26 12:28:59 +00001825 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001826 if (!Solver.isBlockExecutable(&*BB)) {
David Majnemer88542a02016-01-24 06:26:47 +00001827 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001828
David Majnemer88542a02016-01-24 06:26:47 +00001829 ++NumDeadBlocks;
David Majnemere14e7bc2016-06-25 08:19:55 +00001830 NumInstRemoved +=
1831 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
David Majnemer88542a02016-01-24 06:26:47 +00001832
1833 MadeChanges = true;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001834
Benjamin Kramer135f7352016-06-26 12:28:59 +00001835 if (&*BB != &F.front())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001836 BlocksToErase.push_back(&*BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001837 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001838 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001839
Chris Lattnere405ed92009-11-02 02:47:51 +00001840 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001841 Instruction *Inst = &*BI++;
Davide Italiano7dac0272016-07-14 02:51:41 +00001842 if (Inst->getType()->isVoidTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001843 continue;
Sanjoy Dasff855b62016-08-24 18:10:21 +00001844 if (tryToReplaceWithConstant(Solver, Inst)) {
1845 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1846 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001847 // Hey, we just changed something!
1848 MadeChanges = true;
1849 ++IPNumInstRemoved;
1850 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001851 }
1852 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001853
1854 // Now that all instructions in the function are constant folded, erase dead
1855 // blocks, because we can now use ConstantFoldTerminator to get rid of
1856 // in-edges.
1857 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1858 // If there are any PHI nodes in this successor, drop entries for BB now.
1859 BasicBlock *DeadBB = BlocksToErase[i];
Chandler Carruthcdf47882014-03-09 03:16:01 +00001860 for (Value::user_iterator UI = DeadBB->user_begin(),
1861 UE = DeadBB->user_end();
1862 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001863 // Grab the user and then increment the iterator early, as the user
1864 // will be deleted. Step past all adjacent uses from the same user.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001865 auto *I = dyn_cast<Instruction>(*UI);
Dan Gohman1f522d92009-11-23 16:13:39 +00001866 do { ++UI; } while (UI != UE && *UI == I);
1867
Dan Gohmand15302a2009-11-20 20:19:14 +00001868 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001869 if (!I) continue;
1870
Davide Italianodf670a12016-12-06 02:26:50 +00001871 bool Folded = ConstantFoldTerminator(I->getParent());
Xin Tong42ef2172017-02-26 02:11:24 +00001872 assert(Folded &&
1873 "Expect TermInst on constantint or blockaddress to be folded");
1874 (void) Folded;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001875 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001876
Chris Lattnerbae4b642004-12-10 22:29:08 +00001877 // Finally, delete the basic block.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001878 F.getBasicBlockList().erase(DeadBB);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001879 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001880 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001881 }
Chris Lattner99e12952004-12-11 02:53:57 +00001882
1883 // If we inferred constant or undef return values for a function, we replaced
1884 // all call uses with the inferred value. This means we don't need to bother
1885 // actually returning anything from the function. Replace all return
1886 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001887 //
1888 // Do this in two stages: first identify the functions we should process, then
1889 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001890 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001891 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001892 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001893 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00001894
Devang Patela7a20752008-03-11 05:46:42 +00001895 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Benjamin Kramer135f7352016-06-26 12:28:59 +00001896 for (const auto &I : RV) {
1897 Function *F = I.first;
1898 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
Chris Lattnerfb141812009-11-03 03:42:51 +00001899 continue;
Davide Italiano15ff2d62016-07-20 20:17:13 +00001900 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1901 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001902
Davide Italiano15ff2d62016-07-20 20:17:13 +00001903 for (const auto &F : Solver.getMRVFunctionsTracked()) {
1904 assert(F->getReturnType()->isStructTy() &&
1905 "The return type should be a struct");
1906 StructType *STy = cast<StructType>(F->getReturnType());
1907 if (Solver.isStructLatticeConstant(F, STy))
1908 findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001909 }
1910
1911 // Zap all returns which we've identified as zap to change.
1912 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1913 Function *F = ReturnsToZap[i]->getParent()->getParent();
1914 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00001915 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001916
Chad Rosierbb2a6da2012-03-28 00:35:33 +00001917 // If we inferred constant or undef values for globals variables, we can
1918 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001919 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1920 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001921 E = TG.end(); I != E; ++I) {
1922 GlobalVariable *GV = I->first;
1923 assert(!I->second.isOverdefined() &&
1924 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00001925 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00001926 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001927 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00001928 SI->eraseFromParent();
1929 }
1930 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001931 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001932 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001933
Chris Lattnerb4394642004-12-10 08:02:06 +00001934 return MadeChanges;
1935}
Davide Italianof54f2f02016-05-05 21:05:36 +00001936
Sean Silvafd03ac62016-08-09 00:28:38 +00001937PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
Davide Italianof54f2f02016-05-05 21:05:36 +00001938 const DataLayout &DL = M.getDataLayout();
1939 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
1940 if (!runIPSCCP(M, DL, &TLI))
1941 return PreservedAnalyses::all();
1942 return PreservedAnalyses::none();
1943}
1944
1945namespace {
1946//===--------------------------------------------------------------------===//
1947//
1948/// IPSCCP Class - This class implements interprocedural Sparse Conditional
1949/// Constant Propagation.
1950///
Davide Italiano46f249b2016-05-19 15:58:02 +00001951class IPSCCPLegacyPass : public ModulePass {
1952public:
Davide Italianof54f2f02016-05-05 21:05:36 +00001953 static char ID;
1954
1955 IPSCCPLegacyPass() : ModulePass(ID) {
1956 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1957 }
1958
1959 bool runOnModule(Module &M) override {
1960 if (skipModule(M))
1961 return false;
1962 const DataLayout &DL = M.getDataLayout();
1963 const TargetLibraryInfo *TLI =
1964 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1965 return runIPSCCP(M, DL, TLI);
1966 }
1967
1968 void getAnalysisUsage(AnalysisUsage &AU) const override {
1969 AU.addRequired<TargetLibraryInfoWrapperPass>();
1970 }
1971};
1972} // end anonymous namespace
1973
1974char IPSCCPLegacyPass::ID = 0;
1975INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
1976 "Interprocedural Sparse Conditional Constant Propagation",
1977 false, false)
1978INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1979INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
1980 "Interprocedural Sparse Conditional Constant Propagation",
1981 false, false)
1982
1983// createIPSCCPPass - This is the public interface to this file.
1984ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }