blob: 2f6ed05c023b1e6bb63835fb59682ebc334b1786 [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
David Blaikie3bbf5af2018-03-22 21:41:29 +000020#include "llvm/Transforms/Scalar/SCCP.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000021#include "llvm/ADT/ArrayRef.h"
Chris Lattner067d6072007-02-02 20:38:30 +000022#include "llvm/ADT/DenseMap.h"
Chris Lattner65938fc2008-08-23 23:36:38 +000023#include "llvm/ADT/DenseSet.h"
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000024#include "llvm/ADT/PointerIntPair.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000025#include "llvm/ADT/STLExtras.h"
Chris Lattner809aee22009-11-02 06:11:23 +000026#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000027#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Analysis/ConstantFolding.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000030#include "llvm/Analysis/GlobalsModRef.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000031#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000032#include "llvm/Transforms/Utils/Local.h"
Florian Hahnd0208b42017-10-30 10:07:42 +000033#include "llvm/Analysis/ValueLattice.h"
Matthew Simpson22849372017-10-13 17:53:44 +000034#include "llvm/Analysis/ValueLatticeUtils.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000035#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000036#include "llvm/IR/CallSite.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000037#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000041#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalVariable.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000043#include "llvm/IR/InstVisitor.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000044#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Instructions.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000047#include "llvm/IR/Module.h"
48#include "llvm/IR/PassManager.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000052#include "llvm/Pass.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000053#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/raw_ostream.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000057#include "llvm/Transforms/Scalar.h"
Florian Hahn30522902018-08-23 11:04:00 +000058#include "llvm/Transforms/Utils/PredicateInfo.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000059#include <cassert>
60#include <utility>
61#include <vector>
62
Chris Lattner49525f82004-01-09 06:02:20 +000063using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000064
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "sccp"
66
Chris Lattner79a42ac2006-12-19 21:40:18 +000067STATISTIC(NumInstRemoved, "Number of instructions removed");
68STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
69
Nick Lewycky35e92c72008-03-08 07:48:41 +000070STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000071STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
72STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
73
Chris Lattner7d325382002-04-29 21:26:08 +000074namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +000075
Chris Lattner1847f6d2006-12-20 06:21:33 +000076/// LatticeVal class - This class represents the different lattice values that
77/// an LLVM value may occupy. It is a simple class with value semantics.
78///
Chris Lattner2dd09db2009-09-02 06:11:42 +000079class LatticeVal {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000080 enum LatticeValueTy {
Davide Italiano0f03ce02016-07-10 00:35:15 +000081 /// unknown - This LLVM Value has no known value yet.
82 unknown,
Jakub Staszak632a3552012-01-18 21:16:33 +000083
Chris Lattner1847f6d2006-12-20 06:21:33 +000084 /// constant - This LLVM Value has a specific constant value.
85 constant,
86
87 /// forcedconstant - This LLVM Value was thought to be undef until
88 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
89 /// with another (different) constant, it goes to overdefined, instead of
90 /// asserting.
91 forcedconstant,
Jakub Staszak632a3552012-01-18 21:16:33 +000092
Chris Lattner1847f6d2006-12-20 06:21:33 +000093 /// overdefined - This instruction is not known to be constant, and we know
94 /// it has a value.
95 overdefined
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000096 };
97
98 /// Val: This stores the current lattice value along with the Constant* for
99 /// the constant if this is a 'constant' or 'forcedconstant' value.
100 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Jakub Staszak632a3552012-01-18 21:16:33 +0000101
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000102 LatticeValueTy getLatticeValue() const {
103 return Val.getInt();
104 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000105
Chris Lattner347389d2001-06-27 23:38:11 +0000106public:
Davide Italiano0f03ce02016-07-10 00:35:15 +0000107 LatticeVal() : Val(nullptr, unknown) {}
Jakub Staszak632a3552012-01-18 21:16:33 +0000108
Davide Italiano0f03ce02016-07-10 00:35:15 +0000109 bool isUnknown() const { return getLatticeValue() == unknown; }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000110
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000111 bool isConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000112 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
113 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000114
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000115 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Jakub Staszak632a3552012-01-18 21:16:33 +0000116
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000117 Constant *getConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000118 assert(isConstant() && "Cannot get the constant of a non-constant!");
119 return Val.getPointer();
120 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000121
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000122 /// markOverdefined - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000123 bool markOverdefined() {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000124 if (isOverdefined())
125 return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000126
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000127 Val.setInt(overdefined);
128 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000129 }
130
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000131 /// markConstant - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000132 bool markConstant(Constant *V) {
Chris Lattnere1d5cd92009-11-03 16:50:11 +0000133 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000134 assert(getConstant() == V && "Marking constant with different value");
135 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000136 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000137
Davide Italiano0f03ce02016-07-10 00:35:15 +0000138 if (isUnknown()) {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000139 Val.setInt(constant);
140 assert(V && "Marking constant with NULL");
141 Val.setPointer(V);
142 } else {
Jakub Staszak632a3552012-01-18 21:16:33 +0000143 assert(getLatticeValue() == forcedconstant &&
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000144 "Cannot move from overdefined to constant!");
145 // Stay at forcedconstant if the constant is the same.
146 if (V == getConstant()) return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000147
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000148 // Otherwise, we go to overdefined. Assumptions made based on the
149 // forced value are possibly wrong. Assuming this is another constant
150 // could expose a contradiction.
151 Val.setInt(overdefined);
152 }
153 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000154 }
155
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000156 /// getConstantInt - If this is a constant with a ConstantInt value, return it
157 /// otherwise return null.
158 ConstantInt *getConstantInt() const {
159 if (isConstant())
160 return dyn_cast<ConstantInt>(getConstant());
Craig Topperf40110f2014-04-25 05:29:35 +0000161 return nullptr;
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000162 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000163
Xin Tong34888c02017-04-10 00:33:25 +0000164 /// getBlockAddress - If this is a constant with a BlockAddress value, return
165 /// it, otherwise return null.
166 BlockAddress *getBlockAddress() const {
167 if (isConstant())
168 return dyn_cast<BlockAddress>(getConstant());
169 return nullptr;
170 }
171
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000172 void markForcedConstant(Constant *V) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000173 assert(isUnknown() && "Can't force a defined value!");
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000174 Val.setInt(forcedconstant);
175 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000176 }
Florian Hahnd0208b42017-10-30 10:07:42 +0000177
178 ValueLatticeElement toValueLattice() const {
179 if (isOverdefined())
180 return ValueLatticeElement::getOverdefined();
181 if (isConstant())
182 return ValueLatticeElement::get(getConstant());
183 return ValueLatticeElement();
184 }
Chris Lattner347389d2001-06-27 23:38:11 +0000185};
186
Chris Lattner347389d2001-06-27 23:38:11 +0000187//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000188//
Chris Lattner074be1f2004-11-15 04:44:20 +0000189/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
190/// Constant Propagation.
191///
192class SCCPSolver : public InstVisitor<SCCPSolver> {
Mehdi Amini46a43552015-03-04 18:43:29 +0000193 const DataLayout &DL;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000194 const TargetLibraryInfo *TLI;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000195 SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
196 DenseMap<Value *, LatticeVal> ValueState; // The state each value is in.
Florian Hahnd0208b42017-10-30 10:07:42 +0000197 // The state each parameter is in.
198 DenseMap<Value *, ValueLatticeElement> ParamState;
Chris Lattner347389d2001-06-27 23:38:11 +0000199
Chris Lattner156b8c72009-11-03 23:40:48 +0000200 /// StructValueState - This maintains ValueState for values that have
201 /// StructType, for example for formal arguments, calls, insertelement, etc.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000202 DenseMap<std::pair<Value *, unsigned>, LatticeVal> StructValueState;
Jakub Staszak632a3552012-01-18 21:16:33 +0000203
Chris Lattner91dbae62004-12-11 05:15:59 +0000204 /// GlobalValue - If we are tracking any values for the contents of a global
205 /// variable, we keep a mapping from the constant accessor to the element of
206 /// the global, to the currently known value. If the value becomes
207 /// overdefined, it's entry is simply removed from this map.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000208 DenseMap<GlobalVariable *, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000209
Devang Patela7a20752008-03-11 05:46:42 +0000210 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000211 /// value out of a function, it will have an entry in this map, indicating
212 /// what the known return value for the function is.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000213 DenseMap<Function *, LatticeVal> TrackedRetVals;
Devang Patela7a20752008-03-11 05:46:42 +0000214
215 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
216 /// that return multiple values.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000217 DenseMap<std::pair<Function *, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak632a3552012-01-18 21:16:33 +0000218
Chris Lattner156b8c72009-11-03 23:40:48 +0000219 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
220 /// represented here for efficient lookup.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000221 SmallPtrSet<Function *, 16> MRVFunctionsTracked;
Chris Lattnerb4394642004-12-10 08:02:06 +0000222
Reid Kleckner3762a082018-03-01 01:19:18 +0000223 /// MustTailFunctions - Each function here is a callee of non-removable
224 /// musttail call site.
225 SmallPtrSet<Function *, 16> MustTailCallees;
226
Chris Lattner2c427232009-11-03 20:52:57 +0000227 /// TrackingIncomingArguments - This is the set of functions for whose
228 /// arguments we make optimistic assumptions about and try to prove as
229 /// constants.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000230 SmallPtrSet<Function *, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000231
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000232 /// The reason for two worklists is that overdefined is the lowest state
233 /// on the lattice, and moving things to overdefined as fast as possible
234 /// makes SCCP converge much faster.
235 ///
236 /// By having a separate worklist, we accomplish this because everything
237 /// possibly overdefined will become overdefined at the soonest possible
238 /// point.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000239 SmallVector<Value *, 64> OverdefinedInstWorkList;
240 SmallVector<Value *, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000241
Eugene Zelenko99241d72017-10-20 21:47:29 +0000242 // The BasicBlock work list
243 SmallVector<BasicBlock *, 64> BBWorkList;
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000244
245 /// KnownFeasibleEdges - Entries in this set are edges which have already had
246 /// PHI nodes retriggered.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000247 using Edge = std::pair<BasicBlock *, BasicBlock *>;
Chris Lattner65938fc2008-08-23 23:36:38 +0000248 DenseSet<Edge> KnownFeasibleEdges;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000249
Florian Hahna1062f42018-11-09 11:52:27 +0000250 DenseMap<Function *, AnalysisResultsForFn> AnalysisResults;
Florian Hahn30522902018-08-23 11:04:00 +0000251 DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
252
Chris Lattner347389d2001-06-27 23:38:11 +0000253public:
Florian Hahna1062f42018-11-09 11:52:27 +0000254 void addAnalysis(Function &F, AnalysisResultsForFn A) {
255 AnalysisResults.insert({&F, std::move(A)});
Florian Hahn30522902018-08-23 11:04:00 +0000256 }
257
258 const PredicateBase *getPredicateInfoFor(Instruction *I) {
Florian Hahna1062f42018-11-09 11:52:27 +0000259 auto A = AnalysisResults.find(I->getParent()->getParent());
260 if (A == AnalysisResults.end())
Florian Hahn30522902018-08-23 11:04:00 +0000261 return nullptr;
Florian Hahna1062f42018-11-09 11:52:27 +0000262 return A->second.PredInfo->getPredicateInfoFor(I);
263 }
264
Florian Hahn9026d4e2018-11-11 20:22:45 +0000265 DomTreeUpdater getDTU(Function &F) {
Florian Hahna1062f42018-11-09 11:52:27 +0000266 auto A = AnalysisResults.find(&F);
267 assert(A != AnalysisResults.end() && "Need analysis results for function.");
Florian Hahn9026d4e2018-11-11 20:22:45 +0000268 return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy};
Florian Hahn30522902018-08-23 11:04:00 +0000269 }
270
Mehdi Amini46a43552015-03-04 18:43:29 +0000271 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
272 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000273
Chris Lattner074be1f2004-11-15 04:44:20 +0000274 /// MarkBlockExecutable - This method can be used by clients to mark all of
275 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000276 ///
277 /// This returns true if the block was not considered live before.
278 bool MarkBlockExecutable(BasicBlock *BB) {
David Blaikie70573dc2014-11-19 07:49:26 +0000279 if (!BBExecutable.insert(BB).second)
280 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000281 LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000282 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000283 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000284 }
285
Chris Lattner91dbae62004-12-11 05:15:59 +0000286 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000287 /// inform the SCCPSolver that it should track loads and stores to the
288 /// specified global variable if it can. This is only legal to call if
289 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000290 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000291 // We only track the contents of scalar globals.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000292 if (GV->getValueType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000293 LatticeVal &IV = TrackedGlobals[GV];
294 if (!isa<UndefValue>(GV->getInitializer()))
295 IV.markConstant(GV->getInitializer());
296 }
297 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000298
299 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
300 /// and out of the specified function (which cannot have its address taken),
301 /// this method must be called.
302 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000303 // Add an entry, F -> undef.
Davide Italianoe3bdd612016-12-01 08:36:12 +0000304 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000305 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000307 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
308 LatticeVal()));
309 } else
310 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000311 }
312
Reid Kleckner3762a082018-03-01 01:19:18 +0000313 /// AddMustTailCallee - If the SCCP solver finds that this function is called
314 /// from non-removable musttail call site.
315 void AddMustTailCallee(Function *F) {
316 MustTailCallees.insert(F);
317 }
318
319 /// Returns true if the given function is called from non-removable musttail
320 /// call site.
321 bool isMustTailCallee(Function *F) {
322 return MustTailCallees.count(F);
323 }
324
Chris Lattnercde8de52009-11-03 19:24:51 +0000325 void AddArgumentTrackedFunction(Function *F) {
326 TrackingIncomingArguments.insert(F);
327 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000328
Matthew Simpson22849372017-10-13 17:53:44 +0000329 /// Returns true if the given function is in the solver's set of
330 /// argument-tracked functions.
331 bool isArgumentTrackedFunction(Function *F) {
332 return TrackingIncomingArguments.count(F);
333 }
334
Chris Lattner074be1f2004-11-15 04:44:20 +0000335 /// Solve - Solve for constants and executable blocks.
Chris Lattner074be1f2004-11-15 04:44:20 +0000336 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000337
Chris Lattner1847f6d2006-12-20 06:21:33 +0000338 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000339 /// that branches on undef values cannot reach any of their successors.
340 /// However, this is not a safe assumption. After we solve dataflow, this
341 /// method should be use to handle this. If this returns true, the solver
342 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000343 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000344
Chris Lattneradd44f32008-08-23 23:39:31 +0000345 bool isBlockExecutable(BasicBlock *BB) const {
346 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000347 }
348
Eli Friedmana3c78f52018-07-19 23:02:07 +0000349 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
350 // block to the 'To' basic block is currently feasible.
351 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
352
Davide Italiano00802692016-07-12 19:54:19 +0000353 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
354 std::vector<LatticeVal> StructValues;
Davide Italianoe3bdd612016-12-01 08:36:12 +0000355 auto *STy = dyn_cast<StructType>(V->getType());
Davide Italiano00802692016-07-12 19:54:19 +0000356 assert(STy && "getStructLatticeValueFor() can be called only on structs");
357 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
358 auto I = StructValueState.find(std::make_pair(V, i));
359 assert(I != StructValueState.end() && "Value not in valuemap!");
360 StructValues.push_back(I->second);
361 }
362 return StructValues;
363 }
364
Florian Hahn0a560d52018-07-20 13:29:12 +0000365 const LatticeVal &getLatticeValueFor(Value *V) const {
Florian Hahnd0208b42017-10-30 10:07:42 +0000366 assert(!V->getType()->isStructTy() &&
367 "Should use getStructLatticeValueFor");
Florian Hahn0a560d52018-07-20 13:29:12 +0000368 DenseMap<Value *, LatticeVal>::const_iterator I = ValueState.find(V);
369 assert(I != ValueState.end() &&
370 "V not found in ValueState nor Paramstate map!");
371 return I->second;
Chris Lattner074be1f2004-11-15 04:44:20 +0000372 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000373
Devang Patela7a20752008-03-11 05:46:42 +0000374 /// getTrackedRetVals - Get the inferred return value map.
Devang Patela7a20752008-03-11 05:46:42 +0000375 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
376 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000377 }
378
Chris Lattner91dbae62004-12-11 05:15:59 +0000379 /// getTrackedGlobals - Get and return the set of inferred initializers for
380 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000381 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000382 return TrackedGlobals;
383 }
384
Davide Italiano15ff2d62016-07-20 20:17:13 +0000385 /// getMRVFunctionsTracked - Get the set of functions which return multiple
386 /// values tracked by the pass.
387 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
388 return MRVFunctionsTracked;
389 }
390
Reid Kleckner3762a082018-03-01 01:19:18 +0000391 /// getMustTailCallees - Get the set of functions which are called
392 /// from non-removable musttail call sites.
393 const SmallPtrSet<Function *, 16> getMustTailCallees() {
394 return MustTailCallees;
395 }
396
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000397 /// markOverdefined - Mark the specified value overdefined. This
Chris Lattner156b8c72009-11-03 23:40:48 +0000398 /// works with both scalars and structs.
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000399 void markOverdefined(Value *V) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000400 if (auto *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000401 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
402 markOverdefined(getStructValueState(V, i), V);
403 else
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000404 markOverdefined(ValueState[V], V);
Chris Lattner156b8c72009-11-03 23:40:48 +0000405 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000406
Davide Italiano15ff2d62016-07-20 20:17:13 +0000407 // isStructLatticeConstant - Return true if all the lattice values
408 // corresponding to elements of the structure are not overdefined,
409 // false otherwise.
410 bool isStructLatticeConstant(Function *F, StructType *STy) {
411 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
412 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
413 assert(It != TrackedMultipleRetVals.end());
414 LatticeVal LV = It->second;
415 if (LV.isOverdefined())
416 return false;
417 }
418 return true;
419 }
420
Chris Lattner347389d2001-06-27 23:38:11 +0000421private:
Davide Italiano0a1476c2016-12-11 21:19:03 +0000422 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
Davide Italiano390b7ea2016-07-13 19:33:25 +0000423 void pushToWorkList(LatticeVal &IV, Value *V) {
424 if (IV.isOverdefined())
425 return OverdefinedInstWorkList.push_back(V);
426 InstWorkList.push_back(V);
427 }
428
Chris Lattnerd79334d2004-07-15 23:36:43 +0000429 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000430 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000431 // the users of the instruction are updated later.
Florian Hahn0a560d52018-07-20 13:29:12 +0000432 bool markConstant(LatticeVal &IV, Value *V, Constant *C) {
433 if (!IV.markConstant(C)) return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000434 LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000435 pushToWorkList(IV, V);
Florian Hahn0a560d52018-07-20 13:29:12 +0000436 return true;
Chris Lattner7324f7c2003-10-08 16:21:03 +0000437 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000438
Florian Hahn0a560d52018-07-20 13:29:12 +0000439 bool markConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000440 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Florian Hahn0a560d52018-07-20 13:29:12 +0000441 return markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000442 }
443
Chris Lattnerf5484032009-11-02 05:55:40 +0000444 void markForcedConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000445 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000446 LatticeVal &IV = ValueState[V];
447 IV.markForcedConstant(C);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000448 LLVM_DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000449 pushToWorkList(IV, V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000450 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000451
Chris Lattnerd79334d2004-07-15 23:36:43 +0000452 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000454 // work list so that the users of the instruction are updated later.
Florian Hahn0a560d52018-07-20 13:29:12 +0000455 bool markOverdefined(LatticeVal &IV, Value *V) {
456 if (!IV.markOverdefined()) return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000457
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000458 LLVM_DEBUG(dbgs() << "markOverdefined: ";
459 if (auto *F = dyn_cast<Function>(V)) dbgs()
460 << "Function '" << F->getName() << "'\n";
461 else dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000462 // Only instructions go on the work list
Davide Italiano0a1476c2016-12-11 21:19:03 +0000463 pushToWorkList(IV, V);
Florian Hahn0a560d52018-07-20 13:29:12 +0000464 return true;
Chris Lattner7324f7c2003-10-08 16:21:03 +0000465 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000466
Florian Hahn0a560d52018-07-20 13:29:12 +0000467 bool mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000468 if (IV.isOverdefined() || MergeWithV.isUnknown())
Florian Hahn0a560d52018-07-20 13:29:12 +0000469 return false; // Noop.
Chris Lattnerb4394642004-12-10 08:02:06 +0000470 if (MergeWithV.isOverdefined())
Davide Italiano21850012016-07-13 19:23:30 +0000471 return markOverdefined(IV, V);
472 if (IV.isUnknown())
473 return markConstant(IV, V, MergeWithV.getConstant());
474 if (IV.getConstant() != MergeWithV.getConstant())
475 return markOverdefined(IV, V);
Florian Hahn0a560d52018-07-20 13:29:12 +0000476 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000477 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000478
Florian Hahn0a560d52018-07-20 13:29:12 +0000479 bool mergeInValue(Value *V, LatticeVal MergeWithV) {
Davide Italiano63266b62016-07-19 18:31:07 +0000480 assert(!V->getType()->isStructTy() &&
481 "non-structs should use markConstant");
Florian Hahn0a560d52018-07-20 13:29:12 +0000482 return mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000483 }
484
Chris Lattnerf5484032009-11-02 05:55:40 +0000485 /// getValueState - Return the LatticeVal object that corresponds to the
486 /// value. This function handles the case when the value hasn't been seen yet
487 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000488 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000489 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000490
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000491 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
492 ValueState.insert(std::make_pair(V, LatticeVal()));
493 LatticeVal &LV = I.first->second;
494
495 if (!I.second)
496 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000497
Davide Italianoe3bdd612016-12-01 08:36:12 +0000498 if (auto *C = dyn_cast<Constant>(V)) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000499 // Undef values remain unknown.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000500 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000501 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000502 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000503
Chris Lattnera3c39d32009-11-02 02:33:50 +0000504 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000505 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000506 }
507
Florian Hahnd0208b42017-10-30 10:07:42 +0000508 ValueLatticeElement &getParamState(Value *V) {
509 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
510
511 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
512 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
513 ValueLatticeElement &LV = PI.first->second;
514 if (PI.second)
515 LV = getValueState(V).toValueLattice();
516
517 return LV;
518 }
519
Chris Lattner156b8c72009-11-03 23:40:48 +0000520 /// getStructValueState - Return the LatticeVal object that corresponds to the
521 /// value/field pair. This function handles the case when the value hasn't
522 /// been seen yet by properly seeding constants etc.
523 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000524 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000525 assert(i < cast<StructType>(V->getType())->getNumElements() &&
526 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000527
528 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
529 bool> I = StructValueState.insert(
530 std::make_pair(std::make_pair(V, i), LatticeVal()));
531 LatticeVal &LV = I.first->second;
532
533 if (!I.second)
534 return LV; // Common case, already in the map.
535
Davide Italianoe3bdd612016-12-01 08:36:12 +0000536 if (auto *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000537 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000538
Craig Topperf40110f2014-04-25 05:29:35 +0000539 if (!Elt)
Chris Lattner156b8c72009-11-03 23:40:48 +0000540 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000541 else if (isa<UndefValue>(Elt))
Davide Italiano0f03ce02016-07-10 00:35:15 +0000542 ; // Undef values remain unknown.
Chris Lattnerfa775002012-01-26 02:32:04 +0000543 else
544 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000545 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000546
Chris Lattner156b8c72009-11-03 23:40:48 +0000547 // All others are underdefined by default.
548 return LV;
549 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000550
Chris Lattnerf5484032009-11-02 05:55:40 +0000551 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
552 /// work list if it is not already executable.
Eli Friedmana3c78f52018-07-19 23:02:07 +0000553 bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000554 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
Eli Friedmana3c78f52018-07-19 23:02:07 +0000555 return false; // This edge is already known to be executable!
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000556
Chris Lattner809aee22009-11-02 06:11:23 +0000557 if (!MarkBlockExecutable(Dest)) {
558 // If the destination is already executable, we just made an *edge*
559 // feasible that wasn't before. Revisit the PHI nodes in the block
560 // because they have potentially new operands.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
562 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000563
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000564 for (PHINode &PN : Dest->phis())
565 visitPHINode(PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000566 }
Eli Friedmana3c78f52018-07-19 23:02:07 +0000567 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000568 }
569
Chris Lattner074be1f2004-11-15 04:44:20 +0000570 // getFeasibleSuccessors - Return a vector of booleans to indicate which
571 // successors are reachable from a given terminator instruction.
Chandler Carruth52eaaf32018-10-15 10:10:54 +0000572 void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000573
Chris Lattner074be1f2004-11-15 04:44:20 +0000574 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000575 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000576 // information, we need to update the specified user of this instruction.
Chris Lattnerfb141812009-11-03 03:42:51 +0000577 void OperandChangedState(Instruction *I) {
578 if (BBExecutable.count(I->getParent())) // Inst is executable?
579 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000580 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000581
Florian Hahn30522902018-08-23 11:04:00 +0000582 // Add U as additional user of V.
583 void addAdditionalUser(Value *V, User *U) {
584 auto Iter = AdditionalUsers.insert({V, {}});
585 Iter.first->second.insert(U);
586 }
587
588 // Mark I's users as changed, including AdditionalUsers.
589 void markUsersAsChanged(Value *I) {
590 for (User *U : I->users())
591 if (auto *UI = dyn_cast<Instruction>(U))
592 OperandChangedState(UI);
593
594 auto Iter = AdditionalUsers.find(I);
595 if (Iter != AdditionalUsers.end()) {
596 for (User *U : Iter->second)
597 if (auto *UI = dyn_cast<Instruction>(U))
598 OperandChangedState(UI);
599 }
600 }
601
Chris Lattner074be1f2004-11-15 04:44:20 +0000602private:
603 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000604
Chris Lattnera3c39d32009-11-02 02:33:50 +0000605 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000606 // operand made a transition, or the instruction is newly executable. Change
607 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000608 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000609
610 // Terminators
Eugene Zelenko99241d72017-10-20 21:47:29 +0000611
Chris Lattnerb4394642004-12-10 08:02:06 +0000612 void visitReturnInst(ReturnInst &I);
Chandler Carruth52eaaf32018-10-15 10:10:54 +0000613 void visitTerminator(Instruction &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000614
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000615 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000616 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000617 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000618 void visitCmpInst(CmpInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000619 void visitExtractValueInst(ExtractValueInst &EVI);
620 void visitInsertValueInst(InsertValueInst &IVI);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000621
David Majnemer8a1c45d2015-12-12 05:38:55 +0000622 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000623 markOverdefined(&CPI);
Chandler Carruth52eaaf32018-10-15 10:10:54 +0000624 visitTerminator(CPI);
David Majnemereb518bd2015-08-04 08:21:40 +0000625 }
Chris Lattner6e560792002-04-18 15:13:15 +0000626
Chris Lattnera3c39d32009-11-02 02:33:50 +0000627 // Instructions that cannot be folded away.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000628
Chris Lattnerf5484032009-11-02 05:55:40 +0000629 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000630 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000631 void visitGetElementPtrInst(GetElementPtrInst &I);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000632
Victor Hernandeze2971492009-10-24 04:23:03 +0000633 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000634 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000635 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000636
Chris Lattnerb4394642004-12-10 08:02:06 +0000637 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000638 visitCallSite(&II);
Chandler Carruth52eaaf32018-10-15 10:10:54 +0000639 visitTerminator(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000640 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000641
Chris Lattnerb4394642004-12-10 08:02:06 +0000642 void visitCallSite (CallSite CS);
Chandler Carruth52eaaf32018-10-15 10:10:54 +0000643 void visitResumeInst (ResumeInst &I) { /*returns void*/ }
644 void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ }
Davide Italianoa7f5e882016-05-04 23:27:13 +0000645 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000646
Chris Lattner113f4f42002-06-25 16:13:24 +0000647 void visitInstruction(Instruction &I) {
Davide Italiano0b1190a2017-06-16 20:27:17 +0000648 // All the instructions we don't do any special handling for just
649 // go to overdefined.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000650 LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
Davide Italiano0b1190a2017-06-16 20:27:17 +0000651 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000652 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000653};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000654
Duncan Sands2be91fc2007-07-20 08:56:21 +0000655} // end anonymous namespace
656
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000657// getFeasibleSuccessors - Return a vector of booleans to indicate which
658// successors are reachable from a given terminator instruction.
Chandler Carruth52eaaf32018-10-15 10:10:54 +0000659void SCCPSolver::getFeasibleSuccessors(Instruction &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000660 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000661 Succs.resize(TI.getNumSuccessors());
Davide Italianoe3bdd612016-12-01 08:36:12 +0000662 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000663 if (BI->isUnconditional()) {
664 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000665 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000666 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000667
Chris Lattnerf5484032009-11-02 05:55:40 +0000668 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000669 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000670 if (!CI) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000671 // Overdefined condition variables, and branches on unfoldable constant
672 // conditions, mean the branch could go either way.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000673 if (!BCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000674 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000675 return;
676 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000677
Chris Lattner6df5cec2009-11-02 02:30:06 +0000678 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000679 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000680 return;
681 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000682
David Majnemer654e1302015-07-31 17:58:14 +0000683 // Unwinding instructions successors are always executable.
Chandler Carruth698fbe72018-08-26 08:56:42 +0000684 if (TI.isExceptionalTerminator()) {
David Majnemer654e1302015-07-31 17:58:14 +0000685 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattneree8b9512009-10-29 01:21:20 +0000686 return;
687 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000688
Davide Italianoe3bdd612016-12-01 08:36:12 +0000689 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000690 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000691 Succs[0] = true;
692 return;
693 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000694 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000695 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000696
Davide Italiano0f03ce02016-07-10 00:35:15 +0000697 if (!CI) { // Overdefined or unknown condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000698 // All destinations are executable!
Davide Italiano0f03ce02016-07-10 00:35:15 +0000699 if (!SCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000700 Succs.assign(TI.getNumSuccessors(), true);
701 return;
702 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000703
Chandler Carruth927d8e62017-04-12 07:27:28 +0000704 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000705 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000706 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000707
Xin Tong34888c02017-04-10 00:33:25 +0000708 // In case of indirect branch and its address is a blockaddress, we mark
709 // the target as executable.
710 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
711 // Casts are folded by visitCastInst.
712 LatticeVal IBRValue = getValueState(IBR->getAddress());
713 BlockAddress *Addr = IBRValue.getBlockAddress();
714 if (!Addr) { // Overdefined or unknown condition?
715 // All destinations are executable!
716 if (!IBRValue.isUnknown())
717 Succs.assign(TI.getNumSuccessors(), true);
718 return;
719 }
720
721 BasicBlock* T = Addr->getBasicBlock();
722 assert(Addr->getFunction() == T->getParent() &&
723 "Block address of a different function ?");
724 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
725 // This is the target.
726 if (IBR->getDestination(i) == T) {
727 Succs[i] = true;
728 return;
729 }
730 }
731
732 // If we didn't find our destination in the IBR successor list, then we
733 // have undefined behavior. Its ok to assume no successor is executable.
Chris Lattneree8b9512009-10-29 01:21:20 +0000734 return;
735 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000736
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000737 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
Chris Lattneree8b9512009-10-29 01:21:20 +0000738 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000739}
740
Chris Lattner13b52e72002-05-02 21:18:01 +0000741// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000742// block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000743bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Eli Friedmana3c78f52018-07-19 23:02:07 +0000744 // Check if we've called markEdgeExecutable on the edge yet. (We could
745 // be more aggressive and try to consider edges which haven't been marked
746 // yet, but there isn't any need.)
747 return KnownFeasibleEdges.count(Edge(From, To));
Chris Lattner13b52e72002-05-02 21:18:01 +0000748}
Chris Lattner347389d2001-06-27 23:38:11 +0000749
Chris Lattnera3c39d32009-11-02 02:33:50 +0000750// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000751// operand made a transition, or the instruction is newly executable. Change
752// the value type of I to reflect these changes if appropriate. This method
753// makes sure to do the following actions:
754//
755// 1. If a phi node merges two constants in, and has conflicting value coming
756// from different branches, or if the PHI node merges in an overdefined
757// value, then the PHI node becomes overdefined.
758// 2. If a phi node merges only constants in, and they all agree on value, the
759// PHI node becomes a constant value equal to that.
760// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
761// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
762// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
763// 6. If a conditional branch has a value that is constant, make the selected
764// destination executable
765// 7. If a conditional branch has a value that is overdefined, make all
766// successors executable.
Chris Lattner074be1f2004-11-15 04:44:20 +0000767void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000768 // If this PN returns a struct, just mark the result overdefined.
769 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000770 if (PN.getType()->isStructTy())
Florian Hahn0a560d52018-07-20 13:29:12 +0000771 return (void)markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000772
Eli Friedman0a309292011-11-11 01:16:15 +0000773 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000774 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000775
Chris Lattner7a7b1142004-03-16 19:49:59 +0000776 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
777 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000778 if (PN.getNumIncomingValues() > 64)
Florian Hahn0a560d52018-07-20 13:29:12 +0000779 return (void)markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000780
Chris Lattner6e560792002-04-18 15:13:15 +0000781 // Look at all of the executable operands of the PHI node. If any of them
782 // are overdefined, the PHI becomes overdefined as well. If they are all
783 // constant, and they agree with each other, the PHI becomes the identical
784 // constant. If they are constant and don't agree, the PHI is overdefined.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000785 // If there are no executable operands, the PHI remains unknown.
Craig Topperf40110f2014-04-25 05:29:35 +0000786 Constant *OperandVal = nullptr;
Chris Lattnercccc5c72003-04-25 02:50:03 +0000787 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000788 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +0000789 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000790
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000791 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
792 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000793
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000794 if (IV.isOverdefined()) // PHI node becomes overdefined!
Florian Hahn0a560d52018-07-20 13:29:12 +0000795 return (void)markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000796
Craig Topperf40110f2014-04-25 05:29:35 +0000797 if (!OperandVal) { // Grab the first value.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000798 OperandVal = IV.getConstant();
799 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000800 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000801
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000802 // There is already a reachable operand. If we conflict with it,
803 // then the PHI node becomes overdefined. If we agree with it, we
804 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000805
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000806 // Check to see if there are two different constants merging, if so, the PHI
807 // node is overdefined.
808 if (IV.getConstant() != OperandVal)
Florian Hahn0a560d52018-07-20 13:29:12 +0000809 return (void)markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000810 }
811
Chris Lattner6e560792002-04-18 15:13:15 +0000812 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000813 // arguments that agree with each other(and OperandVal is the constant) or
814 // OperandVal is null because there are no defined incoming arguments. If
Davide Italiano0f03ce02016-07-10 00:35:15 +0000815 // this is the case, the PHI remains unknown.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000816 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000817 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000818}
819
Chris Lattnerb4394642004-12-10 08:02:06 +0000820void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000821 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000822
Chris Lattnerb4394642004-12-10 08:02:06 +0000823 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000824 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000825
Devang Patela7a20752008-03-11 05:46:42 +0000826 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000827 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000828 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000829 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000830 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000831 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000832 return;
833 }
834 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000835
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000836 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000837 if (!TrackedMultipleRetVals.empty()) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000838 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000839 if (MRVFunctionsTracked.count(F))
840 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
841 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
842 getStructValueState(ResultOp, i));
Chris Lattnerb4394642004-12-10 08:02:06 +0000843 }
844}
845
Chandler Carruth52eaaf32018-10-15 10:10:54 +0000846void SCCPSolver::visitTerminator(Instruction &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000847 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000848 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000849
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000850 BasicBlock *BB = TI.getParent();
851
Chris Lattnera3c39d32009-11-02 02:33:50 +0000852 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000853 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000854 if (SuccFeasible[i])
855 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000856}
857
Chris Lattner074be1f2004-11-15 04:44:20 +0000858void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000859 LatticeVal OpSt = getValueState(I.getOperand(0));
860 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000861 markOverdefined(&I);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000862 else if (OpSt.isConstant()) {
Davide Italianod555bde2016-07-08 19:13:40 +0000863 // Fold the constant as we build.
Davide Italiano63c4ce82016-07-11 18:21:29 +0000864 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
865 I.getType(), DL);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000866 if (isa<UndefValue>(C))
867 return;
868 // Propagate constant value
869 markConstant(&I, C);
870 }
Chris Lattner6e560792002-04-18 15:13:15 +0000871}
872
Dan Gohman041f9d02008-06-20 01:15:44 +0000873void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000874 // If this returns a struct, mark all elements over defined, we don't track
875 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000876 if (EVI.getType()->isStructTy())
Florian Hahn0a560d52018-07-20 13:29:12 +0000877 return (void)markOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000878
Chris Lattner156b8c72009-11-03 23:40:48 +0000879 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000880 if (EVI.getNumIndices() != 1)
Florian Hahn0a560d52018-07-20 13:29:12 +0000881 return (void)markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000882
Chris Lattner156b8c72009-11-03 23:40:48 +0000883 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000884 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000885 unsigned i = *EVI.idx_begin();
886 LatticeVal EltVal = getStructValueState(AggVal, i);
887 mergeInValue(getValueState(&EVI), &EVI, EltVal);
888 } else {
889 // Otherwise, must be extracting from an array.
Florian Hahn0a560d52018-07-20 13:29:12 +0000890 return (void)markOverdefined(&EVI);
Chris Lattner02e2cee2009-11-10 22:02:09 +0000891 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000892}
893
894void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000895 auto *STy = dyn_cast<StructType>(IVI.getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000896 if (!STy)
Florian Hahn0a560d52018-07-20 13:29:12 +0000897 return (void)markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000898
Chris Lattner156b8c72009-11-03 23:40:48 +0000899 // If this has more than one index, we can't handle it, drive all results to
900 // undef.
901 if (IVI.getNumIndices() != 1)
Florian Hahn0a560d52018-07-20 13:29:12 +0000902 return (void)markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000903
Chris Lattner156b8c72009-11-03 23:40:48 +0000904 Value *Aggr = IVI.getAggregateOperand();
905 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000906
Chris Lattner156b8c72009-11-03 23:40:48 +0000907 // Compute the result based on what we're inserting.
908 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
909 // This passes through all values that aren't the inserted element.
910 if (i != Idx) {
911 LatticeVal EltVal = getStructValueState(Aggr, i);
912 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
913 continue;
914 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000915
Chris Lattner156b8c72009-11-03 23:40:48 +0000916 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000917 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000918 // We don't track structs in structs.
919 markOverdefined(getStructValueState(&IVI, i), &IVI);
920 else {
921 LatticeVal InVal = getValueState(Val);
922 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
923 }
924 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000925}
926
Chris Lattner074be1f2004-11-15 04:44:20 +0000927void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000928 // If this select returns a struct, just mark the result overdefined.
929 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000930 if (I.getType()->isStructTy())
Florian Hahn0a560d52018-07-20 13:29:12 +0000931 return (void)markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000932
Chris Lattnerf5484032009-11-02 05:55:40 +0000933 LatticeVal CondValue = getValueState(I.getCondition());
Davide Italiano0f03ce02016-07-10 00:35:15 +0000934 if (CondValue.isUnknown())
Chris Lattner06a0ed12006-02-08 02:38:11 +0000935 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000936
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000937 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000938 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
939 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000940 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000941 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000942
Chris Lattner06a0ed12006-02-08 02:38:11 +0000943 // Otherwise, the condition is overdefined or a constant we can't evaluate.
944 // See if we can produce something better than overdefined based on the T/F
945 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000946 LatticeVal TVal = getValueState(I.getTrueValue());
947 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000948
Chris Lattner06a0ed12006-02-08 02:38:11 +0000949 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000950 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000951 TVal.getConstant() == FVal.getConstant())
Florian Hahn0a560d52018-07-20 13:29:12 +0000952 return (void)markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000953
Davide Italiano0f03ce02016-07-10 00:35:15 +0000954 if (TVal.isUnknown()) // select ?, undef, X -> X.
Florian Hahn0a560d52018-07-20 13:29:12 +0000955 return (void)mergeInValue(&I, FVal);
Davide Italiano0f03ce02016-07-10 00:35:15 +0000956 if (FVal.isUnknown()) // select ?, X, undef -> X.
Florian Hahn0a560d52018-07-20 13:29:12 +0000957 return (void)mergeInValue(&I, TVal);
Chris Lattnerf5484032009-11-02 05:55:40 +0000958 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000959}
960
Chris Lattnerf5484032009-11-02 05:55:40 +0000961// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000962void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000963 LatticeVal V1State = getValueState(I.getOperand(0));
964 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000965
Chris Lattner4f031622004-11-15 05:03:30 +0000966 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000967 if (IV.isOverdefined()) return;
968
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000969 if (V1State.isConstant() && V2State.isConstant()) {
970 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
971 V2State.getConstant());
972 // X op Y -> undef.
973 if (isa<UndefValue>(C))
974 return;
Florian Hahn0a560d52018-07-20 13:29:12 +0000975 return (void)markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000976 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000977
Chris Lattnerf5484032009-11-02 05:55:40 +0000978 // If something is undef, wait for it to resolve.
979 if (!V1State.isOverdefined() && !V2State.isOverdefined())
980 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000981
Chris Lattnerf5484032009-11-02 05:55:40 +0000982 // Otherwise, one of our operands is overdefined. Try to produce something
983 // better than overdefined with some tricks.
Davide Italiano6c2c3e02017-01-19 23:07:51 +0000984 // If this is 0 / Y, it doesn't matter that the second operand is
985 // overdefined, and we can replace it with zero.
986 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
987 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
Florian Hahn0a560d52018-07-20 13:29:12 +0000988 return (void)markConstant(IV, &I, V1State.getConstant());
Davide Italiano6c2c3e02017-01-19 23:07:51 +0000989
Davide Italiano93c6c182017-01-19 21:07:42 +0000990 // If this is:
991 // -> AND/MUL with 0
992 // -> OR with -1
993 // it doesn't matter that the other operand is overdefined.
Davide Italiano824d6952016-12-09 03:08:42 +0000994 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
995 I.getOpcode() == Instruction::Or) {
Craig Topperf40110f2014-04-25 05:29:35 +0000996 LatticeVal *NonOverdefVal = nullptr;
Chris Lattnerf5484032009-11-02 05:55:40 +0000997 if (!V1State.isOverdefined())
998 NonOverdefVal = &V1State;
999 else if (!V2State.isOverdefined())
1000 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +00001001
Chris Lattnerf5484032009-11-02 05:55:40 +00001002 if (NonOverdefVal) {
Davide Italianoe7ffae92016-11-22 22:11:25 +00001003 if (NonOverdefVal->isUnknown())
Chris Lattnerf5484032009-11-02 05:55:40 +00001004 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001005
Davide Italiano824d6952016-12-09 03:08:42 +00001006 if (I.getOpcode() == Instruction::And ||
1007 I.getOpcode() == Instruction::Mul) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001008 // X and 0 = 0
Davide Italiano824d6952016-12-09 03:08:42 +00001009 // X * 0 = 0
Chris Lattnerf5484032009-11-02 05:55:40 +00001010 if (NonOverdefVal->getConstant()->isNullValue())
Florian Hahn0a560d52018-07-20 13:29:12 +00001011 return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnerf5484032009-11-02 05:55:40 +00001012 } else {
Davide Italianoe7ffae92016-11-22 22:11:25 +00001013 // X or -1 = -1
Chris Lattnerf5484032009-11-02 05:55:40 +00001014 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
Craig Topper79ab6432017-07-06 18:39:47 +00001015 if (CI->isMinusOne())
Florian Hahn0a560d52018-07-20 13:29:12 +00001016 return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +00001017 }
1018 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001019 }
Chris Lattnercbc01612004-12-11 23:15:19 +00001020
Chris Lattnerf5484032009-11-02 05:55:40 +00001021 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +00001022}
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001023
Chris Lattnera3c39d32009-11-02 02:33:50 +00001024// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001025void SCCPSolver::visitCmpInst(CmpInst &I) {
Tim Northover48778062018-10-12 09:01:59 +00001026 // Do not cache this lookup, getValueState calls later in the function might
1027 // invalidate the reference.
1028 if (ValueState[&I].isOverdefined()) return;
Reid Spencer266e42b2006-12-23 06:05:41 +00001029
Florian Hahn0a560d52018-07-20 13:29:12 +00001030 Value *Op1 = I.getOperand(0);
1031 Value *Op2 = I.getOperand(1);
1032
1033 // For parameters, use ParamState which includes constant range info if
1034 // available.
1035 auto V1Param = ParamState.find(Op1);
1036 ValueLatticeElement V1State = (V1Param != ParamState.end())
1037 ? V1Param->second
1038 : getValueState(Op1).toValueLattice();
1039
1040 auto V2Param = ParamState.find(Op2);
1041 ValueLatticeElement V2State = V2Param != ParamState.end()
1042 ? V2Param->second
1043 : getValueState(Op2).toValueLattice();
1044
1045 Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
1046 if (C) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001047 if (isa<UndefValue>(C))
1048 return;
Florian Hahn0a560d52018-07-20 13:29:12 +00001049 LatticeVal CV;
1050 CV.markConstant(C);
1051 mergeInValue(&I, CV);
1052 return;
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001053 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001054
Davide Italiano0f03ce02016-07-10 00:35:15 +00001055 // If operands are still unknown, wait for it to resolve.
Tim Northover48778062018-10-12 09:01:59 +00001056 if (!V1State.isOverdefined() && !V2State.isOverdefined() &&
1057 !ValueState[&I].isConstant())
Chris Lattnerf5484032009-11-02 05:55:40 +00001058 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001059
Chris Lattnerf5484032009-11-02 05:55:40 +00001060 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +00001061}
1062
Chris Lattnera3c39d32009-11-02 02:33:50 +00001063// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001064// can turn this into a getelementptr ConstantExpr.
Chris Lattner074be1f2004-11-15 04:44:20 +00001065void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001066 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001067
Chris Lattner0e7ec672007-02-02 20:51:48 +00001068 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001069 Operands.reserve(I.getNumOperands());
1070
1071 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001072 LatticeVal State = getValueState(I.getOperand(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001073 if (State.isUnknown())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001074 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001075
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001076 if (State.isOverdefined())
Florian Hahn0a560d52018-07-20 13:29:12 +00001077 return (void)markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001078
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001079 assert(State.isConstant() && "Unknown state!");
1080 Operands.push_back(State.getConstant());
1081 }
1082
1083 Constant *Ptr = Operands[0];
Craig Toppere1d12942014-08-27 05:25:25 +00001084 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001085 Constant *C =
1086 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1087 if (isa<UndefValue>(C))
1088 return;
1089 markConstant(&I, C);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001090}
Brian Gaeke960707c2003-11-11 22:41:34 +00001091
Chris Lattnerf5484032009-11-02 05:55:40 +00001092void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001093 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001094 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001095 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001096
Chris Lattner91dbae62004-12-11 05:15:59 +00001097 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1098 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001099
Chris Lattner91dbae62004-12-11 05:15:59 +00001100 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001101 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001102 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1103
Chris Lattnerf5484032009-11-02 05:55:40 +00001104 // Get the value we are storing into the global, then merge it.
1105 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001106 if (I->second.isOverdefined())
1107 TrackedGlobals.erase(I); // No need to keep tracking this!
1108}
1109
Chris Lattner49f74522004-01-12 04:29:41 +00001110// Handle load instructions. If the operand is a constant pointer to a constant
1111// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001112void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001113 // If this load is of a struct, just mark the result overdefined.
David Majnemerf3b99dd2016-01-07 19:30:13 +00001114 if (I.getType()->isStructTy())
Florian Hahn0a560d52018-07-20 13:29:12 +00001115 return (void)markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001116
Chris Lattnerf5484032009-11-02 05:55:40 +00001117 LatticeVal PtrVal = getValueState(I.getOperand(0));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001118 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001119
Chris Lattner4f031622004-11-15 05:03:30 +00001120 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001121 if (IV.isOverdefined()) return;
1122
Chris Lattnerf5484032009-11-02 05:55:40 +00001123 if (!PtrVal.isConstant() || I.isVolatile())
Florian Hahn0a560d52018-07-20 13:29:12 +00001124 return (void)markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001125
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001126 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001127
David Majnemerbae94572016-01-07 19:25:39 +00001128 // load null is undefined.
Manoj Gupta77eeac32018-07-09 22:27:23 +00001129 if (isa<ConstantPointerNull>(Ptr)) {
1130 if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1131 return (void)markOverdefined(IV, &I);
1132 else
1133 return;
1134 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001135
Chris Lattnerf5484032009-11-02 05:55:40 +00001136 // Transform load (constant global) into the value loaded.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001137 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001138 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001139 // If we are tracking this global, merge in the known value for it.
1140 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1141 TrackedGlobals.find(GV);
1142 if (It != TrackedGlobals.end()) {
1143 mergeInValue(IV, &I, It->second);
1144 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001145 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001146 }
Chris Lattner49f74522004-01-12 04:29:41 +00001147 }
1148
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001149 // Transform load from a constant into a constant if possible.
Eduard Burtescu14239212016-01-22 01:17:26 +00001150 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001151 if (isa<UndefValue>(C))
1152 return;
Florian Hahn0a560d52018-07-20 13:29:12 +00001153 return (void)markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001154 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001155
Chris Lattner49f74522004-01-12 04:29:41 +00001156 // Otherwise we cannot say for certain what value this load will produce.
1157 // Bail out.
1158 markOverdefined(IV, &I);
1159}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001160
Chris Lattnerb4394642004-12-10 08:02:06 +00001161void SCCPSolver::visitCallSite(CallSite CS) {
1162 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001163 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001164
Florian Hahn30522902018-08-23 11:04:00 +00001165 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1166 if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1167 if (ValueState[I].isOverdefined())
1168 return;
1169
1170 auto *PI = getPredicateInfoFor(I);
1171 if (!PI)
1172 return;
1173
Florian Hahn6615a712018-11-25 16:32:02 +00001174 Value *CopyOf = I->getOperand(0);
Florian Hahn5c014032018-12-18 19:37:07 +00001175 auto *PBranch = dyn_cast<PredicateBranch>(PI);
Florian Hahn30522902018-08-23 11:04:00 +00001176 if (!PBranch) {
Florian Hahn6615a712018-11-25 16:32:02 +00001177 mergeInValue(ValueState[I], I, getValueState(CopyOf));
Florian Hahn30522902018-08-23 11:04:00 +00001178 return;
1179 }
1180
Florian Hahn30522902018-08-23 11:04:00 +00001181 Value *Cond = PBranch->Condition;
1182
1183 // Everything below relies on the condition being a comparison.
1184 auto *Cmp = dyn_cast<CmpInst>(Cond);
1185 if (!Cmp) {
Florian Hahn6615a712018-11-25 16:32:02 +00001186 mergeInValue(ValueState[I], I, getValueState(CopyOf));
Florian Hahn30522902018-08-23 11:04:00 +00001187 return;
1188 }
1189
1190 Value *CmpOp0 = Cmp->getOperand(0);
1191 Value *CmpOp1 = Cmp->getOperand(1);
1192 if (CopyOf != CmpOp0 && CopyOf != CmpOp1) {
Florian Hahn6615a712018-11-25 16:32:02 +00001193 mergeInValue(ValueState[I], I, getValueState(CopyOf));
Florian Hahn30522902018-08-23 11:04:00 +00001194 return;
1195 }
1196
1197 if (CmpOp0 != CopyOf)
1198 std::swap(CmpOp0, CmpOp1);
1199
1200 LatticeVal OriginalVal = getValueState(CopyOf);
1201 LatticeVal EqVal = getValueState(CmpOp1);
1202 LatticeVal &IV = ValueState[I];
1203 if (PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_EQ) {
1204 addAdditionalUser(CmpOp1, I);
1205 if (OriginalVal.isConstant())
1206 mergeInValue(IV, I, OriginalVal);
1207 else
1208 mergeInValue(IV, I, EqVal);
1209 return;
1210 }
1211 if (!PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_NE) {
1212 addAdditionalUser(CmpOp1, I);
1213 if (OriginalVal.isConstant())
1214 mergeInValue(IV, I, OriginalVal);
1215 else
1216 mergeInValue(IV, I, EqVal);
1217 return;
1218 }
1219
Florian Hahn6615a712018-11-25 16:32:02 +00001220 return (void)mergeInValue(IV, I, getValueState(CopyOf));
Florian Hahn30522902018-08-23 11:04:00 +00001221 }
1222 }
1223
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001224 // The common case is that we aren't tracking the callee, either because we
1225 // are not doing interprocedural analysis or the callee is indirect, or is
1226 // external. Handle these cases first.
Craig Topperf40110f2014-04-25 05:29:35 +00001227 if (!F || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001228CallOverdefined:
1229 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001230 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001231
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001232 // Otherwise, if we have a single return value case, and if the function is
1233 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001234 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Andrew Kaylor647025f2017-06-09 23:18:11 +00001235 canConstantFoldCallTo(CS, F)) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001236 SmallVector<Constant*, 8> Operands;
1237 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1238 AI != E; ++AI) {
James Y Knight72f76bf2018-11-07 15:24:12 +00001239 if (AI->get()->getType()->isStructTy())
1240 return markOverdefined(I); // Can't handle struct args.
Chris Lattnerf5484032009-11-02 05:55:40 +00001241 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001242
Davide Italiano0f03ce02016-07-10 00:35:15 +00001243 if (State.isUnknown())
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001244 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001245 if (State.isOverdefined())
Florian Hahn0a560d52018-07-20 13:29:12 +00001246 return (void)markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001247 assert(State.isConstant() && "Unknown state!");
1248 Operands.push_back(State.getConstant());
1249 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001250
David Majnemer2098b86f2014-11-07 08:54:19 +00001251 if (getValueState(I).isOverdefined())
1252 return;
1253
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001254 // If we can constant fold this, mark the result of the call as a
1255 // constant.
Andrew Kaylor647025f2017-06-09 23:18:11 +00001256 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001257 // call -> undef.
1258 if (isa<UndefValue>(C))
1259 return;
Florian Hahn0a560d52018-07-20 13:29:12 +00001260 return (void)markConstant(I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001261 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001262 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001263
1264 // Otherwise, we don't know anything about this call, mark it overdefined.
Florian Hahn0a560d52018-07-20 13:29:12 +00001265 return (void)markOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001266 }
1267
Chris Lattnercde8de52009-11-03 19:24:51 +00001268 // If this is a local function that doesn't have its address taken, mark its
1269 // entry block executable and merge in the actual arguments to the call into
1270 // the formal arguments of the function.
1271 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001272 MarkBlockExecutable(&F->front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001273
Chris Lattnercde8de52009-11-03 19:24:51 +00001274 // Propagate information from this call site into the callee.
1275 CallSite::arg_iterator CAI = CS.arg_begin();
1276 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1277 AI != E; ++AI, ++CAI) {
1278 // If this argument is byval, and if the function is not readonly, there
1279 // will be an implicit copy formed of the input aggregate.
1280 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001281 markOverdefined(&*AI);
Chris Lattnercde8de52009-11-03 19:24:51 +00001282 continue;
1283 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001284
Davide Italianoe3bdd612016-12-01 08:36:12 +00001285 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001286 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1287 LatticeVal CallArg = getStructValueState(*CAI, i);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001288 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
Chris Lattner762b56f2009-11-04 18:57:42 +00001289 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001290 } else {
Florian Hahnd0208b42017-10-30 10:07:42 +00001291 // Most other parts of the Solver still only use the simpler value
1292 // lattice, so we propagate changes for parameters to both lattices.
Florian Hahn0a560d52018-07-20 13:29:12 +00001293 LatticeVal ConcreteArgument = getValueState(*CAI);
1294 bool ParamChanged =
1295 getParamState(&*AI).mergeIn(ConcreteArgument.toValueLattice(), DL);
1296 bool ValueChanged = mergeInValue(&*AI, ConcreteArgument);
1297 // Add argument to work list, if the state of a parameter changes but
1298 // ValueState does not change (because it is already overdefined there),
1299 // We have to take changes in ParamState into account, as it is used
1300 // when evaluating Cmp instructions.
1301 if (!ValueChanged && ParamChanged)
1302 pushToWorkList(ValueState[&*AI], &*AI);
Chris Lattner156b8c72009-11-03 23:40:48 +00001303 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001304 }
1305 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001306
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001307 // If this is a single/zero retval case, see if we're tracking the function.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001308 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001309 if (!MRVFunctionsTracked.count(F))
1310 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001311
Chris Lattner156b8c72009-11-03 23:40:48 +00001312 // If we are tracking this callee, propagate the result of the function
1313 // into this call site.
1314 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001315 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001316 TrackedMultipleRetVals[std::make_pair(F, i)]);
1317 } else {
1318 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1319 if (TFRVI == TrackedRetVals.end())
1320 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001321
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001322 // If so, propagate the return value of the callee into this call result.
1323 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001324 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001325}
Chris Lattner074be1f2004-11-15 04:44:20 +00001326
Chris Lattner074be1f2004-11-15 04:44:20 +00001327void SCCPSolver::Solve() {
1328 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001329 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001330 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001331 // Process the overdefined instruction's work list first, which drives other
1332 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001333 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001334 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001335
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001336 LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001337
Chris Lattner074be1f2004-11-15 04:44:20 +00001338 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001339 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001340 //
1341 // Anything on this worklist that is overdefined need not be visited
1342 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001343 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001344 //
Florian Hahn30522902018-08-23 11:04:00 +00001345 markUsersAsChanged(I);
Chris Lattner074be1f2004-11-15 04:44:20 +00001346 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001347
Chris Lattnera3c39d32009-11-02 02:33:50 +00001348 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001349 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001350 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001351
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001352 LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001353
Chris Lattnerf5484032009-11-02 05:55:40 +00001354 // "I" got into the work list because it made the transition from undef to
1355 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001356 //
1357 // Anything on this worklist that is overdefined need not be visited
1358 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001359 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001360 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001361 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Florian Hahn30522902018-08-23 11:04:00 +00001362 markUsersAsChanged(I);
Chris Lattner074be1f2004-11-15 04:44:20 +00001363 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001364
Chris Lattnera3c39d32009-11-02 02:33:50 +00001365 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001366 while (!BBWorkList.empty()) {
1367 BasicBlock *BB = BBWorkList.back();
1368 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001369
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001370 LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001371
Chris Lattner074be1f2004-11-15 04:44:20 +00001372 // Notify all instructions in this basic block that they are newly
1373 // executable.
1374 visit(BB);
1375 }
1376 }
1377}
1378
Chris Lattner1847f6d2006-12-20 06:21:33 +00001379/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001380/// that branches on undef values cannot reach any of their successors.
1381/// However, this is not a safe assumption. After we solve dataflow, this
1382/// method should be use to handle this. If this returns true, the solver
1383/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001384///
1385/// This method handles this by finding an unresolved branch and marking it one
1386/// of the edges from the block as being feasible, even though the condition
1387/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1388/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001389/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001390/// constraints on the condition of the branch, as that would impact other users
1391/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001392///
1393/// This scan also checks for values that use undefs, whose results are actually
1394/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1395/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1396/// even if X isn't defined.
1397bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001398 for (BasicBlock &BB : F) {
1399 if (!BBExecutable.count(&BB))
Chris Lattneraf170962006-10-22 05:59:17 +00001400 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001401
Benjamin Kramer135f7352016-06-26 12:28:59 +00001402 for (Instruction &I : BB) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001403 // Look for instructions which produce undef values.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001404 if (I.getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001405
Davide Italianoe3bdd612016-12-01 08:36:12 +00001406 if (auto *STy = dyn_cast<StructType>(I.getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001407 // Only a few things that can be structs matter for undef.
1408
1409 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001410 if (CallSite CS = CallSite(&I))
Eli Friedman1815b682011-09-20 23:28:51 +00001411 if (Function *F = CS.getCalledFunction())
1412 if (MRVFunctionsTracked.count(F))
1413 continue;
1414
1415 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001416 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001417 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1418 continue;
1419
1420 // Send the results of everything else to overdefined. We could be
1421 // more precise than this but it isn't worth bothering.
1422 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001423 LatticeVal &LV = getStructValueState(&I, i);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001424 if (LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001425 markOverdefined(LV, &I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001426 }
1427 continue;
1428 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001429
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001430 LatticeVal &LV = getValueState(&I);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001431 if (!LV.isUnknown()) continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001432
Eli Friedmand7749be2011-08-17 18:10:43 +00001433 // extractvalue is safe; check here because the argument is a struct.
1434 if (isa<ExtractValueInst>(I))
1435 continue;
1436
1437 // Compute the operand LatticeVals, for convenience below.
1438 // Anything taking a struct is conservatively assumed to require
1439 // overdefined markings.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001440 if (I.getOperand(0)->getType()->isStructTy()) {
1441 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001442 return true;
1443 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001444 LatticeVal Op0LV = getValueState(I.getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001445 LatticeVal Op1LV;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001446 if (I.getNumOperands() == 2) {
1447 if (I.getOperand(1)->getType()->isStructTy()) {
1448 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001449 return true;
1450 }
1451
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001452 Op1LV = getValueState(I.getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001453 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001454 // If this is an instructions whose result is defined even if the input is
1455 // not fully defined, propagate the information.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001456 Type *ITy = I.getType();
1457 switch (I.getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001458 case Instruction::Add:
1459 case Instruction::Sub:
1460 case Instruction::Trunc:
1461 case Instruction::FPTrunc:
1462 case Instruction::BitCast:
1463 break; // Any undef -> undef
1464 case Instruction::FSub:
1465 case Instruction::FAdd:
1466 case Instruction::FMul:
1467 case Instruction::FDiv:
1468 case Instruction::FRem:
1469 // Floating-point binary operation: be conservative.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001470 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001471 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001472 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001473 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001474 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001475 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001476 case Instruction::SExt:
1477 case Instruction::FPToUI:
1478 case Instruction::FPToSI:
1479 case Instruction::FPExt:
1480 case Instruction::PtrToInt:
1481 case Instruction::IntToPtr:
1482 case Instruction::SIToFP:
1483 case Instruction::UIToFP:
1484 // undef -> 0; some outputs are impossible
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001485 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001486 return true;
1487 case Instruction::Mul:
1488 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001489 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001490 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001491 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001492 // undef * X -> 0. X could be zero.
1493 // undef & X -> 0. X could be zero.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001494 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001495 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001496 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001497 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001498 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001499 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001500 // undef | X -> -1. X could be -1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001501 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001502 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001503 case Instruction::Xor:
1504 // undef ^ undef -> 0; strictly speaking, this is not strictly
1505 // necessary, but we try to be nice to people who expect this
1506 // behavior in simple cases
Davide Italiano0f03ce02016-07-10 00:35:15 +00001507 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001508 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001509 return true;
1510 }
1511 // undef ^ X -> undef
1512 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001513 case Instruction::SDiv:
1514 case Instruction::UDiv:
1515 case Instruction::SRem:
1516 case Instruction::URem:
1517 // X / undef -> undef. No change.
1518 // X % undef -> undef. No change.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001519 if (Op1LV.isUnknown()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001520
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001521 // X / 0 -> undef. No change.
1522 // X % 0 -> undef. No change.
1523 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1524 break;
1525
Chris Lattner1847f6d2006-12-20 06:21:33 +00001526 // undef / X -> 0. X could be maxint.
1527 // undef % X -> 0. X could be 1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001528 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001529 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001530 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001531 // X >>a undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001532 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001533
David Majnemer96f0d382016-05-12 03:07:40 +00001534 // Shifting by the bitwidth or more is undefined.
1535 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001536 if (auto *ShiftAmt = Op1LV.getConstantInt())
1537 if (ShiftAmt->getLimitedValue() >=
1538 ShiftAmt->getType()->getScalarSizeInBits())
1539 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001540 }
1541
Davide Italiano54c683f2016-12-08 22:28:53 +00001542 // undef >>a X -> 0
1543 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001544 return true;
1545 case Instruction::LShr:
1546 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001547 // X << undef -> undef.
1548 // X >> undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001549 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001550
David Majnemer96f0d382016-05-12 03:07:40 +00001551 // Shifting by the bitwidth or more is undefined.
1552 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001553 if (auto *ShiftAmt = Op1LV.getConstantInt())
1554 if (ShiftAmt->getLimitedValue() >=
1555 ShiftAmt->getType()->getScalarSizeInBits())
1556 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001557 }
1558
Eli Friedman0793eb42011-08-16 22:06:31 +00001559 // undef << X -> 0
1560 // undef >> X -> 0
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001561 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001562 return true;
1563 case Instruction::Select:
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001564 Op1LV = getValueState(I.getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001565 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001566 if (Op0LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001567 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001568 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001569 } else if (Op1LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001570 // c ? undef : undef -> undef. No change.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001571 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001572 if (Op1LV.isUnknown())
Chris Lattner1847f6d2006-12-20 06:21:33 +00001573 break;
1574 // Otherwise, c ? undef : x -> x.
1575 } else {
1576 // Leave Op1LV as Operand(1)'s LatticeValue.
1577 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001578
Chris Lattner1847f6d2006-12-20 06:21:33 +00001579 if (Op1LV.isConstant())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001580 markForcedConstant(&I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001581 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001582 markOverdefined(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001583 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001584 case Instruction::Load:
1585 // A load here means one of two things: a load of undef from a global,
1586 // a load from an unknown pointer. Either way, having it return undef
1587 // is okay.
1588 break;
1589 case Instruction::ICmp:
1590 // X == undef -> undef. Other comparisons get more complicated.
Florian Hahn0a560d52018-07-20 13:29:12 +00001591 Op0LV = getValueState(I.getOperand(0));
1592 Op1LV = getValueState(I.getOperand(1));
1593
1594 if ((Op0LV.isUnknown() || Op1LV.isUnknown()) &&
1595 cast<ICmpInst>(&I)->isEquality())
Eli Friedman0793eb42011-08-16 22:06:31 +00001596 break;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001597 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001598 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001599 case Instruction::Call:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001600 case Instruction::Invoke:
Eli Friedman1815b682011-09-20 23:28:51 +00001601 // There are two reasons a call can have an undef result
1602 // 1. It could be tracked.
1603 // 2. It could be constant-foldable.
1604 // Because of the way we solve return values, tracked calls must
1605 // never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001606 if (Function *F = CallSite(&I).getCalledFunction())
Eli Friedman1815b682011-09-20 23:28:51 +00001607 if (TrackedRetVals.count(F))
1608 break;
1609
1610 // If the call is constant-foldable, we mark it overdefined because
1611 // we do not know what return values are valid.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001612 markOverdefined(&I);
Eli Friedman1815b682011-09-20 23:28:51 +00001613 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001614 default:
1615 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001616 // overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001617 markOverdefined(&I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001618 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001619 }
1620 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001621
Chris Lattneradca6082010-04-05 22:14:48 +00001622 // Check to see if we have a branch or switch on an undefined value. If so
1623 // we force the branch to go one way or the other to make the successor
1624 // values live. It doesn't really matter which way we force it.
Chandler Carruthedb12a82018-10-15 10:04:59 +00001625 Instruction *TI = BB.getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +00001626 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneraf170962006-10-22 05:59:17 +00001627 if (!BI->isConditional()) continue;
Davide Italiano0f03ce02016-07-10 00:35:15 +00001628 if (!getValueState(BI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001629 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001630
Chris Lattneradca6082010-04-05 22:14:48 +00001631 // If the input to SCCP is actually branch on undef, fix the undef to
1632 // false.
1633 if (isa<UndefValue>(BI->getCondition())) {
1634 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Benjamin Kramer135f7352016-06-26 12:28:59 +00001635 markEdgeExecutable(&BB, TI->getSuccessor(1));
Chris Lattneradca6082010-04-05 22:14:48 +00001636 return true;
1637 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001638
Chris Lattneradca6082010-04-05 22:14:48 +00001639 // Otherwise, it is a branch on a symbolic value which is currently
Eli Friedmana3c78f52018-07-19 23:02:07 +00001640 // considered to be undef. Make sure some edge is executable, so a
1641 // branch on "undef" always flows somewhere.
1642 // FIXME: Distinguish between dead code and an LLVM "undef" value.
1643 BasicBlock *DefaultSuccessor = TI->getSuccessor(1);
1644 if (markEdgeExecutable(&BB, DefaultSuccessor))
1645 return true;
1646
1647 continue;
Chris Lattneradca6082010-04-05 22:14:48 +00001648 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001649
Xin Tong34888c02017-04-10 00:33:25 +00001650 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1651 // Indirect branch with no successor ?. Its ok to assume it branches
1652 // to no target.
1653 if (IBR->getNumSuccessors() < 1)
1654 continue;
1655
1656 if (!getValueState(IBR->getAddress()).isUnknown())
1657 continue;
1658
1659 // If the input to SCCP is actually branch on undef, fix the undef to
1660 // the first successor of the indirect branch.
1661 if (isa<UndefValue>(IBR->getAddress())) {
1662 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1663 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1664 return true;
1665 }
1666
1667 // Otherwise, it is a branch on a symbolic value which is currently
Eli Friedmana3c78f52018-07-19 23:02:07 +00001668 // considered to be undef. Make sure some edge is executable, so a
1669 // branch on "undef" always flows somewhere.
1670 // FIXME: IndirectBr on "undef" doesn't actually need to go anywhere:
1671 // we can assume the branch has undefined behavior instead.
1672 BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1673 if (markEdgeExecutable(&BB, DefaultSuccessor))
1674 return true;
1675
1676 continue;
Xin Tong34888c02017-04-10 00:33:25 +00001677 }
1678
Davide Italianoe3bdd612016-12-01 08:36:12 +00001679 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Davide Italiano094dadd2016-07-15 18:33:16 +00001680 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001681 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001682
Chris Lattneradca6082010-04-05 22:14:48 +00001683 // If the input to SCCP is actually switch on undef, fix the undef to
1684 // the first constant.
1685 if (isa<UndefValue>(SI->getCondition())) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00001686 SI->setCondition(SI->case_begin()->getCaseValue());
1687 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001688 return true;
1689 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001690
Eli Friedmana3c78f52018-07-19 23:02:07 +00001691 // Otherwise, it is a branch on a symbolic value which is currently
1692 // considered to be undef. Make sure some edge is executable, so a
1693 // branch on "undef" always flows somewhere.
1694 // FIXME: Distinguish between dead code and an LLVM "undef" value.
1695 BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1696 if (markEdgeExecutable(&BB, DefaultSuccessor))
1697 return true;
1698
1699 continue;
Chris Lattner7285f432004-12-10 20:41:50 +00001700 }
Chris Lattneraf170962006-10-22 05:59:17 +00001701 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001702
Chris Lattneraf170962006-10-22 05:59:17 +00001703 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001704}
1705
Davide Italiano6f735882016-07-14 20:25:54 +00001706static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
Davide Italiano296e9782016-07-13 23:20:04 +00001707 Constant *Const = nullptr;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001708 if (V->getType()->isStructTy()) {
1709 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
Eugene Zelenko99241d72017-10-20 21:47:29 +00001710 if (llvm::any_of(IVs,
1711 [](const LatticeVal &LV) { return LV.isOverdefined(); }))
Davide Italiano296e9782016-07-13 23:20:04 +00001712 return false;
1713 std::vector<Constant *> ConstVals;
Davide Italianoe3bdd612016-12-01 08:36:12 +00001714 auto *ST = dyn_cast<StructType>(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001715 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1716 LatticeVal V = IVs[i];
1717 ConstVals.push_back(V.isConstant()
1718 ? V.getConstant()
1719 : UndefValue::get(ST->getElementType(i)));
1720 }
1721 Const = ConstantStruct::get(ST, ConstVals);
1722 } else {
Florian Hahn0a560d52018-07-20 13:29:12 +00001723 const LatticeVal &IV = Solver.getLatticeValueFor(V);
Davide Italiano296e9782016-07-13 23:20:04 +00001724 if (IV.isOverdefined())
1725 return false;
Florian Hahnd0208b42017-10-30 10:07:42 +00001726
Florian Hahn0a560d52018-07-20 13:29:12 +00001727 Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001728 }
1729 assert(Const && "Constant is nullptr here!");
Reid Kleckner3762a082018-03-01 01:19:18 +00001730
1731 // Replacing `musttail` instructions with constant breaks `musttail` invariant
1732 // unless the call itself can be removed
1733 CallInst *CI = dyn_cast<CallInst>(V);
1734 if (CI && CI->isMustTailCall() && !CI->isSafeToRemove()) {
1735 CallSite CS(CI);
1736 Function *F = CS.getCalledFunction();
1737
1738 // Don't zap returns of the callee
1739 if (F)
1740 Solver.AddMustTailCallee(F);
1741
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001742 LLVM_DEBUG(dbgs() << " Can\'t treat the result of musttail call : " << *CI
1743 << " as a constant\n");
Reid Kleckner3762a082018-03-01 01:19:18 +00001744 return false;
1745 }
1746
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001747 LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
Davide Italiano296e9782016-07-13 23:20:04 +00001748
1749 // Replaces all of the uses of a variable with uses of the constant.
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001750 V->replaceAllUsesWith(Const);
Davide Italiano6ed6d772016-07-14 01:27:29 +00001751 return true;
1752}
1753
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001754// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner074be1f2004-11-15 04:44:20 +00001755// and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001756static bool runSCCP(Function &F, const DataLayout &DL,
1757 const TargetLibraryInfo *TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001758 LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001759 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001760
1761 // Mark the first block of the function as being executable.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001762 Solver.MarkBlockExecutable(&F.front());
Chris Lattner074be1f2004-11-15 04:44:20 +00001763
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001764 // Mark all arguments to the function as being overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001765 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001766 Solver.markOverdefined(&AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001767
Chris Lattner074be1f2004-11-15 04:44:20 +00001768 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001769 bool ResolvedUndefs = true;
1770 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001771 Solver.Solve();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001772 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001773 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001774 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001775
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001776 bool MadeChanges = false;
1777
1778 // If we decided that there are basic blocks that are dead in this function,
1779 // delete their contents now. Note that we cannot actually delete the blocks,
1780 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001781
Benjamin Kramer135f7352016-06-26 12:28:59 +00001782 for (BasicBlock &BB : F) {
1783 if (!Solver.isBlockExecutable(&BB)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001784 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << BB);
David Majnemer88542a02016-01-24 06:26:47 +00001785
1786 ++NumDeadBlocks;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001787 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer88542a02016-01-24 06:26:47 +00001788
Chris Lattnere405ed92009-11-02 02:47:51 +00001789 MadeChanges = true;
1790 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001791 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001792
Chris Lattnere405ed92009-11-02 02:47:51 +00001793 // Iterate over all of the instructions in a function, replacing them with
1794 // constants if we have found them to be of constant values.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001795 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001796 Instruction *Inst = &*BI++;
Chandler Carruth9ae926b2018-08-26 09:51:22 +00001797 if (Inst->getType()->isVoidTy() || Inst->isTerminator())
Chris Lattnere405ed92009-11-02 02:47:51 +00001798 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001799
Sanjoy Dasff855b62016-08-24 18:10:21 +00001800 if (tryToReplaceWithConstant(Solver, Inst)) {
1801 if (isInstructionTriviallyDead(Inst))
1802 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001803 // Hey, we just changed something!
1804 MadeChanges = true;
1805 ++NumInstRemoved;
Davide Italiano00802692016-07-12 19:54:19 +00001806 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001807 }
1808 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001809
1810 return MadeChanges;
1811}
Chris Lattnerb4394642004-12-10 08:02:06 +00001812
Sean Silva36e0d012016-08-09 00:28:15 +00001813PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001814 const DataLayout &DL = F.getParent()->getDataLayout();
1815 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1816 if (!runSCCP(F, DL, &TLI))
1817 return PreservedAnalyses::all();
Davide Italiano484b5ab2016-05-29 00:31:15 +00001818
1819 auto PA = PreservedAnalyses();
1820 PA.preserve<GlobalsAA>();
Florian Hahn388af142018-06-28 09:53:38 +00001821 PA.preserveSet<CFGAnalyses>();
Davide Italiano484b5ab2016-05-29 00:31:15 +00001822 return PA;
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001823}
1824
1825namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +00001826
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001827//===--------------------------------------------------------------------===//
1828//
1829/// SCCP Class - This class uses the SCCPSolver to implement a per-function
1830/// Sparse Conditional Constant Propagator.
1831///
Davide Italiano46f249b2016-05-19 15:58:02 +00001832class SCCPLegacyPass : public FunctionPass {
1833public:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001834 // Pass identification, replacement for typeid
1835 static char ID;
1836
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001837 SCCPLegacyPass() : FunctionPass(ID) {
1838 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1839 }
1840
Eugene Zelenko99241d72017-10-20 21:47:29 +00001841 void getAnalysisUsage(AnalysisUsage &AU) const override {
1842 AU.addRequired<TargetLibraryInfoWrapperPass>();
1843 AU.addPreserved<GlobalsAAWrapperPass>();
Florian Hahn388af142018-06-28 09:53:38 +00001844 AU.setPreservesCFG();
Eugene Zelenko99241d72017-10-20 21:47:29 +00001845 }
1846
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001847 // runOnFunction - Run the Sparse Conditional Constant Propagation
1848 // algorithm, and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001849 bool runOnFunction(Function &F) override {
1850 if (skipFunction(F))
1851 return false;
1852 const DataLayout &DL = F.getParent()->getDataLayout();
1853 const TargetLibraryInfo *TLI =
1854 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1855 return runSCCP(F, DL, TLI);
1856 }
1857};
Eugene Zelenko99241d72017-10-20 21:47:29 +00001858
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001859} // end anonymous namespace
1860
1861char SCCPLegacyPass::ID = 0;
Eugene Zelenko99241d72017-10-20 21:47:29 +00001862
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001863INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1864 "Sparse Conditional Constant Propagation", false, false)
1865INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1866INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1867 "Sparse Conditional Constant Propagation", false, false)
1868
1869// createSCCPPass - This is the public interface to this file.
1870FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1871
Davide Italiano15ff2d62016-07-20 20:17:13 +00001872static void findReturnsToZap(Function &F,
Matthew Simpson22849372017-10-13 17:53:44 +00001873 SmallVector<ReturnInst *, 8> &ReturnsToZap,
1874 SCCPSolver &Solver) {
Davide Italiano15ff2d62016-07-20 20:17:13 +00001875 // We can only do this if we know that nothing else can call the function.
Matthew Simpson22849372017-10-13 17:53:44 +00001876 if (!Solver.isArgumentTrackedFunction(&F))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001877 return;
1878
Reid Kleckner3762a082018-03-01 01:19:18 +00001879 // There is a non-removable musttail call site of this function. Zapping
1880 // returns is not allowed.
1881 if (Solver.isMustTailCallee(&F)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001882 LLVM_DEBUG(dbgs() << "Can't zap returns of the function : " << F.getName()
1883 << " due to present musttail call of it\n");
Reid Kleckner3762a082018-03-01 01:19:18 +00001884 return;
1885 }
1886
1887 for (BasicBlock &BB : F) {
1888 if (CallInst *CI = BB.getTerminatingMustTailCall()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001889 LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "
1890 << "musttail call : " << *CI << "\n");
Benjamin Kramerd1cf7ff2018-03-01 11:31:44 +00001891 (void)CI;
Reid Kleckner3762a082018-03-01 01:19:18 +00001892 return;
1893 }
1894
Davide Italianoe3bdd612016-12-01 08:36:12 +00001895 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001896 if (!isa<UndefValue>(RI->getOperand(0)))
1897 ReturnsToZap.push_back(RI);
Reid Kleckner3762a082018-03-01 01:19:18 +00001898 }
Davide Italiano15ff2d62016-07-20 20:17:13 +00001899}
1900
Bjorn Petterssoncd53b7f2018-09-20 09:00:17 +00001901// Update the condition for terminators that are branching on indeterminate
1902// values, forcing them to use a specific edge.
1903static void forceIndeterminateEdge(Instruction* I, SCCPSolver &Solver) {
1904 BasicBlock *Dest = nullptr;
1905 Constant *C = nullptr;
1906 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1907 if (!isa<ConstantInt>(SI->getCondition())) {
1908 // Indeterminate switch; use first case value.
1909 Dest = SI->case_begin()->getCaseSuccessor();
1910 C = SI->case_begin()->getCaseValue();
1911 }
1912 } else if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1913 if (!isa<ConstantInt>(BI->getCondition())) {
1914 // Indeterminate branch; use false.
1915 Dest = BI->getSuccessor(1);
1916 C = ConstantInt::getFalse(BI->getContext());
1917 }
1918 } else if (IndirectBrInst *IBR = dyn_cast<IndirectBrInst>(I)) {
1919 if (!isa<BlockAddress>(IBR->getAddress()->stripPointerCasts())) {
1920 // Indeterminate indirectbr; use successor 0.
1921 Dest = IBR->getSuccessor(0);
1922 C = BlockAddress::get(IBR->getSuccessor(0));
1923 }
1924 } else {
1925 llvm_unreachable("Unexpected terminator instruction");
1926 }
1927 if (C) {
1928 assert(Solver.isEdgeFeasible(I->getParent(), Dest) &&
1929 "Didn't find feasible edge?");
1930 (void)Dest;
1931
1932 I->setOperand(0, C);
1933 }
1934}
1935
Florian Hahn30522902018-08-23 11:04:00 +00001936bool llvm::runIPSCCP(
1937 Module &M, const DataLayout &DL, const TargetLibraryInfo *TLI,
Florian Hahna1062f42018-11-09 11:52:27 +00001938 function_ref<AnalysisResultsForFn(Function &)> getAnalysis) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001939 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001940
1941 // Loop over all functions, marking arguments to those with their addresses
1942 // taken or that are external as overdefined.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001943 for (Function &F : M) {
1944 if (F.isDeclaration())
Chris Lattner47837c52009-11-02 06:34:04 +00001945 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001946
Florian Hahna1062f42018-11-09 11:52:27 +00001947 Solver.addAnalysis(F, getAnalysis(F));
1948
Matthew Simpson22849372017-10-13 17:53:44 +00001949 // Determine if we can track the function's return values. If so, add the
1950 // function to the solver's set of return-tracked functions.
1951 if (canTrackReturnsInterprocedurally(&F))
Davide Italianoe7c56c52016-05-14 20:59:09 +00001952 Solver.AddTrackedFunction(&F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001953
Matthew Simpson22849372017-10-13 17:53:44 +00001954 // Determine if we can track the function's arguments. If so, add the
1955 // function to the solver's set of argument-tracked functions.
1956 if (canTrackArgumentsInterprocedurally(&F)) {
1957 Solver.AddArgumentTrackedFunction(&F);
1958 continue;
Chris Lattnercde8de52009-11-03 19:24:51 +00001959 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001960
1961 // Assume the function is called.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001962 Solver.MarkBlockExecutable(&F.front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001963
Chris Lattnerfb141812009-11-03 03:42:51 +00001964 // Assume nothing about the incoming arguments.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001965 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001966 Solver.markOverdefined(&AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001967 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001968
Matthew Simpson22849372017-10-13 17:53:44 +00001969 // Determine if we can track any of the module's global variables. If so, add
1970 // the global variables we can track to the solver's set of tracked global
1971 // variables.
1972 for (GlobalVariable &G : M.globals()) {
1973 G.removeDeadConstantUsers();
1974 if (canTrackGlobalVariableInterprocedurally(&G))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001975 Solver.TrackValueOfGlobalVariable(&G);
Matthew Simpson22849372017-10-13 17:53:44 +00001976 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001977
Chris Lattnerb4394642004-12-10 08:02:06 +00001978 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001979 bool ResolvedUndefs = true;
Florian Hahnd95761d2018-07-17 14:04:59 +00001980 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001981 while (ResolvedUndefs) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001982 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001983 ResolvedUndefs = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001984 for (Function &F : M)
Florian Hahnd95761d2018-07-17 14:04:59 +00001985 if (Solver.ResolvedUndefsIn(F)) {
1986 // We run Solve() after we resolved an undef in a function, because
1987 // we might deduce a fact that eliminates an undef in another function.
1988 Solver.Solve();
1989 ResolvedUndefs = true;
1990 }
Chris Lattner7285f432004-12-10 20:41:50 +00001991 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001992
1993 bool MadeChanges = false;
1994
1995 // Iterate over all of the instructions in the module, replacing them with
1996 // constants if we have found them to be of constant values.
Chris Lattner37d400a2007-02-02 21:15:06 +00001997
Benjamin Kramer135f7352016-06-26 12:28:59 +00001998 for (Function &F : M) {
1999 if (F.isDeclaration())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002000 continue;
2001
Florian Hahna1062f42018-11-09 11:52:27 +00002002 SmallVector<BasicBlock *, 512> BlocksToErase;
2003
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00002004 if (Solver.isBlockExecutable(&F.front()))
Benjamin Kramer135f7352016-06-26 12:28:59 +00002005 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
Florian Hahnd0208b42017-10-30 10:07:42 +00002006 ++AI) {
Davide Italiano5df80802017-11-21 00:21:52 +00002007 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) {
Davide Italiano6ed6d772016-07-14 01:27:29 +00002008 ++IPNumArgsElimed;
Davide Italiano5df80802017-11-21 00:21:52 +00002009 continue;
2010 }
Florian Hahnd0208b42017-10-30 10:07:42 +00002011 }
2012
Benjamin Kramer135f7352016-06-26 12:28:59 +00002013 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002014 if (!Solver.isBlockExecutable(&*BB)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002015 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
David Majnemer88542a02016-01-24 06:26:47 +00002016 ++NumDeadBlocks;
David Majnemer88542a02016-01-24 06:26:47 +00002017
2018 MadeChanges = true;
Chris Lattnerbae4b642004-12-10 22:29:08 +00002019
Benjamin Kramer135f7352016-06-26 12:28:59 +00002020 if (&*BB != &F.front())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002021 BlocksToErase.push_back(&*BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00002022 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00002023 }
Jakub Staszak632a3552012-01-18 21:16:33 +00002024
Chris Lattnere405ed92009-11-02 02:47:51 +00002025 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002026 Instruction *Inst = &*BI++;
Davide Italiano7dac0272016-07-14 02:51:41 +00002027 if (Inst->getType()->isVoidTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00002028 continue;
Sanjoy Dasff855b62016-08-24 18:10:21 +00002029 if (tryToReplaceWithConstant(Solver, Inst)) {
Chris Bienemanabdea262018-01-09 21:58:46 +00002030 if (Inst->isSafeToRemove())
Sanjoy Dasff855b62016-08-24 18:10:21 +00002031 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00002032 // Hey, we just changed something!
2033 MadeChanges = true;
2034 ++IPNumInstRemoved;
2035 }
Chris Lattnere405ed92009-11-02 02:47:51 +00002036 }
2037 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00002038
Florian Hahn9026d4e2018-11-11 20:22:45 +00002039 DomTreeUpdater DTU = Solver.getDTU(F);
Florian Hahna1062f42018-11-09 11:52:27 +00002040 // Change dead blocks to unreachable. We do it after replacing constants
2041 // in all executable blocks, because changeToUnreachable may remove PHI
2042 // nodes in executable blocks we found values for. The function's entry
2043 // block is not part of BlocksToErase, so we have to handle it separately.
2044 for (BasicBlock *BB : BlocksToErase) {
Florian Hahn4a69b0b2018-06-26 10:15:02 +00002045 NumInstRemoved +=
Florian Hahna1062f42018-11-09 11:52:27 +00002046 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false,
2047 /*PreserveLCSSA=*/false, &DTU);
2048 }
Florian Hahn4a69b0b2018-06-26 10:15:02 +00002049 if (!Solver.isBlockExecutable(&F.front()))
2050 NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
Florian Hahna1062f42018-11-09 11:52:27 +00002051 /*UseLLVMTrap=*/false,
2052 /*PreserveLCSSA=*/false, &DTU);
Florian Hahn4a69b0b2018-06-26 10:15:02 +00002053
Florian Hahna1062f42018-11-09 11:52:27 +00002054 // Now that all instructions in the function are constant folded,
2055 // use ConstantFoldTerminator to get rid of in-edges, record DT updates and
2056 // delete dead BBs.
2057 for (BasicBlock *DeadBB : BlocksToErase) {
Chris Lattnerbae4b642004-12-10 22:29:08 +00002058 // If there are any PHI nodes in this successor, drop entries for BB now.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002059 for (Value::user_iterator UI = DeadBB->user_begin(),
2060 UE = DeadBB->user_end();
2061 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00002062 // Grab the user and then increment the iterator early, as the user
2063 // will be deleted. Step past all adjacent uses from the same user.
Davide Italianoe3bdd612016-12-01 08:36:12 +00002064 auto *I = dyn_cast<Instruction>(*UI);
Dan Gohman1f522d92009-11-23 16:13:39 +00002065 do { ++UI; } while (UI != UE && *UI == I);
2066
Dan Gohmand15302a2009-11-20 20:19:14 +00002067 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00002068 if (!I) continue;
2069
Bjorn Petterssoncd53b7f2018-09-20 09:00:17 +00002070 // If we have forced an edge for an indeterminate value, then force the
2071 // terminator to fold to that edge.
2072 forceIndeterminateEdge(I, Solver);
Florian Hahna1062f42018-11-09 11:52:27 +00002073 bool Folded = ConstantFoldTerminator(I->getParent(),
2074 /*DeleteDeadConditions=*/false,
2075 /*TLI=*/nullptr, &DTU);
Davide Italianoe15bffe2018-01-07 22:09:44 +00002076 assert(Folded &&
2077 "Expect TermInst on constantint or blockaddress to be folded");
2078 (void) Folded;
Chris Lattnerbae4b642004-12-10 22:29:08 +00002079 }
Florian Hahna1062f42018-11-09 11:52:27 +00002080 // Mark dead BB for deletion.
2081 DTU.deleteBB(DeadBB);
Chris Lattnerbae4b642004-12-10 22:29:08 +00002082 }
Florian Hahn30522902018-08-23 11:04:00 +00002083
2084 for (BasicBlock &BB : F) {
2085 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
2086 Instruction *Inst = &*BI++;
Florian Hahn17e7ace2018-08-23 11:17:59 +00002087 if (Solver.getPredicateInfoFor(Inst)) {
Florian Hahn30522902018-08-23 11:04:00 +00002088 if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
2089 if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
2090 Value *Op = II->getOperand(0);
2091 Inst->replaceAllUsesWith(Op);
2092 Inst->eraseFromParent();
2093 }
2094 }
2095 }
2096 }
2097 }
Chris Lattnerb4394642004-12-10 08:02:06 +00002098 }
Chris Lattner99e12952004-12-11 02:53:57 +00002099
2100 // If we inferred constant or undef return values for a function, we replaced
2101 // all call uses with the inferred value. This means we don't need to bother
2102 // actually returning anything from the function. Replace all return
2103 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00002104 //
2105 // Do this in two stages: first identify the functions we should process, then
2106 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00002107 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00002108 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00002109 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00002110 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00002111
Devang Patela7a20752008-03-11 05:46:42 +00002112 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Benjamin Kramer135f7352016-06-26 12:28:59 +00002113 for (const auto &I : RV) {
2114 Function *F = I.first;
2115 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
Chris Lattnerfb141812009-11-03 03:42:51 +00002116 continue;
Matthew Simpson22849372017-10-13 17:53:44 +00002117 findReturnsToZap(*F, ReturnsToZap, Solver);
Davide Italiano15ff2d62016-07-20 20:17:13 +00002118 }
Jakub Staszak632a3552012-01-18 21:16:33 +00002119
Davide Italiano15ff2d62016-07-20 20:17:13 +00002120 for (const auto &F : Solver.getMRVFunctionsTracked()) {
2121 assert(F->getReturnType()->isStructTy() &&
2122 "The return type should be a struct");
2123 StructType *STy = cast<StructType>(F->getReturnType());
2124 if (Solver.isStructLatticeConstant(F, STy))
Matthew Simpson22849372017-10-13 17:53:44 +00002125 findReturnsToZap(*F, ReturnsToZap, Solver);
Chris Lattnerd887f1d2010-02-27 00:07:42 +00002126 }
2127
2128 // Zap all returns which we've identified as zap to change.
2129 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
2130 Function *F = ReturnsToZap[i]->getParent()->getParent();
2131 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00002132 }
Jakub Staszak632a3552012-01-18 21:16:33 +00002133
Chad Rosierbb2a6da2012-03-28 00:35:33 +00002134 // If we inferred constant or undef values for globals variables, we can
2135 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00002136 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2137 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00002138 E = TG.end(); I != E; ++I) {
2139 GlobalVariable *GV = I->first;
2140 assert(!I->second.isOverdefined() &&
2141 "Overdefined values should have been taken out of the map!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002142 LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
2143 << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00002144 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002145 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00002146 SI->eraseFromParent();
2147 }
2148 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00002149 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00002150 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002151
Chris Lattnerb4394642004-12-10 08:02:06 +00002152 return MadeChanges;
2153}