blob: 345b030ddc12cbafff7e85aa1adacd9bfdb424f6 [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"
Eugene Zelenko99241d72017-10-20 21:47:29 +000058#include <cassert>
59#include <utility>
60#include <vector>
61
Chris Lattner49525f82004-01-09 06:02:20 +000062using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000063
Chandler Carruth964daaa2014-04-22 02:55:47 +000064#define DEBUG_TYPE "sccp"
65
Chris Lattner79a42ac2006-12-19 21:40:18 +000066STATISTIC(NumInstRemoved, "Number of instructions removed");
67STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
68
Nick Lewycky35e92c72008-03-08 07:48:41 +000069STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000070STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
71STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
Florian Hahnf73c3ec2018-03-23 12:49:39 +000072STATISTIC(IPNumRangeInfoUsed, "Number of times constant range info was used by"
73 "IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000074
Chris Lattner7d325382002-04-29 21:26:08 +000075namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +000076
Chris Lattner1847f6d2006-12-20 06:21:33 +000077/// LatticeVal class - This class represents the different lattice values that
78/// an LLVM value may occupy. It is a simple class with value semantics.
79///
Chris Lattner2dd09db2009-09-02 06:11:42 +000080class LatticeVal {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000081 enum LatticeValueTy {
Davide Italiano0f03ce02016-07-10 00:35:15 +000082 /// unknown - This LLVM Value has no known value yet.
83 unknown,
Jakub Staszak632a3552012-01-18 21:16:33 +000084
Chris Lattner1847f6d2006-12-20 06:21:33 +000085 /// constant - This LLVM Value has a specific constant value.
86 constant,
87
88 /// forcedconstant - This LLVM Value was thought to be undef until
89 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
90 /// with another (different) constant, it goes to overdefined, instead of
91 /// asserting.
92 forcedconstant,
Jakub Staszak632a3552012-01-18 21:16:33 +000093
Chris Lattner1847f6d2006-12-20 06:21:33 +000094 /// overdefined - This instruction is not known to be constant, and we know
95 /// it has a value.
96 overdefined
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000097 };
98
99 /// Val: This stores the current lattice value along with the Constant* for
100 /// the constant if this is a 'constant' or 'forcedconstant' value.
101 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Jakub Staszak632a3552012-01-18 21:16:33 +0000102
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000103 LatticeValueTy getLatticeValue() const {
104 return Val.getInt();
105 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000106
Chris Lattner347389d2001-06-27 23:38:11 +0000107public:
Davide Italiano0f03ce02016-07-10 00:35:15 +0000108 LatticeVal() : Val(nullptr, unknown) {}
Jakub Staszak632a3552012-01-18 21:16:33 +0000109
Davide Italiano0f03ce02016-07-10 00:35:15 +0000110 bool isUnknown() const { return getLatticeValue() == unknown; }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000111
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000112 bool isConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000113 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
114 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000115
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000116 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Jakub Staszak632a3552012-01-18 21:16:33 +0000117
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000118 Constant *getConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000119 assert(isConstant() && "Cannot get the constant of a non-constant!");
120 return Val.getPointer();
121 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000122
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000123 /// markOverdefined - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000124 bool markOverdefined() {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000125 if (isOverdefined())
126 return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000127
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000128 Val.setInt(overdefined);
129 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000130 }
131
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000132 /// markConstant - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000133 bool markConstant(Constant *V) {
Chris Lattnere1d5cd92009-11-03 16:50:11 +0000134 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000135 assert(getConstant() == V && "Marking constant with different value");
136 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000137 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000138
Davide Italiano0f03ce02016-07-10 00:35:15 +0000139 if (isUnknown()) {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000140 Val.setInt(constant);
141 assert(V && "Marking constant with NULL");
142 Val.setPointer(V);
143 } else {
Jakub Staszak632a3552012-01-18 21:16:33 +0000144 assert(getLatticeValue() == forcedconstant &&
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000145 "Cannot move from overdefined to constant!");
146 // Stay at forcedconstant if the constant is the same.
147 if (V == getConstant()) return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000148
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000149 // Otherwise, we go to overdefined. Assumptions made based on the
150 // forced value are possibly wrong. Assuming this is another constant
151 // could expose a contradiction.
152 Val.setInt(overdefined);
153 }
154 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000155 }
156
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000157 /// getConstantInt - If this is a constant with a ConstantInt value, return it
158 /// otherwise return null.
159 ConstantInt *getConstantInt() const {
160 if (isConstant())
161 return dyn_cast<ConstantInt>(getConstant());
Craig Topperf40110f2014-04-25 05:29:35 +0000162 return nullptr;
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000163 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000164
Xin Tong34888c02017-04-10 00:33:25 +0000165 /// getBlockAddress - If this is a constant with a BlockAddress value, return
166 /// it, otherwise return null.
167 BlockAddress *getBlockAddress() const {
168 if (isConstant())
169 return dyn_cast<BlockAddress>(getConstant());
170 return nullptr;
171 }
172
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000173 void markForcedConstant(Constant *V) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000174 assert(isUnknown() && "Can't force a defined value!");
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000175 Val.setInt(forcedconstant);
176 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000177 }
Florian Hahnd0208b42017-10-30 10:07:42 +0000178
179 ValueLatticeElement toValueLattice() const {
180 if (isOverdefined())
181 return ValueLatticeElement::getOverdefined();
182 if (isConstant())
183 return ValueLatticeElement::get(getConstant());
184 return ValueLatticeElement();
185 }
Chris Lattner347389d2001-06-27 23:38:11 +0000186};
187
Chris Lattner347389d2001-06-27 23:38:11 +0000188//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000189//
Chris Lattner074be1f2004-11-15 04:44:20 +0000190/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
191/// Constant Propagation.
192///
193class SCCPSolver : public InstVisitor<SCCPSolver> {
Mehdi Amini46a43552015-03-04 18:43:29 +0000194 const DataLayout &DL;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000195 const TargetLibraryInfo *TLI;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000196 SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
197 DenseMap<Value *, LatticeVal> ValueState; // The state each value is in.
Florian Hahnd0208b42017-10-30 10:07:42 +0000198 // The state each parameter is in.
199 DenseMap<Value *, ValueLatticeElement> ParamState;
Chris Lattner347389d2001-06-27 23:38:11 +0000200
Chris Lattner156b8c72009-11-03 23:40:48 +0000201 /// StructValueState - This maintains ValueState for values that have
202 /// StructType, for example for formal arguments, calls, insertelement, etc.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000203 DenseMap<std::pair<Value *, unsigned>, LatticeVal> StructValueState;
Jakub Staszak632a3552012-01-18 21:16:33 +0000204
Chris Lattner91dbae62004-12-11 05:15:59 +0000205 /// GlobalValue - If we are tracking any values for the contents of a global
206 /// variable, we keep a mapping from the constant accessor to the element of
207 /// the global, to the currently known value. If the value becomes
208 /// overdefined, it's entry is simply removed from this map.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000209 DenseMap<GlobalVariable *, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000210
Devang Patela7a20752008-03-11 05:46:42 +0000211 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000212 /// value out of a function, it will have an entry in this map, indicating
213 /// what the known return value for the function is.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000214 DenseMap<Function *, LatticeVal> TrackedRetVals;
Devang Patela7a20752008-03-11 05:46:42 +0000215
216 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
217 /// that return multiple values.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000218 DenseMap<std::pair<Function *, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak632a3552012-01-18 21:16:33 +0000219
Chris Lattner156b8c72009-11-03 23:40:48 +0000220 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
221 /// represented here for efficient lookup.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000222 SmallPtrSet<Function *, 16> MRVFunctionsTracked;
Chris Lattnerb4394642004-12-10 08:02:06 +0000223
Reid Kleckner3762a082018-03-01 01:19:18 +0000224 /// MustTailFunctions - Each function here is a callee of non-removable
225 /// musttail call site.
226 SmallPtrSet<Function *, 16> MustTailCallees;
227
Chris Lattner2c427232009-11-03 20:52:57 +0000228 /// TrackingIncomingArguments - This is the set of functions for whose
229 /// arguments we make optimistic assumptions about and try to prove as
230 /// constants.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000231 SmallPtrSet<Function *, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000232
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000233 /// The reason for two worklists is that overdefined is the lowest state
234 /// on the lattice, and moving things to overdefined as fast as possible
235 /// makes SCCP converge much faster.
236 ///
237 /// By having a separate worklist, we accomplish this because everything
238 /// possibly overdefined will become overdefined at the soonest possible
239 /// point.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000240 SmallVector<Value *, 64> OverdefinedInstWorkList;
241 SmallVector<Value *, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000242
Eugene Zelenko99241d72017-10-20 21:47:29 +0000243 // The BasicBlock work list
244 SmallVector<BasicBlock *, 64> BBWorkList;
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000245
246 /// KnownFeasibleEdges - Entries in this set are edges which have already had
247 /// PHI nodes retriggered.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000248 using Edge = std::pair<BasicBlock *, BasicBlock *>;
Chris Lattner65938fc2008-08-23 23:36:38 +0000249 DenseSet<Edge> KnownFeasibleEdges;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000250
Chris Lattner347389d2001-06-27 23:38:11 +0000251public:
Mehdi Amini46a43552015-03-04 18:43:29 +0000252 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
253 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000254
Chris Lattner074be1f2004-11-15 04:44:20 +0000255 /// MarkBlockExecutable - This method can be used by clients to mark all of
256 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000257 ///
258 /// This returns true if the block was not considered live before.
259 bool MarkBlockExecutable(BasicBlock *BB) {
David Blaikie70573dc2014-11-19 07:49:26 +0000260 if (!BBExecutable.insert(BB).second)
261 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000262 LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000263 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000264 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000265 }
266
Chris Lattner91dbae62004-12-11 05:15:59 +0000267 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000268 /// inform the SCCPSolver that it should track loads and stores to the
269 /// specified global variable if it can. This is only legal to call if
270 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000271 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000272 // We only track the contents of scalar globals.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000273 if (GV->getValueType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000274 LatticeVal &IV = TrackedGlobals[GV];
275 if (!isa<UndefValue>(GV->getInitializer()))
276 IV.markConstant(GV->getInitializer());
277 }
278 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000279
280 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
281 /// and out of the specified function (which cannot have its address taken),
282 /// this method must be called.
283 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000284 // Add an entry, F -> undef.
Davide Italianoe3bdd612016-12-01 08:36:12 +0000285 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000286 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000287 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000288 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
289 LatticeVal()));
290 } else
291 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000292 }
293
Reid Kleckner3762a082018-03-01 01:19:18 +0000294 /// AddMustTailCallee - If the SCCP solver finds that this function is called
295 /// from non-removable musttail call site.
296 void AddMustTailCallee(Function *F) {
297 MustTailCallees.insert(F);
298 }
299
300 /// Returns true if the given function is called from non-removable musttail
301 /// call site.
302 bool isMustTailCallee(Function *F) {
303 return MustTailCallees.count(F);
304 }
305
Chris Lattnercde8de52009-11-03 19:24:51 +0000306 void AddArgumentTrackedFunction(Function *F) {
307 TrackingIncomingArguments.insert(F);
308 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000309
Matthew Simpson22849372017-10-13 17:53:44 +0000310 /// Returns true if the given function is in the solver's set of
311 /// argument-tracked functions.
312 bool isArgumentTrackedFunction(Function *F) {
313 return TrackingIncomingArguments.count(F);
314 }
315
Chris Lattner074be1f2004-11-15 04:44:20 +0000316 /// Solve - Solve for constants and executable blocks.
Chris Lattner074be1f2004-11-15 04:44:20 +0000317 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000318
Chris Lattner1847f6d2006-12-20 06:21:33 +0000319 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000320 /// that branches on undef values cannot reach any of their successors.
321 /// However, this is not a safe assumption. After we solve dataflow, this
322 /// method should be use to handle this. If this returns true, the solver
323 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000324 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000325
Chris Lattneradd44f32008-08-23 23:39:31 +0000326 bool isBlockExecutable(BasicBlock *BB) const {
327 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000328 }
329
Davide Italiano00802692016-07-12 19:54:19 +0000330 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
331 std::vector<LatticeVal> StructValues;
Davide Italianoe3bdd612016-12-01 08:36:12 +0000332 auto *STy = dyn_cast<StructType>(V->getType());
Davide Italiano00802692016-07-12 19:54:19 +0000333 assert(STy && "getStructLatticeValueFor() can be called only on structs");
334 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
335 auto I = StructValueState.find(std::make_pair(V, i));
336 assert(I != StructValueState.end() && "Value not in valuemap!");
337 StructValues.push_back(I->second);
338 }
339 return StructValues;
340 }
341
Florian Hahnd0208b42017-10-30 10:07:42 +0000342 ValueLatticeElement getLatticeValueFor(Value *V) {
343 assert(!V->getType()->isStructTy() &&
344 "Should use getStructLatticeValueFor");
345 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
346 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
347 ValueLatticeElement &LV = PI.first->second;
348 if (PI.second) {
349 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
350 assert(I != ValueState.end() &&
351 "V not found in ValueState nor Paramstate map!");
352 LV = I->second.toValueLattice();
353 }
354
355 return LV;
Chris Lattner074be1f2004-11-15 04:44:20 +0000356 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000357
Devang Patela7a20752008-03-11 05:46:42 +0000358 /// getTrackedRetVals - Get the inferred return value map.
Devang Patela7a20752008-03-11 05:46:42 +0000359 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
360 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000361 }
362
Chris Lattner91dbae62004-12-11 05:15:59 +0000363 /// getTrackedGlobals - Get and return the set of inferred initializers for
364 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000365 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000366 return TrackedGlobals;
367 }
368
Davide Italiano15ff2d62016-07-20 20:17:13 +0000369 /// getMRVFunctionsTracked - Get the set of functions which return multiple
370 /// values tracked by the pass.
371 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
372 return MRVFunctionsTracked;
373 }
374
Reid Kleckner3762a082018-03-01 01:19:18 +0000375 /// getMustTailCallees - Get the set of functions which are called
376 /// from non-removable musttail call sites.
377 const SmallPtrSet<Function *, 16> getMustTailCallees() {
378 return MustTailCallees;
379 }
380
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000381 /// markOverdefined - Mark the specified value overdefined. This
Chris Lattner156b8c72009-11-03 23:40:48 +0000382 /// works with both scalars and structs.
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000383 void markOverdefined(Value *V) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000384 if (auto *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000385 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
386 markOverdefined(getStructValueState(V, i), V);
387 else
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000388 markOverdefined(ValueState[V], V);
Chris Lattner156b8c72009-11-03 23:40:48 +0000389 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000390
Davide Italiano15ff2d62016-07-20 20:17:13 +0000391 // isStructLatticeConstant - Return true if all the lattice values
392 // corresponding to elements of the structure are not overdefined,
393 // false otherwise.
394 bool isStructLatticeConstant(Function *F, StructType *STy) {
395 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
396 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
397 assert(It != TrackedMultipleRetVals.end());
398 LatticeVal LV = It->second;
399 if (LV.isOverdefined())
400 return false;
401 }
402 return true;
403 }
404
Chris Lattner347389d2001-06-27 23:38:11 +0000405private:
Davide Italiano0a1476c2016-12-11 21:19:03 +0000406 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
Davide Italiano390b7ea2016-07-13 19:33:25 +0000407 void pushToWorkList(LatticeVal &IV, Value *V) {
408 if (IV.isOverdefined())
409 return OverdefinedInstWorkList.push_back(V);
410 InstWorkList.push_back(V);
411 }
412
Chris Lattnerd79334d2004-07-15 23:36:43 +0000413 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000414 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000415 // the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000416 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
417 if (!IV.markConstant(C)) return;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000418 LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000419 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000420 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000421
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000422 void markConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000423 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerb4394642004-12-10 08:02:06 +0000424 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000425 }
426
Chris Lattnerf5484032009-11-02 05:55:40 +0000427 void markForcedConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000428 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000429 LatticeVal &IV = ValueState[V];
430 IV.markForcedConstant(C);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000431 LLVM_DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000432 pushToWorkList(IV, V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000433 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000434
Chris Lattnerd79334d2004-07-15 23:36:43 +0000435 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000436 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000437 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000438 void markOverdefined(LatticeVal &IV, Value *V) {
439 if (!IV.markOverdefined()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000440
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000441 LLVM_DEBUG(dbgs() << "markOverdefined: ";
442 if (auto *F = dyn_cast<Function>(V)) dbgs()
443 << "Function '" << F->getName() << "'\n";
444 else dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000445 // Only instructions go on the work list
Davide Italiano0a1476c2016-12-11 21:19:03 +0000446 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000447 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000448
Chris Lattnerf5484032009-11-02 05:55:40 +0000449 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000450 if (IV.isOverdefined() || MergeWithV.isUnknown())
Chris Lattnerb4394642004-12-10 08:02:06 +0000451 return; // Noop.
452 if (MergeWithV.isOverdefined())
Davide Italiano21850012016-07-13 19:23:30 +0000453 return markOverdefined(IV, V);
454 if (IV.isUnknown())
455 return markConstant(IV, V, MergeWithV.getConstant());
456 if (IV.getConstant() != MergeWithV.getConstant())
457 return markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000458 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000459
Chris Lattnerf5484032009-11-02 05:55:40 +0000460 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Davide Italiano63266b62016-07-19 18:31:07 +0000461 assert(!V->getType()->isStructTy() &&
462 "non-structs should use markConstant");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000463 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000464 }
465
Chris Lattnerf5484032009-11-02 05:55:40 +0000466 /// getValueState - Return the LatticeVal object that corresponds to the
467 /// value. This function handles the case when the value hasn't been seen yet
468 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000469 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000470 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000471
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000472 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
473 ValueState.insert(std::make_pair(V, LatticeVal()));
474 LatticeVal &LV = I.first->second;
475
476 if (!I.second)
477 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000478
Davide Italianoe3bdd612016-12-01 08:36:12 +0000479 if (auto *C = dyn_cast<Constant>(V)) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000480 // Undef values remain unknown.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000481 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000482 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000483 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000484
Chris Lattnera3c39d32009-11-02 02:33:50 +0000485 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000486 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000487 }
488
Florian Hahnd0208b42017-10-30 10:07:42 +0000489 ValueLatticeElement &getParamState(Value *V) {
490 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
491
492 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
493 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
494 ValueLatticeElement &LV = PI.first->second;
495 if (PI.second)
496 LV = getValueState(V).toValueLattice();
497
498 return LV;
499 }
500
Chris Lattner156b8c72009-11-03 23:40:48 +0000501 /// getStructValueState - Return the LatticeVal object that corresponds to the
502 /// value/field pair. This function handles the case when the value hasn't
503 /// been seen yet by properly seeding constants etc.
504 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000505 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000506 assert(i < cast<StructType>(V->getType())->getNumElements() &&
507 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000508
509 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
510 bool> I = StructValueState.insert(
511 std::make_pair(std::make_pair(V, i), LatticeVal()));
512 LatticeVal &LV = I.first->second;
513
514 if (!I.second)
515 return LV; // Common case, already in the map.
516
Davide Italianoe3bdd612016-12-01 08:36:12 +0000517 if (auto *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000518 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000519
Craig Topperf40110f2014-04-25 05:29:35 +0000520 if (!Elt)
Chris Lattner156b8c72009-11-03 23:40:48 +0000521 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000522 else if (isa<UndefValue>(Elt))
Davide Italiano0f03ce02016-07-10 00:35:15 +0000523 ; // Undef values remain unknown.
Chris Lattnerfa775002012-01-26 02:32:04 +0000524 else
525 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000526 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000527
Chris Lattner156b8c72009-11-03 23:40:48 +0000528 // All others are underdefined by default.
529 return LV;
530 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000531
Chris Lattnerf5484032009-11-02 05:55:40 +0000532 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
533 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000534 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
535 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
536 return; // This edge is already known to be executable!
537
Chris Lattner809aee22009-11-02 06:11:23 +0000538 if (!MarkBlockExecutable(Dest)) {
539 // If the destination is already executable, we just made an *edge*
540 // feasible that wasn't before. Revisit the PHI nodes in the block
541 // because they have potentially new operands.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000542 LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
543 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000544
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000545 for (PHINode &PN : Dest->phis())
546 visitPHINode(PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000547 }
Chris Lattner347389d2001-06-27 23:38:11 +0000548 }
549
Chris Lattner074be1f2004-11-15 04:44:20 +0000550 // getFeasibleSuccessors - Return a vector of booleans to indicate which
551 // successors are reachable from a given terminator instruction.
Craig Topperb94011f2013-07-14 04:42:23 +0000552 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000553
554 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000555 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000556 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
557
558 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000559 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000560 // information, we need to update the specified user of this instruction.
Chris Lattnerfb141812009-11-03 03:42:51 +0000561 void OperandChangedState(Instruction *I) {
562 if (BBExecutable.count(I->getParent())) // Inst is executable?
563 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000564 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000565
Chris Lattner074be1f2004-11-15 04:44:20 +0000566private:
567 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000568
Chris Lattnera3c39d32009-11-02 02:33:50 +0000569 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000570 // operand made a transition, or the instruction is newly executable. Change
571 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000572 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000573
574 // Terminators
Eugene Zelenko99241d72017-10-20 21:47:29 +0000575
Chris Lattnerb4394642004-12-10 08:02:06 +0000576 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000577 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000578
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000579 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000580 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000581 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000582 void visitCmpInst(CmpInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000583 void visitExtractValueInst(ExtractValueInst &EVI);
584 void visitInsertValueInst(InsertValueInst &IVI);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000585
David Majnemer8a1c45d2015-12-12 05:38:55 +0000586 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000587 markOverdefined(&CPI);
David Majnemereb518bd2015-08-04 08:21:40 +0000588 visitTerminatorInst(CPI);
589 }
Chris Lattner6e560792002-04-18 15:13:15 +0000590
Chris Lattnera3c39d32009-11-02 02:33:50 +0000591 // Instructions that cannot be folded away.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000592
Chris Lattnerf5484032009-11-02 05:55:40 +0000593 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000594 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000595 void visitGetElementPtrInst(GetElementPtrInst &I);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000596
Victor Hernandeze2971492009-10-24 04:23:03 +0000597 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000598 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000599 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000600
Chris Lattnerb4394642004-12-10 08:02:06 +0000601 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000602 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000603 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000604 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000605
Chris Lattnerb4394642004-12-10 08:02:06 +0000606 void visitCallSite (CallSite CS);
Davide Italianoa7f5e882016-05-04 23:27:13 +0000607 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
608 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
609 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000610
Chris Lattner113f4f42002-06-25 16:13:24 +0000611 void visitInstruction(Instruction &I) {
Davide Italiano0b1190a2017-06-16 20:27:17 +0000612 // All the instructions we don't do any special handling for just
613 // go to overdefined.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000614 LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
Davide Italiano0b1190a2017-06-16 20:27:17 +0000615 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000616 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000617};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000618
Duncan Sands2be91fc2007-07-20 08:56:21 +0000619} // end anonymous namespace
620
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000621// getFeasibleSuccessors - Return a vector of booleans to indicate which
622// successors are reachable from a given terminator instruction.
Chris Lattner074be1f2004-11-15 04:44:20 +0000623void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000624 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000625 Succs.resize(TI.getNumSuccessors());
Davide Italianoe3bdd612016-12-01 08:36:12 +0000626 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000627 if (BI->isUnconditional()) {
628 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000629 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000630 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000631
Chris Lattnerf5484032009-11-02 05:55:40 +0000632 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000633 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000634 if (!CI) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000635 // Overdefined condition variables, and branches on unfoldable constant
636 // conditions, mean the branch could go either way.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000637 if (!BCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000638 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000639 return;
640 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000641
Chris Lattner6df5cec2009-11-02 02:30:06 +0000642 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000643 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000644 return;
645 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000646
David Majnemer654e1302015-07-31 17:58:14 +0000647 // Unwinding instructions successors are always executable.
648 if (TI.isExceptional()) {
649 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattneree8b9512009-10-29 01:21:20 +0000650 return;
651 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000652
Davide Italianoe3bdd612016-12-01 08:36:12 +0000653 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000654 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000655 Succs[0] = true;
656 return;
657 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000658 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000659 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000660
Davide Italiano0f03ce02016-07-10 00:35:15 +0000661 if (!CI) { // Overdefined or unknown condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000662 // All destinations are executable!
Davide Italiano0f03ce02016-07-10 00:35:15 +0000663 if (!SCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000664 Succs.assign(TI.getNumSuccessors(), true);
665 return;
666 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000667
Chandler Carruth927d8e62017-04-12 07:27:28 +0000668 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000669 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000670 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000671
Xin Tong34888c02017-04-10 00:33:25 +0000672 // In case of indirect branch and its address is a blockaddress, we mark
673 // the target as executable.
674 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
675 // Casts are folded by visitCastInst.
676 LatticeVal IBRValue = getValueState(IBR->getAddress());
677 BlockAddress *Addr = IBRValue.getBlockAddress();
678 if (!Addr) { // Overdefined or unknown condition?
679 // All destinations are executable!
680 if (!IBRValue.isUnknown())
681 Succs.assign(TI.getNumSuccessors(), true);
682 return;
683 }
684
685 BasicBlock* T = Addr->getBasicBlock();
686 assert(Addr->getFunction() == T->getParent() &&
687 "Block address of a different function ?");
688 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
689 // This is the target.
690 if (IBR->getDestination(i) == T) {
691 Succs[i] = true;
692 return;
693 }
694 }
695
696 // If we didn't find our destination in the IBR successor list, then we
697 // have undefined behavior. Its ok to assume no successor is executable.
Chris Lattneree8b9512009-10-29 01:21:20 +0000698 return;
699 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000700
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000701 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
Chris Lattneree8b9512009-10-29 01:21:20 +0000702 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000703}
704
Chris Lattner13b52e72002-05-02 21:18:01 +0000705// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000706// block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000707bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000708 assert(BBExecutable.count(To) && "Dest should always be alive!");
709
710 // Make sure the source basic block is executable!!
711 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000712
Chris Lattnera3c39d32009-11-02 02:33:50 +0000713 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000714 TerminatorInst *TI = From->getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +0000715 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000716 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000717 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000718
Chris Lattnerf5484032009-11-02 05:55:40 +0000719 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000720
Chris Lattner6df5cec2009-11-02 02:30:06 +0000721 // Overdefined condition variables mean the branch could go either way,
722 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000723 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000724 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000725 return !BCValue.isUnknown();
Jakub Staszak632a3552012-01-18 21:16:33 +0000726
Chris Lattner6df5cec2009-11-02 02:30:06 +0000727 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000728 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000729 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000730
David Majnemer654e1302015-07-31 17:58:14 +0000731 // Unwinding instructions successors are always executable.
732 if (TI->isExceptional())
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000733 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000734
Davide Italianoe3bdd612016-12-01 08:36:12 +0000735 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000736 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000737 return true;
738
Chris Lattnerf5484032009-11-02 05:55:40 +0000739 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000740 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000741
Craig Topperf40110f2014-04-25 05:29:35 +0000742 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000743 return !SCValue.isUnknown();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000744
Chandler Carruth927d8e62017-04-12 07:27:28 +0000745 return SI->findCaseValue(CI)->getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000746 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000747
Xin Tong34888c02017-04-10 00:33:25 +0000748 // In case of indirect branch and its address is a blockaddress, we mark
749 // the target as executable.
750 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
751 LatticeVal IBRValue = getValueState(IBR->getAddress());
752 BlockAddress *Addr = IBRValue.getBlockAddress();
753
754 if (!Addr)
755 return !IBRValue.isUnknown();
756
757 // At this point, the indirectbr is branching on a blockaddress.
758 return Addr->getBasicBlock() == To;
759 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000760
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000761 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
Davide Italianodd04fee2015-11-25 21:03:36 +0000762 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattner13b52e72002-05-02 21:18:01 +0000763}
Chris Lattner347389d2001-06-27 23:38:11 +0000764
Chris Lattnera3c39d32009-11-02 02:33:50 +0000765// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000766// operand made a transition, or the instruction is newly executable. Change
767// the value type of I to reflect these changes if appropriate. This method
768// makes sure to do the following actions:
769//
770// 1. If a phi node merges two constants in, and has conflicting value coming
771// from different branches, or if the PHI node merges in an overdefined
772// value, then the PHI node becomes overdefined.
773// 2. If a phi node merges only constants in, and they all agree on value, the
774// PHI node becomes a constant value equal to that.
775// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
776// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
777// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
778// 6. If a conditional branch has a value that is constant, make the selected
779// destination executable
780// 7. If a conditional branch has a value that is overdefined, make all
781// successors executable.
Chris Lattner074be1f2004-11-15 04:44:20 +0000782void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000783 // If this PN returns a struct, just mark the result overdefined.
784 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000785 if (PN.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000786 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000787
Eli Friedman0a309292011-11-11 01:16:15 +0000788 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000789 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000790
Chris Lattner7a7b1142004-03-16 19:49:59 +0000791 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
792 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000793 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000794 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000795
Chris Lattner6e560792002-04-18 15:13:15 +0000796 // Look at all of the executable operands of the PHI node. If any of them
797 // are overdefined, the PHI becomes overdefined as well. If they are all
798 // constant, and they agree with each other, the PHI becomes the identical
799 // constant. If they are constant and don't agree, the PHI is overdefined.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000800 // If there are no executable operands, the PHI remains unknown.
Craig Topperf40110f2014-04-25 05:29:35 +0000801 Constant *OperandVal = nullptr;
Chris Lattnercccc5c72003-04-25 02:50:03 +0000802 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000803 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +0000804 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000805
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000806 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
807 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000808
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000809 if (IV.isOverdefined()) // PHI node becomes overdefined!
810 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000811
Craig Topperf40110f2014-04-25 05:29:35 +0000812 if (!OperandVal) { // Grab the first value.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000813 OperandVal = IV.getConstant();
814 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000815 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000816
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000817 // There is already a reachable operand. If we conflict with it,
818 // then the PHI node becomes overdefined. If we agree with it, we
819 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000820
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000821 // Check to see if there are two different constants merging, if so, the PHI
822 // node is overdefined.
823 if (IV.getConstant() != OperandVal)
824 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000825 }
826
Chris Lattner6e560792002-04-18 15:13:15 +0000827 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000828 // arguments that agree with each other(and OperandVal is the constant) or
829 // OperandVal is null because there are no defined incoming arguments. If
Davide Italiano0f03ce02016-07-10 00:35:15 +0000830 // this is the case, the PHI remains unknown.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000831 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000832 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000833}
834
Chris Lattnerb4394642004-12-10 08:02:06 +0000835void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000836 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000837
Chris Lattnerb4394642004-12-10 08:02:06 +0000838 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000839 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000840
Devang Patela7a20752008-03-11 05:46:42 +0000841 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000842 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000843 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000844 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000845 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000846 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000847 return;
848 }
849 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000850
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000851 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000852 if (!TrackedMultipleRetVals.empty()) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000853 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000854 if (MRVFunctionsTracked.count(F))
855 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
856 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
857 getStructValueState(ResultOp, i));
Chris Lattnerb4394642004-12-10 08:02:06 +0000858 }
859}
860
Chris Lattner074be1f2004-11-15 04:44:20 +0000861void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000862 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000863 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000864
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000865 BasicBlock *BB = TI.getParent();
866
Chris Lattnera3c39d32009-11-02 02:33:50 +0000867 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000868 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000869 if (SuccFeasible[i])
870 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000871}
872
Chris Lattner074be1f2004-11-15 04:44:20 +0000873void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000874 LatticeVal OpSt = getValueState(I.getOperand(0));
875 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000876 markOverdefined(&I);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000877 else if (OpSt.isConstant()) {
Davide Italianod555bde2016-07-08 19:13:40 +0000878 // Fold the constant as we build.
Davide Italiano63c4ce82016-07-11 18:21:29 +0000879 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
880 I.getType(), DL);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000881 if (isa<UndefValue>(C))
882 return;
883 // Propagate constant value
884 markConstant(&I, C);
885 }
Chris Lattner6e560792002-04-18 15:13:15 +0000886}
887
Dan Gohman041f9d02008-06-20 01:15:44 +0000888void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000889 // If this returns a struct, mark all elements over defined, we don't track
890 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000891 if (EVI.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000892 return markOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000893
Chris Lattner156b8c72009-11-03 23:40:48 +0000894 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000895 if (EVI.getNumIndices() != 1)
896 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000897
Chris Lattner156b8c72009-11-03 23:40:48 +0000898 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000899 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000900 unsigned i = *EVI.idx_begin();
901 LatticeVal EltVal = getStructValueState(AggVal, i);
902 mergeInValue(getValueState(&EVI), &EVI, EltVal);
903 } else {
904 // Otherwise, must be extracting from an array.
905 return markOverdefined(&EVI);
906 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000907}
908
909void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000910 auto *STy = dyn_cast<StructType>(IVI.getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000911 if (!STy)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000912 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000913
Chris Lattner156b8c72009-11-03 23:40:48 +0000914 // If this has more than one index, we can't handle it, drive all results to
915 // undef.
916 if (IVI.getNumIndices() != 1)
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000917 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000918
Chris Lattner156b8c72009-11-03 23:40:48 +0000919 Value *Aggr = IVI.getAggregateOperand();
920 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000921
Chris Lattner156b8c72009-11-03 23:40:48 +0000922 // Compute the result based on what we're inserting.
923 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
924 // This passes through all values that aren't the inserted element.
925 if (i != Idx) {
926 LatticeVal EltVal = getStructValueState(Aggr, i);
927 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
928 continue;
929 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000930
Chris Lattner156b8c72009-11-03 23:40:48 +0000931 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000932 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000933 // We don't track structs in structs.
934 markOverdefined(getStructValueState(&IVI, i), &IVI);
935 else {
936 LatticeVal InVal = getValueState(Val);
937 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
938 }
939 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000940}
941
Chris Lattner074be1f2004-11-15 04:44:20 +0000942void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000943 // If this select returns a struct, just mark the result overdefined.
944 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000945 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000946 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000947
Chris Lattnerf5484032009-11-02 05:55:40 +0000948 LatticeVal CondValue = getValueState(I.getCondition());
Davide Italiano0f03ce02016-07-10 00:35:15 +0000949 if (CondValue.isUnknown())
Chris Lattner06a0ed12006-02-08 02:38:11 +0000950 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000951
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000952 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000953 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
954 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000955 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000956 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000957
Chris Lattner06a0ed12006-02-08 02:38:11 +0000958 // Otherwise, the condition is overdefined or a constant we can't evaluate.
959 // See if we can produce something better than overdefined based on the T/F
960 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000961 LatticeVal TVal = getValueState(I.getTrueValue());
962 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000963
Chris Lattner06a0ed12006-02-08 02:38:11 +0000964 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000965 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000966 TVal.getConstant() == FVal.getConstant())
967 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000968
Davide Italiano0f03ce02016-07-10 00:35:15 +0000969 if (TVal.isUnknown()) // select ?, undef, X -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000970 return mergeInValue(&I, FVal);
Davide Italiano0f03ce02016-07-10 00:35:15 +0000971 if (FVal.isUnknown()) // select ?, X, undef -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000972 return mergeInValue(&I, TVal);
973 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000974}
975
Chris Lattnerf5484032009-11-02 05:55:40 +0000976// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000977void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000978 LatticeVal V1State = getValueState(I.getOperand(0));
979 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000980
Chris Lattner4f031622004-11-15 05:03:30 +0000981 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000982 if (IV.isOverdefined()) return;
983
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000984 if (V1State.isConstant() && V2State.isConstant()) {
985 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
986 V2State.getConstant());
987 // X op Y -> undef.
988 if (isa<UndefValue>(C))
989 return;
990 return markConstant(IV, &I, C);
991 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000992
Chris Lattnerf5484032009-11-02 05:55:40 +0000993 // If something is undef, wait for it to resolve.
994 if (!V1State.isOverdefined() && !V2State.isOverdefined())
995 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000996
Chris Lattnerf5484032009-11-02 05:55:40 +0000997 // Otherwise, one of our operands is overdefined. Try to produce something
998 // better than overdefined with some tricks.
Davide Italiano6c2c3e02017-01-19 23:07:51 +0000999 // If this is 0 / Y, it doesn't matter that the second operand is
1000 // overdefined, and we can replace it with zero.
1001 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
1002 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
1003 return markConstant(IV, &I, V1State.getConstant());
1004
Davide Italiano93c6c182017-01-19 21:07:42 +00001005 // If this is:
1006 // -> AND/MUL with 0
1007 // -> OR with -1
1008 // it doesn't matter that the other operand is overdefined.
Davide Italiano824d6952016-12-09 03:08:42 +00001009 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
1010 I.getOpcode() == Instruction::Or) {
Craig Topperf40110f2014-04-25 05:29:35 +00001011 LatticeVal *NonOverdefVal = nullptr;
Chris Lattnerf5484032009-11-02 05:55:40 +00001012 if (!V1State.isOverdefined())
1013 NonOverdefVal = &V1State;
1014 else if (!V2State.isOverdefined())
1015 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +00001016
Chris Lattnerf5484032009-11-02 05:55:40 +00001017 if (NonOverdefVal) {
Davide Italianoe7ffae92016-11-22 22:11:25 +00001018 if (NonOverdefVal->isUnknown())
Chris Lattnerf5484032009-11-02 05:55:40 +00001019 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001020
Davide Italiano824d6952016-12-09 03:08:42 +00001021 if (I.getOpcode() == Instruction::And ||
1022 I.getOpcode() == Instruction::Mul) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001023 // X and 0 = 0
Davide Italiano824d6952016-12-09 03:08:42 +00001024 // X * 0 = 0
Chris Lattnerf5484032009-11-02 05:55:40 +00001025 if (NonOverdefVal->getConstant()->isNullValue())
1026 return markConstant(IV, &I, NonOverdefVal->getConstant());
1027 } else {
Davide Italianoe7ffae92016-11-22 22:11:25 +00001028 // X or -1 = -1
Chris Lattnerf5484032009-11-02 05:55:40 +00001029 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
Craig Topper79ab6432017-07-06 18:39:47 +00001030 if (CI->isMinusOne())
Chris Lattnerf5484032009-11-02 05:55:40 +00001031 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +00001032 }
1033 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001034 }
Chris Lattnercbc01612004-12-11 23:15:19 +00001035
Chris Lattnerf5484032009-11-02 05:55:40 +00001036 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +00001037}
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001038
Chris Lattnera3c39d32009-11-02 02:33:50 +00001039// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001040void SCCPSolver::visitCmpInst(CmpInst &I) {
Florian Hahnf73c3ec2018-03-23 12:49:39 +00001041 LatticeVal V1State = getValueState(I.getOperand(0));
1042 LatticeVal V2State = getValueState(I.getOperand(1));
1043
Reid Spencer266e42b2006-12-23 06:05:41 +00001044 LatticeVal &IV = ValueState[&I];
1045 if (IV.isOverdefined()) return;
1046
Florian Hahnf73c3ec2018-03-23 12:49:39 +00001047 if (V1State.isConstant() && V2State.isConstant()) {
1048 Constant *C = ConstantExpr::getCompare(
1049 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001050 if (isa<UndefValue>(C))
1051 return;
1052 return markConstant(IV, &I, C);
1053 }
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.
Chris Lattnerf5484032009-11-02 05:55:40 +00001056 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1057 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001058
Chris Lattnerf5484032009-11-02 05:55:40 +00001059 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +00001060}
1061
Chris Lattnera3c39d32009-11-02 02:33:50 +00001062// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001063// can turn this into a getelementptr ConstantExpr.
Chris Lattner074be1f2004-11-15 04:44:20 +00001064void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001065 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001066
Chris Lattner0e7ec672007-02-02 20:51:48 +00001067 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001068 Operands.reserve(I.getNumOperands());
1069
1070 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001071 LatticeVal State = getValueState(I.getOperand(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001072 if (State.isUnknown())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001073 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001074
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001075 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001076 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001077
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001078 assert(State.isConstant() && "Unknown state!");
1079 Operands.push_back(State.getConstant());
1080 }
1081
1082 Constant *Ptr = Operands[0];
Craig Toppere1d12942014-08-27 05:25:25 +00001083 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001084 Constant *C =
1085 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1086 if (isa<UndefValue>(C))
1087 return;
1088 markConstant(&I, C);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001089}
Brian Gaeke960707c2003-11-11 22:41:34 +00001090
Chris Lattnerf5484032009-11-02 05:55:40 +00001091void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001092 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001093 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001094 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001095
Chris Lattner91dbae62004-12-11 05:15:59 +00001096 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1097 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001098
Chris Lattner91dbae62004-12-11 05:15:59 +00001099 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001100 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001101 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1102
Chris Lattnerf5484032009-11-02 05:55:40 +00001103 // Get the value we are storing into the global, then merge it.
1104 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001105 if (I->second.isOverdefined())
1106 TrackedGlobals.erase(I); // No need to keep tracking this!
1107}
1108
Chris Lattner49f74522004-01-12 04:29:41 +00001109// Handle load instructions. If the operand is a constant pointer to a constant
1110// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001111void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001112 // If this load is of a struct, just mark the result overdefined.
David Majnemerf3b99dd2016-01-07 19:30:13 +00001113 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001114 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001115
Chris Lattnerf5484032009-11-02 05:55:40 +00001116 LatticeVal PtrVal = getValueState(I.getOperand(0));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001117 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001118
Chris Lattner4f031622004-11-15 05:03:30 +00001119 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001120 if (IV.isOverdefined()) return;
1121
Chris Lattnerf5484032009-11-02 05:55:40 +00001122 if (!PtrVal.isConstant() || I.isVolatile())
1123 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001124
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001125 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001126
David Majnemerbae94572016-01-07 19:25:39 +00001127 // load null is undefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001128 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
David Majnemerbae94572016-01-07 19:25:39 +00001129 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001130
Chris Lattnerf5484032009-11-02 05:55:40 +00001131 // Transform load (constant global) into the value loaded.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001132 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001133 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001134 // If we are tracking this global, merge in the known value for it.
1135 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1136 TrackedGlobals.find(GV);
1137 if (It != TrackedGlobals.end()) {
1138 mergeInValue(IV, &I, It->second);
1139 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001140 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001141 }
Chris Lattner49f74522004-01-12 04:29:41 +00001142 }
1143
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001144 // Transform load from a constant into a constant if possible.
Eduard Burtescu14239212016-01-22 01:17:26 +00001145 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001146 if (isa<UndefValue>(C))
1147 return;
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001148 return markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001149 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001150
Chris Lattner49f74522004-01-12 04:29:41 +00001151 // Otherwise we cannot say for certain what value this load will produce.
1152 // Bail out.
1153 markOverdefined(IV, &I);
1154}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001155
Chris Lattnerb4394642004-12-10 08:02:06 +00001156void SCCPSolver::visitCallSite(CallSite CS) {
1157 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001158 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001159
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001160 // The common case is that we aren't tracking the callee, either because we
1161 // are not doing interprocedural analysis or the callee is indirect, or is
1162 // external. Handle these cases first.
Craig Topperf40110f2014-04-25 05:29:35 +00001163 if (!F || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001164CallOverdefined:
1165 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001166 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001167
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001168 // Otherwise, if we have a single return value case, and if the function is
1169 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001170 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Andrew Kaylor647025f2017-06-09 23:18:11 +00001171 canConstantFoldCallTo(CS, F)) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001172 SmallVector<Constant*, 8> Operands;
1173 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1174 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001175 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001176
Davide Italiano0f03ce02016-07-10 00:35:15 +00001177 if (State.isUnknown())
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001178 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001179 if (State.isOverdefined())
1180 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001181 assert(State.isConstant() && "Unknown state!");
1182 Operands.push_back(State.getConstant());
1183 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001184
David Majnemer2098b86f2014-11-07 08:54:19 +00001185 if (getValueState(I).isOverdefined())
1186 return;
1187
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001188 // If we can constant fold this, mark the result of the call as a
1189 // constant.
Andrew Kaylor647025f2017-06-09 23:18:11 +00001190 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001191 // call -> undef.
1192 if (isa<UndefValue>(C))
1193 return;
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001194 return markConstant(I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001195 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001196 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001197
1198 // Otherwise, we don't know anything about this call, mark it overdefined.
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001199 return markOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001200 }
1201
Chris Lattnercde8de52009-11-03 19:24:51 +00001202 // If this is a local function that doesn't have its address taken, mark its
1203 // entry block executable and merge in the actual arguments to the call into
1204 // the formal arguments of the function.
1205 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001206 MarkBlockExecutable(&F->front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001207
Chris Lattnercde8de52009-11-03 19:24:51 +00001208 // Propagate information from this call site into the callee.
1209 CallSite::arg_iterator CAI = CS.arg_begin();
1210 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1211 AI != E; ++AI, ++CAI) {
1212 // If this argument is byval, and if the function is not readonly, there
1213 // will be an implicit copy formed of the input aggregate.
1214 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001215 markOverdefined(&*AI);
Chris Lattnercde8de52009-11-03 19:24:51 +00001216 continue;
1217 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001218
Davide Italianoe3bdd612016-12-01 08:36:12 +00001219 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001220 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1221 LatticeVal CallArg = getStructValueState(*CAI, i);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001222 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
Chris Lattner762b56f2009-11-04 18:57:42 +00001223 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001224 } else {
Florian Hahnd0208b42017-10-30 10:07:42 +00001225 // Most other parts of the Solver still only use the simpler value
1226 // lattice, so we propagate changes for parameters to both lattices.
1227 getParamState(&*AI).mergeIn(getValueState(*CAI).toValueLattice(), DL);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001228 mergeInValue(&*AI, getValueState(*CAI));
Chris Lattner156b8c72009-11-03 23:40:48 +00001229 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001230 }
1231 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001232
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001233 // If this is a single/zero retval case, see if we're tracking the function.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001234 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001235 if (!MRVFunctionsTracked.count(F))
1236 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001237
Chris Lattner156b8c72009-11-03 23:40:48 +00001238 // If we are tracking this callee, propagate the result of the function
1239 // into this call site.
1240 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001241 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001242 TrackedMultipleRetVals[std::make_pair(F, i)]);
1243 } else {
1244 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1245 if (TFRVI == TrackedRetVals.end())
1246 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001247
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001248 // If so, propagate the return value of the callee into this call result.
1249 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001250 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001251}
Chris Lattner074be1f2004-11-15 04:44:20 +00001252
Chris Lattner074be1f2004-11-15 04:44:20 +00001253void SCCPSolver::Solve() {
1254 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001255 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001256 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001257 // Process the overdefined instruction's work list first, which drives other
1258 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001259 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001260 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001261
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001262 LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001263
Chris Lattner074be1f2004-11-15 04:44:20 +00001264 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001265 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001266 //
1267 // Anything on this worklist that is overdefined need not be visited
1268 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001269 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001270 //
Florian Hahn8a17f1f2018-06-01 12:58:43 +00001271 for (User *U : I->users())
1272 if (auto *UI = dyn_cast<Instruction>(U))
1273 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001274 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001275
Chris Lattnera3c39d32009-11-02 02:33:50 +00001276 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001277 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001278 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001279
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001280 LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001281
Chris Lattnerf5484032009-11-02 05:55:40 +00001282 // "I" got into the work list because it made the transition from undef to
1283 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001284 //
1285 // Anything on this worklist that is overdefined need not be visited
1286 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001287 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001288 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001289 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Florian Hahn8a17f1f2018-06-01 12:58:43 +00001290 for (User *U : I->users())
1291 if (auto *UI = dyn_cast<Instruction>(U))
1292 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001293 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001294
Chris Lattnera3c39d32009-11-02 02:33:50 +00001295 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001296 while (!BBWorkList.empty()) {
1297 BasicBlock *BB = BBWorkList.back();
1298 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001299
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001300 LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001301
Chris Lattner074be1f2004-11-15 04:44:20 +00001302 // Notify all instructions in this basic block that they are newly
1303 // executable.
1304 visit(BB);
1305 }
1306 }
1307}
1308
Chris Lattner1847f6d2006-12-20 06:21:33 +00001309/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001310/// that branches on undef values cannot reach any of their successors.
1311/// However, this is not a safe assumption. After we solve dataflow, this
1312/// method should be use to handle this. If this returns true, the solver
1313/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001314///
1315/// This method handles this by finding an unresolved branch and marking it one
1316/// of the edges from the block as being feasible, even though the condition
1317/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1318/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001319/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001320/// constraints on the condition of the branch, as that would impact other users
1321/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001322///
1323/// This scan also checks for values that use undefs, whose results are actually
1324/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1325/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1326/// even if X isn't defined.
1327bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001328 for (BasicBlock &BB : F) {
1329 if (!BBExecutable.count(&BB))
Chris Lattneraf170962006-10-22 05:59:17 +00001330 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001331
Benjamin Kramer135f7352016-06-26 12:28:59 +00001332 for (Instruction &I : BB) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001333 // Look for instructions which produce undef values.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001334 if (I.getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001335
Davide Italianoe3bdd612016-12-01 08:36:12 +00001336 if (auto *STy = dyn_cast<StructType>(I.getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001337 // Only a few things that can be structs matter for undef.
1338
1339 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001340 if (CallSite CS = CallSite(&I))
Eli Friedman1815b682011-09-20 23:28:51 +00001341 if (Function *F = CS.getCalledFunction())
1342 if (MRVFunctionsTracked.count(F))
1343 continue;
1344
1345 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001346 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001347 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1348 continue;
1349
1350 // Send the results of everything else to overdefined. We could be
1351 // more precise than this but it isn't worth bothering.
1352 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001353 LatticeVal &LV = getStructValueState(&I, i);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001354 if (LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001355 markOverdefined(LV, &I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001356 }
1357 continue;
1358 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001359
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001360 LatticeVal &LV = getValueState(&I);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001361 if (!LV.isUnknown()) continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001362
Eli Friedmand7749be2011-08-17 18:10:43 +00001363 // extractvalue is safe; check here because the argument is a struct.
1364 if (isa<ExtractValueInst>(I))
1365 continue;
1366
1367 // Compute the operand LatticeVals, for convenience below.
1368 // Anything taking a struct is conservatively assumed to require
1369 // overdefined markings.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001370 if (I.getOperand(0)->getType()->isStructTy()) {
1371 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001372 return true;
1373 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001374 LatticeVal Op0LV = getValueState(I.getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001375 LatticeVal Op1LV;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001376 if (I.getNumOperands() == 2) {
1377 if (I.getOperand(1)->getType()->isStructTy()) {
1378 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001379 return true;
1380 }
1381
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001382 Op1LV = getValueState(I.getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001383 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001384 // If this is an instructions whose result is defined even if the input is
1385 // not fully defined, propagate the information.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001386 Type *ITy = I.getType();
1387 switch (I.getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001388 case Instruction::Add:
1389 case Instruction::Sub:
1390 case Instruction::Trunc:
1391 case Instruction::FPTrunc:
1392 case Instruction::BitCast:
1393 break; // Any undef -> undef
1394 case Instruction::FSub:
1395 case Instruction::FAdd:
1396 case Instruction::FMul:
1397 case Instruction::FDiv:
1398 case Instruction::FRem:
1399 // Floating-point binary operation: be conservative.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001400 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001401 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001402 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001403 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001404 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001405 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001406 case Instruction::SExt:
1407 case Instruction::FPToUI:
1408 case Instruction::FPToSI:
1409 case Instruction::FPExt:
1410 case Instruction::PtrToInt:
1411 case Instruction::IntToPtr:
1412 case Instruction::SIToFP:
1413 case Instruction::UIToFP:
1414 // undef -> 0; some outputs are impossible
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001415 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001416 return true;
1417 case Instruction::Mul:
1418 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001419 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001420 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001421 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001422 // undef * X -> 0. X could be zero.
1423 // undef & X -> 0. X could be zero.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001424 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001425 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001426 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001427 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001428 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001429 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001430 // undef | X -> -1. X could be -1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001431 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001432 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001433 case Instruction::Xor:
1434 // undef ^ undef -> 0; strictly speaking, this is not strictly
1435 // necessary, but we try to be nice to people who expect this
1436 // behavior in simple cases
Davide Italiano0f03ce02016-07-10 00:35:15 +00001437 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001438 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001439 return true;
1440 }
1441 // undef ^ X -> undef
1442 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001443 case Instruction::SDiv:
1444 case Instruction::UDiv:
1445 case Instruction::SRem:
1446 case Instruction::URem:
1447 // X / undef -> undef. No change.
1448 // X % undef -> undef. No change.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001449 if (Op1LV.isUnknown()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001450
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001451 // X / 0 -> undef. No change.
1452 // X % 0 -> undef. No change.
1453 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1454 break;
1455
Chris Lattner1847f6d2006-12-20 06:21:33 +00001456 // undef / X -> 0. X could be maxint.
1457 // undef % X -> 0. X could be 1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001458 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001459 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001460 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001461 // X >>a undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001462 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001463
David Majnemer96f0d382016-05-12 03:07:40 +00001464 // Shifting by the bitwidth or more is undefined.
1465 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001466 if (auto *ShiftAmt = Op1LV.getConstantInt())
1467 if (ShiftAmt->getLimitedValue() >=
1468 ShiftAmt->getType()->getScalarSizeInBits())
1469 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001470 }
1471
Davide Italiano54c683f2016-12-08 22:28:53 +00001472 // undef >>a X -> 0
1473 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001474 return true;
1475 case Instruction::LShr:
1476 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001477 // X << undef -> undef.
1478 // X >> undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001479 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001480
David Majnemer96f0d382016-05-12 03:07:40 +00001481 // Shifting by the bitwidth or more is undefined.
1482 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001483 if (auto *ShiftAmt = Op1LV.getConstantInt())
1484 if (ShiftAmt->getLimitedValue() >=
1485 ShiftAmt->getType()->getScalarSizeInBits())
1486 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001487 }
1488
Eli Friedman0793eb42011-08-16 22:06:31 +00001489 // undef << X -> 0
1490 // undef >> X -> 0
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001491 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001492 return true;
1493 case Instruction::Select:
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001494 Op1LV = getValueState(I.getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001495 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001496 if (Op0LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001497 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001498 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001499 } else if (Op1LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001500 // c ? undef : undef -> undef. No change.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001501 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001502 if (Op1LV.isUnknown())
Chris Lattner1847f6d2006-12-20 06:21:33 +00001503 break;
1504 // Otherwise, c ? undef : x -> x.
1505 } else {
1506 // Leave Op1LV as Operand(1)'s LatticeValue.
1507 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001508
Chris Lattner1847f6d2006-12-20 06:21:33 +00001509 if (Op1LV.isConstant())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001510 markForcedConstant(&I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001511 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001512 markOverdefined(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001513 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001514 case Instruction::Load:
1515 // A load here means one of two things: a load of undef from a global,
1516 // a load from an unknown pointer. Either way, having it return undef
1517 // is okay.
1518 break;
1519 case Instruction::ICmp:
1520 // X == undef -> undef. Other comparisons get more complicated.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001521 if (cast<ICmpInst>(&I)->isEquality())
Eli Friedman0793eb42011-08-16 22:06:31 +00001522 break;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001523 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001524 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001525 case Instruction::Call:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001526 case Instruction::Invoke:
Eli Friedman1815b682011-09-20 23:28:51 +00001527 // There are two reasons a call can have an undef result
1528 // 1. It could be tracked.
1529 // 2. It could be constant-foldable.
1530 // Because of the way we solve return values, tracked calls must
1531 // never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001532 if (Function *F = CallSite(&I).getCalledFunction())
Eli Friedman1815b682011-09-20 23:28:51 +00001533 if (TrackedRetVals.count(F))
1534 break;
1535
1536 // If the call is constant-foldable, we mark it overdefined because
1537 // we do not know what return values are valid.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001538 markOverdefined(&I);
Eli Friedman1815b682011-09-20 23:28:51 +00001539 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001540 default:
1541 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001542 // overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001543 markOverdefined(&I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001544 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001545 }
1546 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001547
Chris Lattneradca6082010-04-05 22:14:48 +00001548 // Check to see if we have a branch or switch on an undefined value. If so
1549 // we force the branch to go one way or the other to make the successor
1550 // values live. It doesn't really matter which way we force it.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001551 TerminatorInst *TI = BB.getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +00001552 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneraf170962006-10-22 05:59:17 +00001553 if (!BI->isConditional()) continue;
Davide Italiano0f03ce02016-07-10 00:35:15 +00001554 if (!getValueState(BI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001555 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001556
Chris Lattneradca6082010-04-05 22:14:48 +00001557 // If the input to SCCP is actually branch on undef, fix the undef to
1558 // false.
1559 if (isa<UndefValue>(BI->getCondition())) {
1560 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Benjamin Kramer135f7352016-06-26 12:28:59 +00001561 markEdgeExecutable(&BB, TI->getSuccessor(1));
Chris Lattneradca6082010-04-05 22:14:48 +00001562 return true;
1563 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001564
Chris Lattneradca6082010-04-05 22:14:48 +00001565 // Otherwise, it is a branch on a symbolic value which is currently
1566 // considered to be undef. Handle this by forcing the input value to the
1567 // branch to false.
1568 markForcedConstant(BI->getCondition(),
1569 ConstantInt::getFalse(TI->getContext()));
1570 return true;
1571 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001572
Xin Tong34888c02017-04-10 00:33:25 +00001573 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1574 // Indirect branch with no successor ?. Its ok to assume it branches
1575 // to no target.
1576 if (IBR->getNumSuccessors() < 1)
1577 continue;
1578
1579 if (!getValueState(IBR->getAddress()).isUnknown())
1580 continue;
1581
1582 // If the input to SCCP is actually branch on undef, fix the undef to
1583 // the first successor of the indirect branch.
1584 if (isa<UndefValue>(IBR->getAddress())) {
1585 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1586 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1587 return true;
1588 }
1589
1590 // Otherwise, it is a branch on a symbolic value which is currently
1591 // considered to be undef. Handle this by forcing the input value to the
1592 // branch to the first successor.
1593 markForcedConstant(IBR->getAddress(),
1594 BlockAddress::get(IBR->getSuccessor(0)));
1595 return true;
1596 }
1597
Davide Italianoe3bdd612016-12-01 08:36:12 +00001598 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Davide Italiano094dadd2016-07-15 18:33:16 +00001599 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001600 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001601
Chris Lattneradca6082010-04-05 22:14:48 +00001602 // If the input to SCCP is actually switch on undef, fix the undef to
1603 // the first constant.
1604 if (isa<UndefValue>(SI->getCondition())) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00001605 SI->setCondition(SI->case_begin()->getCaseValue());
1606 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001607 return true;
1608 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001609
Chandler Carruth927d8e62017-04-12 07:27:28 +00001610 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001611 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001612 }
Chris Lattneraf170962006-10-22 05:59:17 +00001613 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001614
Chris Lattneraf170962006-10-22 05:59:17 +00001615 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001616}
1617
Florian Hahnf73c3ec2018-03-23 12:49:39 +00001618static bool tryToReplaceWithConstantRange(SCCPSolver &Solver, Value *V) {
1619 bool Changed = false;
1620
1621 // Currently we only use range information for integer values.
1622 if (!V->getType()->isIntegerTy())
1623 return false;
1624
1625 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
1626 if (!IV.isConstantRange())
1627 return false;
1628
1629 for (auto UI = V->uses().begin(), E = V->uses().end(); UI != E;) {
1630 const Use &U = *UI++;
1631 auto *Icmp = dyn_cast<ICmpInst>(U.getUser());
1632 if (!Icmp || !Solver.isBlockExecutable(Icmp->getParent()))
1633 continue;
1634
1635 auto getIcmpLatticeValue = [&](Value *Op) {
1636 if (auto *C = dyn_cast<Constant>(Op))
1637 return ValueLatticeElement::get(C);
1638 return Solver.getLatticeValueFor(Op);
1639 };
1640
1641 ValueLatticeElement A = getIcmpLatticeValue(Icmp->getOperand(0));
1642 ValueLatticeElement B = getIcmpLatticeValue(Icmp->getOperand(1));
1643
1644 Constant *C = A.getCompare(Icmp->getPredicate(), Icmp->getType(), B);
1645 if (C) {
1646 Icmp->replaceAllUsesWith(C);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001647 LLVM_DEBUG(dbgs() << "Replacing " << *Icmp << " with " << *C
1648 << ", because of range information " << A << " " << B
1649 << "\n");
Florian Hahnf73c3ec2018-03-23 12:49:39 +00001650 Icmp->eraseFromParent();
1651 Changed = true;
1652 }
1653 }
1654 return Changed;
1655}
1656
Davide Italiano6f735882016-07-14 20:25:54 +00001657static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
Davide Italiano296e9782016-07-13 23:20:04 +00001658 Constant *Const = nullptr;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001659 if (V->getType()->isStructTy()) {
1660 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
Eugene Zelenko99241d72017-10-20 21:47:29 +00001661 if (llvm::any_of(IVs,
1662 [](const LatticeVal &LV) { return LV.isOverdefined(); }))
Davide Italiano296e9782016-07-13 23:20:04 +00001663 return false;
1664 std::vector<Constant *> ConstVals;
Davide Italianoe3bdd612016-12-01 08:36:12 +00001665 auto *ST = dyn_cast<StructType>(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001666 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1667 LatticeVal V = IVs[i];
1668 ConstVals.push_back(V.isConstant()
1669 ? V.getConstant()
1670 : UndefValue::get(ST->getElementType(i)));
1671 }
1672 Const = ConstantStruct::get(ST, ConstVals);
1673 } else {
Florian Hahnd0208b42017-10-30 10:07:42 +00001674 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
Davide Italiano296e9782016-07-13 23:20:04 +00001675 if (IV.isOverdefined())
1676 return false;
Florian Hahnd0208b42017-10-30 10:07:42 +00001677
1678 if (IV.isConstantRange()) {
1679 if (IV.getConstantRange().isSingleElement())
1680 Const =
1681 ConstantInt::get(V->getType(), IV.asConstantInteger().getValue());
1682 else
1683 return false;
1684 } else
1685 Const =
1686 IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001687 }
1688 assert(Const && "Constant is nullptr here!");
Reid Kleckner3762a082018-03-01 01:19:18 +00001689
1690 // Replacing `musttail` instructions with constant breaks `musttail` invariant
1691 // unless the call itself can be removed
1692 CallInst *CI = dyn_cast<CallInst>(V);
1693 if (CI && CI->isMustTailCall() && !CI->isSafeToRemove()) {
1694 CallSite CS(CI);
1695 Function *F = CS.getCalledFunction();
1696
1697 // Don't zap returns of the callee
1698 if (F)
1699 Solver.AddMustTailCallee(F);
1700
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001701 LLVM_DEBUG(dbgs() << " Can\'t treat the result of musttail call : " << *CI
1702 << " as a constant\n");
Reid Kleckner3762a082018-03-01 01:19:18 +00001703 return false;
1704 }
1705
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001706 LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
Davide Italiano296e9782016-07-13 23:20:04 +00001707
1708 // Replaces all of the uses of a variable with uses of the constant.
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001709 V->replaceAllUsesWith(Const);
Davide Italiano6ed6d772016-07-14 01:27:29 +00001710 return true;
1711}
1712
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001713// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner074be1f2004-11-15 04:44:20 +00001714// and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001715static bool runSCCP(Function &F, const DataLayout &DL,
1716 const TargetLibraryInfo *TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001717 LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001718 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001719
1720 // Mark the first block of the function as being executable.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001721 Solver.MarkBlockExecutable(&F.front());
Chris Lattner074be1f2004-11-15 04:44:20 +00001722
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001723 // Mark all arguments to the function as being overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001724 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001725 Solver.markOverdefined(&AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001726
Chris Lattner074be1f2004-11-15 04:44:20 +00001727 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001728 bool ResolvedUndefs = true;
1729 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001730 Solver.Solve();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001731 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001732 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001733 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001734
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001735 bool MadeChanges = false;
1736
1737 // If we decided that there are basic blocks that are dead in this function,
1738 // delete their contents now. Note that we cannot actually delete the blocks,
1739 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001740
Benjamin Kramer135f7352016-06-26 12:28:59 +00001741 for (BasicBlock &BB : F) {
1742 if (!Solver.isBlockExecutable(&BB)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001743 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << BB);
David Majnemer88542a02016-01-24 06:26:47 +00001744
1745 ++NumDeadBlocks;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001746 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer88542a02016-01-24 06:26:47 +00001747
Chris Lattnere405ed92009-11-02 02:47:51 +00001748 MadeChanges = true;
1749 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001750 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001751
Chris Lattnere405ed92009-11-02 02:47:51 +00001752 // Iterate over all of the instructions in a function, replacing them with
1753 // constants if we have found them to be of constant values.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001754 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001755 Instruction *Inst = &*BI++;
Chris Lattnere405ed92009-11-02 02:47:51 +00001756 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1757 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001758
Sanjoy Dasff855b62016-08-24 18:10:21 +00001759 if (tryToReplaceWithConstant(Solver, Inst)) {
1760 if (isInstructionTriviallyDead(Inst))
1761 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001762 // Hey, we just changed something!
1763 MadeChanges = true;
1764 ++NumInstRemoved;
Davide Italiano00802692016-07-12 19:54:19 +00001765 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001766 }
1767 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001768
1769 return MadeChanges;
1770}
Chris Lattnerb4394642004-12-10 08:02:06 +00001771
Sean Silva36e0d012016-08-09 00:28:15 +00001772PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001773 const DataLayout &DL = F.getParent()->getDataLayout();
1774 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1775 if (!runSCCP(F, DL, &TLI))
1776 return PreservedAnalyses::all();
Davide Italiano484b5ab2016-05-29 00:31:15 +00001777
1778 auto PA = PreservedAnalyses();
1779 PA.preserve<GlobalsAA>();
1780 return PA;
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001781}
1782
1783namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +00001784
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001785//===--------------------------------------------------------------------===//
1786//
1787/// SCCP Class - This class uses the SCCPSolver to implement a per-function
1788/// Sparse Conditional Constant Propagator.
1789///
Davide Italiano46f249b2016-05-19 15:58:02 +00001790class SCCPLegacyPass : public FunctionPass {
1791public:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001792 // Pass identification, replacement for typeid
1793 static char ID;
1794
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001795 SCCPLegacyPass() : FunctionPass(ID) {
1796 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1797 }
1798
Eugene Zelenko99241d72017-10-20 21:47:29 +00001799 void getAnalysisUsage(AnalysisUsage &AU) const override {
1800 AU.addRequired<TargetLibraryInfoWrapperPass>();
1801 AU.addPreserved<GlobalsAAWrapperPass>();
1802 }
1803
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001804 // runOnFunction - Run the Sparse Conditional Constant Propagation
1805 // algorithm, and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001806 bool runOnFunction(Function &F) override {
1807 if (skipFunction(F))
1808 return false;
1809 const DataLayout &DL = F.getParent()->getDataLayout();
1810 const TargetLibraryInfo *TLI =
1811 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1812 return runSCCP(F, DL, TLI);
1813 }
1814};
Eugene Zelenko99241d72017-10-20 21:47:29 +00001815
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001816} // end anonymous namespace
1817
1818char SCCPLegacyPass::ID = 0;
Eugene Zelenko99241d72017-10-20 21:47:29 +00001819
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001820INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1821 "Sparse Conditional Constant Propagation", false, false)
1822INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1823INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1824 "Sparse Conditional Constant Propagation", false, false)
1825
1826// createSCCPPass - This is the public interface to this file.
1827FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1828
Davide Italiano15ff2d62016-07-20 20:17:13 +00001829static void findReturnsToZap(Function &F,
Matthew Simpson22849372017-10-13 17:53:44 +00001830 SmallVector<ReturnInst *, 8> &ReturnsToZap,
1831 SCCPSolver &Solver) {
Davide Italiano15ff2d62016-07-20 20:17:13 +00001832 // We can only do this if we know that nothing else can call the function.
Matthew Simpson22849372017-10-13 17:53:44 +00001833 if (!Solver.isArgumentTrackedFunction(&F))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001834 return;
1835
Reid Kleckner3762a082018-03-01 01:19:18 +00001836 // There is a non-removable musttail call site of this function. Zapping
1837 // returns is not allowed.
1838 if (Solver.isMustTailCallee(&F)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001839 LLVM_DEBUG(dbgs() << "Can't zap returns of the function : " << F.getName()
1840 << " due to present musttail call of it\n");
Reid Kleckner3762a082018-03-01 01:19:18 +00001841 return;
1842 }
1843
1844 for (BasicBlock &BB : F) {
1845 if (CallInst *CI = BB.getTerminatingMustTailCall()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001846 LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "
1847 << "musttail call : " << *CI << "\n");
Benjamin Kramerd1cf7ff2018-03-01 11:31:44 +00001848 (void)CI;
Reid Kleckner3762a082018-03-01 01:19:18 +00001849 return;
1850 }
1851
Davide Italianoe3bdd612016-12-01 08:36:12 +00001852 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001853 if (!isa<UndefValue>(RI->getOperand(0)))
1854 ReturnsToZap.push_back(RI);
Reid Kleckner3762a082018-03-01 01:19:18 +00001855 }
Davide Italiano15ff2d62016-07-20 20:17:13 +00001856}
1857
Florian Hahn8a17f1f2018-06-01 12:58:43 +00001858bool llvm::runIPSCCP(Module &M, const DataLayout &DL,
1859 const TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001860 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001861
1862 // Loop over all functions, marking arguments to those with their addresses
1863 // taken or that are external as overdefined.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001864 for (Function &F : M) {
1865 if (F.isDeclaration())
Chris Lattner47837c52009-11-02 06:34:04 +00001866 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001867
Matthew Simpson22849372017-10-13 17:53:44 +00001868 // Determine if we can track the function's return values. If so, add the
1869 // function to the solver's set of return-tracked functions.
1870 if (canTrackReturnsInterprocedurally(&F))
Davide Italianoe7c56c52016-05-14 20:59:09 +00001871 Solver.AddTrackedFunction(&F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001872
Matthew Simpson22849372017-10-13 17:53:44 +00001873 // Determine if we can track the function's arguments. If so, add the
1874 // function to the solver's set of argument-tracked functions.
1875 if (canTrackArgumentsInterprocedurally(&F)) {
1876 Solver.AddArgumentTrackedFunction(&F);
1877 continue;
Chris Lattnercde8de52009-11-03 19:24:51 +00001878 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001879
1880 // Assume the function is called.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001881 Solver.MarkBlockExecutable(&F.front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001882
Chris Lattnerfb141812009-11-03 03:42:51 +00001883 // Assume nothing about the incoming arguments.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001884 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001885 Solver.markOverdefined(&AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001886 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001887
Matthew Simpson22849372017-10-13 17:53:44 +00001888 // Determine if we can track any of the module's global variables. If so, add
1889 // the global variables we can track to the solver's set of tracked global
1890 // variables.
1891 for (GlobalVariable &G : M.globals()) {
1892 G.removeDeadConstantUsers();
1893 if (canTrackGlobalVariableInterprocedurally(&G))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001894 Solver.TrackValueOfGlobalVariable(&G);
Matthew Simpson22849372017-10-13 17:53:44 +00001895 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001896
Chris Lattnerb4394642004-12-10 08:02:06 +00001897 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001898 bool ResolvedUndefs = true;
1899 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001900 Solver.Solve();
1901
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001902 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001903 ResolvedUndefs = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001904 for (Function &F : M)
1905 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001906 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001907
1908 bool MadeChanges = false;
1909
1910 // Iterate over all of the instructions in the module, replacing them with
1911 // constants if we have found them to be of constant values.
Chris Lattner65938fc2008-08-23 23:36:38 +00001912 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001913
Benjamin Kramer135f7352016-06-26 12:28:59 +00001914 for (Function &F : M) {
1915 if (F.isDeclaration())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001916 continue;
1917
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00001918 if (Solver.isBlockExecutable(&F.front()))
Benjamin Kramer135f7352016-06-26 12:28:59 +00001919 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
Florian Hahnd0208b42017-10-30 10:07:42 +00001920 ++AI) {
Davide Italiano5df80802017-11-21 00:21:52 +00001921 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) {
Davide Italiano6ed6d772016-07-14 01:27:29 +00001922 ++IPNumArgsElimed;
Davide Italiano5df80802017-11-21 00:21:52 +00001923 continue;
1924 }
Florian Hahnf73c3ec2018-03-23 12:49:39 +00001925
1926 if (!AI->use_empty() && tryToReplaceWithConstantRange(Solver, &*AI))
1927 ++IPNumRangeInfoUsed;
Florian Hahnd0208b42017-10-30 10:07:42 +00001928 }
1929
Benjamin Kramer135f7352016-06-26 12:28:59 +00001930 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001931 if (!Solver.isBlockExecutable(&*BB)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001932 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001933
David Majnemer88542a02016-01-24 06:26:47 +00001934 ++NumDeadBlocks;
David Majnemere14e7bc2016-06-25 08:19:55 +00001935 NumInstRemoved +=
1936 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
David Majnemer88542a02016-01-24 06:26:47 +00001937
1938 MadeChanges = true;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001939
Benjamin Kramer135f7352016-06-26 12:28:59 +00001940 if (&*BB != &F.front())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001941 BlocksToErase.push_back(&*BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001942 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001943 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001944
Chris Lattnere405ed92009-11-02 02:47:51 +00001945 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001946 Instruction *Inst = &*BI++;
Davide Italiano7dac0272016-07-14 02:51:41 +00001947 if (Inst->getType()->isVoidTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001948 continue;
Sanjoy Dasff855b62016-08-24 18:10:21 +00001949 if (tryToReplaceWithConstant(Solver, Inst)) {
Chris Bienemanabdea262018-01-09 21:58:46 +00001950 if (Inst->isSafeToRemove())
Sanjoy Dasff855b62016-08-24 18:10:21 +00001951 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001952 // Hey, we just changed something!
1953 MadeChanges = true;
1954 ++IPNumInstRemoved;
1955 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001956 }
1957 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001958
1959 // Now that all instructions in the function are constant folded, erase dead
1960 // blocks, because we can now use ConstantFoldTerminator to get rid of
1961 // in-edges.
1962 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1963 // If there are any PHI nodes in this successor, drop entries for BB now.
1964 BasicBlock *DeadBB = BlocksToErase[i];
Chandler Carruthcdf47882014-03-09 03:16:01 +00001965 for (Value::user_iterator UI = DeadBB->user_begin(),
1966 UE = DeadBB->user_end();
1967 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001968 // Grab the user and then increment the iterator early, as the user
1969 // will be deleted. Step past all adjacent uses from the same user.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001970 auto *I = dyn_cast<Instruction>(*UI);
Dan Gohman1f522d92009-11-23 16:13:39 +00001971 do { ++UI; } while (UI != UE && *UI == I);
1972
Dan Gohmand15302a2009-11-20 20:19:14 +00001973 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001974 if (!I) continue;
1975
Davide Italianodf670a12016-12-06 02:26:50 +00001976 bool Folded = ConstantFoldTerminator(I->getParent());
Davide Italianoe15bffe2018-01-07 22:09:44 +00001977 assert(Folded &&
1978 "Expect TermInst on constantint or blockaddress to be folded");
1979 (void) Folded;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001980 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001981
Chris Lattnerbae4b642004-12-10 22:29:08 +00001982 // Finally, delete the basic block.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001983 F.getBasicBlockList().erase(DeadBB);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001984 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001985 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001986 }
Chris Lattner99e12952004-12-11 02:53:57 +00001987
1988 // If we inferred constant or undef return values for a function, we replaced
1989 // all call uses with the inferred value. This means we don't need to bother
1990 // actually returning anything from the function. Replace all return
1991 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001992 //
1993 // Do this in two stages: first identify the functions we should process, then
1994 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001995 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001996 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001997 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001998 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00001999
Devang Patela7a20752008-03-11 05:46:42 +00002000 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Benjamin Kramer135f7352016-06-26 12:28:59 +00002001 for (const auto &I : RV) {
2002 Function *F = I.first;
2003 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
Chris Lattnerfb141812009-11-03 03:42:51 +00002004 continue;
Matthew Simpson22849372017-10-13 17:53:44 +00002005 findReturnsToZap(*F, ReturnsToZap, Solver);
Davide Italiano15ff2d62016-07-20 20:17:13 +00002006 }
Jakub Staszak632a3552012-01-18 21:16:33 +00002007
Davide Italiano15ff2d62016-07-20 20:17:13 +00002008 for (const auto &F : Solver.getMRVFunctionsTracked()) {
2009 assert(F->getReturnType()->isStructTy() &&
2010 "The return type should be a struct");
2011 StructType *STy = cast<StructType>(F->getReturnType());
2012 if (Solver.isStructLatticeConstant(F, STy))
Matthew Simpson22849372017-10-13 17:53:44 +00002013 findReturnsToZap(*F, ReturnsToZap, Solver);
Chris Lattnerd887f1d2010-02-27 00:07:42 +00002014 }
2015
2016 // Zap all returns which we've identified as zap to change.
2017 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
2018 Function *F = ReturnsToZap[i]->getParent()->getParent();
2019 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00002020 }
Jakub Staszak632a3552012-01-18 21:16:33 +00002021
Chad Rosierbb2a6da2012-03-28 00:35:33 +00002022 // If we inferred constant or undef values for globals variables, we can
2023 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00002024 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2025 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00002026 E = TG.end(); I != E; ++I) {
2027 GlobalVariable *GV = I->first;
2028 assert(!I->second.isOverdefined() &&
2029 "Overdefined values should have been taken out of the map!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002030 LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
2031 << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00002032 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002033 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00002034 SI->eraseFromParent();
2035 }
2036 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00002037 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00002038 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002039
Chris Lattnerb4394642004-12-10 08:02:06 +00002040 return MadeChanges;
2041}