blob: da8b6cfda5f4a25e311899045899060d29883dcb [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-06-27 23:38:11 +000017//
Chris Lattner347389d2001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Davide Italianof54f2f02016-05-05 21:05:36 +000020#include "llvm/Transforms/IPO/SCCP.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000021#include "llvm/Transforms/Scalar/SCCP.h"
22#include "llvm/ADT/ArrayRef.h"
Chris Lattner067d6072007-02-02 20:38:30 +000023#include "llvm/ADT/DenseMap.h"
Chris Lattner65938fc2008-08-23 23:36:38 +000024#include "llvm/ADT/DenseSet.h"
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000025#include "llvm/ADT/PointerIntPair.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000026#include "llvm/ADT/STLExtras.h"
Chris Lattner809aee22009-11-02 06:11:23 +000027#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000028#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000029#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Analysis/ConstantFolding.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000031#include "llvm/Analysis/GlobalsModRef.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Analysis/TargetLibraryInfo.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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include "llvm/Transforms/IPO.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000058#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000060#include <cassert>
61#include <utility>
62#include <vector>
63
Chris Lattner49525f82004-01-09 06:02:20 +000064using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000065
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "sccp"
67
Chris Lattner79a42ac2006-12-19 21:40:18 +000068STATISTIC(NumInstRemoved, "Number of instructions removed");
69STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
70
Nick Lewycky35e92c72008-03-08 07:48:41 +000071STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000072STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
73STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
Florian Hahnd0208b42017-10-30 10:07:42 +000074STATISTIC(IPNumRangeInfoUsed, "Number of times constant range info was used by"
75 "IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000076
Chris Lattner7d325382002-04-29 21:26:08 +000077namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +000078
Chris Lattner1847f6d2006-12-20 06:21:33 +000079/// LatticeVal class - This class represents the different lattice values that
80/// an LLVM value may occupy. It is a simple class with value semantics.
81///
Chris Lattner2dd09db2009-09-02 06:11:42 +000082class LatticeVal {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000083 enum LatticeValueTy {
Davide Italiano0f03ce02016-07-10 00:35:15 +000084 /// unknown - This LLVM Value has no known value yet.
85 unknown,
Jakub Staszak632a3552012-01-18 21:16:33 +000086
Chris Lattner1847f6d2006-12-20 06:21:33 +000087 /// constant - This LLVM Value has a specific constant value.
88 constant,
89
90 /// forcedconstant - This LLVM Value was thought to be undef until
91 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
92 /// with another (different) constant, it goes to overdefined, instead of
93 /// asserting.
94 forcedconstant,
Jakub Staszak632a3552012-01-18 21:16:33 +000095
Chris Lattner1847f6d2006-12-20 06:21:33 +000096 /// overdefined - This instruction is not known to be constant, and we know
97 /// it has a value.
98 overdefined
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000099 };
100
101 /// Val: This stores the current lattice value along with the Constant* for
102 /// the constant if this is a 'constant' or 'forcedconstant' value.
103 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Jakub Staszak632a3552012-01-18 21:16:33 +0000104
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000105 LatticeValueTy getLatticeValue() const {
106 return Val.getInt();
107 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000108
Chris Lattner347389d2001-06-27 23:38:11 +0000109public:
Davide Italiano0f03ce02016-07-10 00:35:15 +0000110 LatticeVal() : Val(nullptr, unknown) {}
Jakub Staszak632a3552012-01-18 21:16:33 +0000111
Davide Italiano0f03ce02016-07-10 00:35:15 +0000112 bool isUnknown() const { return getLatticeValue() == unknown; }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000113
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000114 bool isConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000115 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
116 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000117
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000118 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Jakub Staszak632a3552012-01-18 21:16:33 +0000119
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000120 Constant *getConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000121 assert(isConstant() && "Cannot get the constant of a non-constant!");
122 return Val.getPointer();
123 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000124
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000125 /// markOverdefined - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000126 bool markOverdefined() {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000127 if (isOverdefined())
128 return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000129
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000130 Val.setInt(overdefined);
131 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000132 }
133
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000134 /// markConstant - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000135 bool markConstant(Constant *V) {
Chris Lattnere1d5cd92009-11-03 16:50:11 +0000136 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000137 assert(getConstant() == V && "Marking constant with different value");
138 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000139 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000140
Davide Italiano0f03ce02016-07-10 00:35:15 +0000141 if (isUnknown()) {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000142 Val.setInt(constant);
143 assert(V && "Marking constant with NULL");
144 Val.setPointer(V);
145 } else {
Jakub Staszak632a3552012-01-18 21:16:33 +0000146 assert(getLatticeValue() == forcedconstant &&
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000147 "Cannot move from overdefined to constant!");
148 // Stay at forcedconstant if the constant is the same.
149 if (V == getConstant()) return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000150
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000151 // Otherwise, we go to overdefined. Assumptions made based on the
152 // forced value are possibly wrong. Assuming this is another constant
153 // could expose a contradiction.
154 Val.setInt(overdefined);
155 }
156 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000157 }
158
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000159 /// getConstantInt - If this is a constant with a ConstantInt value, return it
160 /// otherwise return null.
161 ConstantInt *getConstantInt() const {
162 if (isConstant())
163 return dyn_cast<ConstantInt>(getConstant());
Craig Topperf40110f2014-04-25 05:29:35 +0000164 return nullptr;
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000165 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000166
Xin Tong34888c02017-04-10 00:33:25 +0000167 /// getBlockAddress - If this is a constant with a BlockAddress value, return
168 /// it, otherwise return null.
169 BlockAddress *getBlockAddress() const {
170 if (isConstant())
171 return dyn_cast<BlockAddress>(getConstant());
172 return nullptr;
173 }
174
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000175 void markForcedConstant(Constant *V) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000176 assert(isUnknown() && "Can't force a defined value!");
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000177 Val.setInt(forcedconstant);
178 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000179 }
Florian Hahnd0208b42017-10-30 10:07:42 +0000180
181 ValueLatticeElement toValueLattice() const {
182 if (isOverdefined())
183 return ValueLatticeElement::getOverdefined();
184 if (isConstant())
185 return ValueLatticeElement::get(getConstant());
186 return ValueLatticeElement();
187 }
Chris Lattner347389d2001-06-27 23:38:11 +0000188};
189
Chris Lattner347389d2001-06-27 23:38:11 +0000190//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000191//
Chris Lattner074be1f2004-11-15 04:44:20 +0000192/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
193/// Constant Propagation.
194///
195class SCCPSolver : public InstVisitor<SCCPSolver> {
Mehdi Amini46a43552015-03-04 18:43:29 +0000196 const DataLayout &DL;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000197 const TargetLibraryInfo *TLI;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000198 SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
199 DenseMap<Value *, LatticeVal> ValueState; // The state each value is in.
Florian Hahnd0208b42017-10-30 10:07:42 +0000200 // The state each parameter is in.
201 DenseMap<Value *, ValueLatticeElement> ParamState;
Chris Lattner347389d2001-06-27 23:38:11 +0000202
Chris Lattner156b8c72009-11-03 23:40:48 +0000203 /// StructValueState - This maintains ValueState for values that have
204 /// StructType, for example for formal arguments, calls, insertelement, etc.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000205 DenseMap<std::pair<Value *, unsigned>, LatticeVal> StructValueState;
Jakub Staszak632a3552012-01-18 21:16:33 +0000206
Chris Lattner91dbae62004-12-11 05:15:59 +0000207 /// GlobalValue - If we are tracking any values for the contents of a global
208 /// variable, we keep a mapping from the constant accessor to the element of
209 /// the global, to the currently known value. If the value becomes
210 /// overdefined, it's entry is simply removed from this map.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000211 DenseMap<GlobalVariable *, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000212
Devang Patela7a20752008-03-11 05:46:42 +0000213 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000214 /// value out of a function, it will have an entry in this map, indicating
215 /// what the known return value for the function is.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000216 DenseMap<Function *, LatticeVal> TrackedRetVals;
Devang Patela7a20752008-03-11 05:46:42 +0000217
218 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
219 /// that return multiple values.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000220 DenseMap<std::pair<Function *, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak632a3552012-01-18 21:16:33 +0000221
Chris Lattner156b8c72009-11-03 23:40:48 +0000222 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
223 /// represented here for efficient lookup.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000224 SmallPtrSet<Function *, 16> MRVFunctionsTracked;
Chris Lattnerb4394642004-12-10 08:02:06 +0000225
Reid Kleckner3762a082018-03-01 01:19:18 +0000226 /// MustTailFunctions - Each function here is a callee of non-removable
227 /// musttail call site.
228 SmallPtrSet<Function *, 16> MustTailCallees;
229
Chris Lattner2c427232009-11-03 20:52:57 +0000230 /// TrackingIncomingArguments - This is the set of functions for whose
231 /// arguments we make optimistic assumptions about and try to prove as
232 /// constants.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000233 SmallPtrSet<Function *, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000234
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000235 /// The reason for two worklists is that overdefined is the lowest state
236 /// on the lattice, and moving things to overdefined as fast as possible
237 /// makes SCCP converge much faster.
238 ///
239 /// By having a separate worklist, we accomplish this because everything
240 /// possibly overdefined will become overdefined at the soonest possible
241 /// point.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000242 SmallVector<Value *, 64> OverdefinedInstWorkList;
243 SmallVector<Value *, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000244
Eugene Zelenko99241d72017-10-20 21:47:29 +0000245 // The BasicBlock work list
246 SmallVector<BasicBlock *, 64> BBWorkList;
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000247
248 /// KnownFeasibleEdges - Entries in this set are edges which have already had
249 /// PHI nodes retriggered.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000250 using Edge = std::pair<BasicBlock *, BasicBlock *>;
Chris Lattner65938fc2008-08-23 23:36:38 +0000251 DenseSet<Edge> KnownFeasibleEdges;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000252
Chris Lattner347389d2001-06-27 23:38:11 +0000253public:
Mehdi Amini46a43552015-03-04 18:43:29 +0000254 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
255 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000256
Chris Lattner074be1f2004-11-15 04:44:20 +0000257 /// MarkBlockExecutable - This method can be used by clients to mark all of
258 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000259 ///
260 /// This returns true if the block was not considered live before.
261 bool MarkBlockExecutable(BasicBlock *BB) {
David Blaikie70573dc2014-11-19 07:49:26 +0000262 if (!BBExecutable.insert(BB).second)
263 return false;
Nick Lewycky5cd95382013-06-26 00:30:18 +0000264 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000265 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000266 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000267 }
268
Chris Lattner91dbae62004-12-11 05:15:59 +0000269 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000270 /// inform the SCCPSolver that it should track loads and stores to the
271 /// specified global variable if it can. This is only legal to call if
272 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000273 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000274 // We only track the contents of scalar globals.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000275 if (GV->getValueType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000276 LatticeVal &IV = TrackedGlobals[GV];
277 if (!isa<UndefValue>(GV->getInitializer()))
278 IV.markConstant(GV->getInitializer());
279 }
280 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000281
282 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
283 /// and out of the specified function (which cannot have its address taken),
284 /// this method must be called.
285 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000286 // Add an entry, F -> undef.
Davide Italianoe3bdd612016-12-01 08:36:12 +0000287 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000288 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000289 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000290 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
291 LatticeVal()));
292 } else
293 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000294 }
295
Reid Kleckner3762a082018-03-01 01:19:18 +0000296 /// AddMustTailCallee - If the SCCP solver finds that this function is called
297 /// from non-removable musttail call site.
298 void AddMustTailCallee(Function *F) {
299 MustTailCallees.insert(F);
300 }
301
302 /// Returns true if the given function is called from non-removable musttail
303 /// call site.
304 bool isMustTailCallee(Function *F) {
305 return MustTailCallees.count(F);
306 }
307
Chris Lattnercde8de52009-11-03 19:24:51 +0000308 void AddArgumentTrackedFunction(Function *F) {
309 TrackingIncomingArguments.insert(F);
310 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000311
Matthew Simpson22849372017-10-13 17:53:44 +0000312 /// Returns true if the given function is in the solver's set of
313 /// argument-tracked functions.
314 bool isArgumentTrackedFunction(Function *F) {
315 return TrackingIncomingArguments.count(F);
316 }
317
Chris Lattner074be1f2004-11-15 04:44:20 +0000318 /// Solve - Solve for constants and executable blocks.
Chris Lattner074be1f2004-11-15 04:44:20 +0000319 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000320
Chris Lattner1847f6d2006-12-20 06:21:33 +0000321 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000322 /// that branches on undef values cannot reach any of their successors.
323 /// However, this is not a safe assumption. After we solve dataflow, this
324 /// method should be use to handle this. If this returns true, the solver
325 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000326 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000327
Chris Lattneradd44f32008-08-23 23:39:31 +0000328 bool isBlockExecutable(BasicBlock *BB) const {
329 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000330 }
331
Davide Italiano00802692016-07-12 19:54:19 +0000332 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
333 std::vector<LatticeVal> StructValues;
Davide Italianoe3bdd612016-12-01 08:36:12 +0000334 auto *STy = dyn_cast<StructType>(V->getType());
Davide Italiano00802692016-07-12 19:54:19 +0000335 assert(STy && "getStructLatticeValueFor() can be called only on structs");
336 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
337 auto I = StructValueState.find(std::make_pair(V, i));
338 assert(I != StructValueState.end() && "Value not in valuemap!");
339 StructValues.push_back(I->second);
340 }
341 return StructValues;
342 }
343
Florian Hahnd0208b42017-10-30 10:07:42 +0000344 ValueLatticeElement getLatticeValueFor(Value *V) {
345 assert(!V->getType()->isStructTy() &&
346 "Should use getStructLatticeValueFor");
347 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
348 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
349 ValueLatticeElement &LV = PI.first->second;
350 if (PI.second) {
351 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
352 assert(I != ValueState.end() &&
353 "V not found in ValueState nor Paramstate map!");
354 LV = I->second.toValueLattice();
355 }
356
357 return LV;
Chris Lattner074be1f2004-11-15 04:44:20 +0000358 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000359
Devang Patela7a20752008-03-11 05:46:42 +0000360 /// getTrackedRetVals - Get the inferred return value map.
Devang Patela7a20752008-03-11 05:46:42 +0000361 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
362 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000363 }
364
Chris Lattner91dbae62004-12-11 05:15:59 +0000365 /// getTrackedGlobals - Get and return the set of inferred initializers for
366 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000367 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000368 return TrackedGlobals;
369 }
370
Davide Italiano15ff2d62016-07-20 20:17:13 +0000371 /// getMRVFunctionsTracked - Get the set of functions which return multiple
372 /// values tracked by the pass.
373 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
374 return MRVFunctionsTracked;
375 }
376
Reid Kleckner3762a082018-03-01 01:19:18 +0000377 /// getMustTailCallees - Get the set of functions which are called
378 /// from non-removable musttail call sites.
379 const SmallPtrSet<Function *, 16> getMustTailCallees() {
380 return MustTailCallees;
381 }
382
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000383 /// markOverdefined - Mark the specified value overdefined. This
Chris Lattner156b8c72009-11-03 23:40:48 +0000384 /// works with both scalars and structs.
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000385 void markOverdefined(Value *V) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000386 if (auto *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000387 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
388 markOverdefined(getStructValueState(V, i), V);
389 else
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000390 markOverdefined(ValueState[V], V);
Chris Lattner156b8c72009-11-03 23:40:48 +0000391 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000392
Davide Italiano15ff2d62016-07-20 20:17:13 +0000393 // isStructLatticeConstant - Return true if all the lattice values
394 // corresponding to elements of the structure are not overdefined,
395 // false otherwise.
396 bool isStructLatticeConstant(Function *F, StructType *STy) {
397 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
398 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
399 assert(It != TrackedMultipleRetVals.end());
400 LatticeVal LV = It->second;
401 if (LV.isOverdefined())
402 return false;
403 }
404 return true;
405 }
406
Chris Lattner347389d2001-06-27 23:38:11 +0000407private:
Davide Italiano0a1476c2016-12-11 21:19:03 +0000408 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
Davide Italiano390b7ea2016-07-13 19:33:25 +0000409 void pushToWorkList(LatticeVal &IV, Value *V) {
410 if (IV.isOverdefined())
411 return OverdefinedInstWorkList.push_back(V);
412 InstWorkList.push_back(V);
413 }
414
Chris Lattnerd79334d2004-07-15 23:36:43 +0000415 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000416 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000417 // the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000418 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
419 if (!IV.markConstant(C)) return;
David Greene389fc3b2010-01-05 01:27:15 +0000420 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000421 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000422 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000423
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000424 void markConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000425 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerb4394642004-12-10 08:02:06 +0000426 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000427 }
428
Chris Lattnerf5484032009-11-02 05:55:40 +0000429 void markForcedConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000430 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000431 LatticeVal &IV = ValueState[V];
432 IV.markForcedConstant(C);
David Greene389fc3b2010-01-05 01:27:15 +0000433 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000434 pushToWorkList(IV, V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000435 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000436
Chris Lattnerd79334d2004-07-15 23:36:43 +0000437 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000438 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000439 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000440 void markOverdefined(LatticeVal &IV, Value *V) {
441 if (!IV.markOverdefined()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000442
David Greene389fc3b2010-01-05 01:27:15 +0000443 DEBUG(dbgs() << "markOverdefined: ";
Davide Italianoe3bdd612016-12-01 08:36:12 +0000444 if (auto *F = dyn_cast<Function>(V))
David Greene389fc3b2010-01-05 01:27:15 +0000445 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000446 else
David Greene389fc3b2010-01-05 01:27:15 +0000447 dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000448 // Only instructions go on the work list
Davide Italiano0a1476c2016-12-11 21:19:03 +0000449 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000450 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000451
Chris Lattnerf5484032009-11-02 05:55:40 +0000452 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000453 if (IV.isOverdefined() || MergeWithV.isUnknown())
Chris Lattnerb4394642004-12-10 08:02:06 +0000454 return; // Noop.
455 if (MergeWithV.isOverdefined())
Davide Italiano21850012016-07-13 19:23:30 +0000456 return markOverdefined(IV, V);
457 if (IV.isUnknown())
458 return markConstant(IV, V, MergeWithV.getConstant());
459 if (IV.getConstant() != MergeWithV.getConstant())
460 return markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000461 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000462
Chris Lattnerf5484032009-11-02 05:55:40 +0000463 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Davide Italiano63266b62016-07-19 18:31:07 +0000464 assert(!V->getType()->isStructTy() &&
465 "non-structs should use markConstant");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000466 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000467 }
468
Chris Lattnerf5484032009-11-02 05:55:40 +0000469 /// getValueState - Return the LatticeVal object that corresponds to the
470 /// value. This function handles the case when the value hasn't been seen yet
471 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000472 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000473 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000474
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000475 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
476 ValueState.insert(std::make_pair(V, LatticeVal()));
477 LatticeVal &LV = I.first->second;
478
479 if (!I.second)
480 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000481
Davide Italianoe3bdd612016-12-01 08:36:12 +0000482 if (auto *C = dyn_cast<Constant>(V)) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000483 // Undef values remain unknown.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000484 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000485 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000486 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000487
Chris Lattnera3c39d32009-11-02 02:33:50 +0000488 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000489 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000490 }
491
Florian Hahnd0208b42017-10-30 10:07:42 +0000492 ValueLatticeElement &getParamState(Value *V) {
493 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
494
495 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
496 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
497 ValueLatticeElement &LV = PI.first->second;
498 if (PI.second)
499 LV = getValueState(V).toValueLattice();
500
501 return LV;
502 }
503
Chris Lattner156b8c72009-11-03 23:40:48 +0000504 /// getStructValueState - Return the LatticeVal object that corresponds to the
505 /// value/field pair. This function handles the case when the value hasn't
506 /// been seen yet by properly seeding constants etc.
507 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000508 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000509 assert(i < cast<StructType>(V->getType())->getNumElements() &&
510 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000511
512 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
513 bool> I = StructValueState.insert(
514 std::make_pair(std::make_pair(V, i), LatticeVal()));
515 LatticeVal &LV = I.first->second;
516
517 if (!I.second)
518 return LV; // Common case, already in the map.
519
Davide Italianoe3bdd612016-12-01 08:36:12 +0000520 if (auto *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000521 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000522
Craig Topperf40110f2014-04-25 05:29:35 +0000523 if (!Elt)
Chris Lattner156b8c72009-11-03 23:40:48 +0000524 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000525 else if (isa<UndefValue>(Elt))
Davide Italiano0f03ce02016-07-10 00:35:15 +0000526 ; // Undef values remain unknown.
Chris Lattnerfa775002012-01-26 02:32:04 +0000527 else
528 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000529 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000530
Chris Lattner156b8c72009-11-03 23:40:48 +0000531 // All others are underdefined by default.
532 return LV;
533 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000534
Chris Lattnerf5484032009-11-02 05:55:40 +0000535 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
536 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000537 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
538 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
539 return; // This edge is already known to be executable!
540
Chris Lattner809aee22009-11-02 06:11:23 +0000541 if (!MarkBlockExecutable(Dest)) {
542 // If the destination is already executable, we just made an *edge*
543 // feasible that wasn't before. Revisit the PHI nodes in the block
544 // because they have potentially new operands.
David Greene389fc3b2010-01-05 01:27:15 +0000545 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Nick Lewycky5cd95382013-06-26 00:30:18 +0000546 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000547
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000548 for (PHINode &PN : Dest->phis())
549 visitPHINode(PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000550 }
Chris Lattner347389d2001-06-27 23:38:11 +0000551 }
552
Chris Lattner074be1f2004-11-15 04:44:20 +0000553 // getFeasibleSuccessors - Return a vector of booleans to indicate which
554 // successors are reachable from a given terminator instruction.
Craig Topperb94011f2013-07-14 04:42:23 +0000555 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000556
557 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000558 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000559 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
560
561 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000562 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000563 // information, we need to update the specified user of this instruction.
Chris Lattnerfb141812009-11-03 03:42:51 +0000564 void OperandChangedState(Instruction *I) {
565 if (BBExecutable.count(I->getParent())) // Inst is executable?
566 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000567 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000568
Chris Lattner074be1f2004-11-15 04:44:20 +0000569private:
570 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000571
Chris Lattnera3c39d32009-11-02 02:33:50 +0000572 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000573 // operand made a transition, or the instruction is newly executable. Change
574 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000575 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000576
577 // Terminators
Eugene Zelenko99241d72017-10-20 21:47:29 +0000578
Chris Lattnerb4394642004-12-10 08:02:06 +0000579 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000580 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000581
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000582 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000583 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000584 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000585 void visitCmpInst(CmpInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000586 void visitExtractValueInst(ExtractValueInst &EVI);
587 void visitInsertValueInst(InsertValueInst &IVI);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000588
David Majnemer8a1c45d2015-12-12 05:38:55 +0000589 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000590 markOverdefined(&CPI);
David Majnemereb518bd2015-08-04 08:21:40 +0000591 visitTerminatorInst(CPI);
592 }
Chris Lattner6e560792002-04-18 15:13:15 +0000593
Chris Lattnera3c39d32009-11-02 02:33:50 +0000594 // Instructions that cannot be folded away.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000595
Chris Lattnerf5484032009-11-02 05:55:40 +0000596 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000597 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000598 void visitGetElementPtrInst(GetElementPtrInst &I);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000599
Victor Hernandeze2971492009-10-24 04:23:03 +0000600 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000601 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000602 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000603
Chris Lattnerb4394642004-12-10 08:02:06 +0000604 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000605 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000606 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000607 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000608
Chris Lattnerb4394642004-12-10 08:02:06 +0000609 void visitCallSite (CallSite CS);
Davide Italianoa7f5e882016-05-04 23:27:13 +0000610 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
611 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
612 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000613
Chris Lattner113f4f42002-06-25 16:13:24 +0000614 void visitInstruction(Instruction &I) {
Davide Italiano0b1190a2017-06-16 20:27:17 +0000615 // All the instructions we don't do any special handling for just
616 // go to overdefined.
Davide Italiano463bebc2016-12-13 05:56:04 +0000617 DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
Davide Italiano0b1190a2017-06-16 20:27:17 +0000618 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000619 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000620};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000621
Duncan Sands2be91fc2007-07-20 08:56:21 +0000622} // end anonymous namespace
623
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000624// getFeasibleSuccessors - Return a vector of booleans to indicate which
625// successors are reachable from a given terminator instruction.
Chris Lattner074be1f2004-11-15 04:44:20 +0000626void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000627 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000628 Succs.resize(TI.getNumSuccessors());
Davide Italianoe3bdd612016-12-01 08:36:12 +0000629 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000630 if (BI->isUnconditional()) {
631 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000632 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000633 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000634
Chris Lattnerf5484032009-11-02 05:55:40 +0000635 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000636 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000637 if (!CI) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000638 // Overdefined condition variables, and branches on unfoldable constant
639 // conditions, mean the branch could go either way.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000640 if (!BCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000641 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000642 return;
643 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000644
Chris Lattner6df5cec2009-11-02 02:30:06 +0000645 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000646 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000647 return;
648 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000649
David Majnemer654e1302015-07-31 17:58:14 +0000650 // Unwinding instructions successors are always executable.
651 if (TI.isExceptional()) {
652 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattneree8b9512009-10-29 01:21:20 +0000653 return;
654 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000655
Davide Italianoe3bdd612016-12-01 08:36:12 +0000656 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000657 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000658 Succs[0] = true;
659 return;
660 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000661 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000662 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000663
Davide Italiano0f03ce02016-07-10 00:35:15 +0000664 if (!CI) { // Overdefined or unknown condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000665 // All destinations are executable!
Davide Italiano0f03ce02016-07-10 00:35:15 +0000666 if (!SCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000667 Succs.assign(TI.getNumSuccessors(), true);
668 return;
669 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000670
Chandler Carruth927d8e62017-04-12 07:27:28 +0000671 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000672 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000673 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000674
Xin Tong34888c02017-04-10 00:33:25 +0000675 // In case of indirect branch and its address is a blockaddress, we mark
676 // the target as executable.
677 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
678 // Casts are folded by visitCastInst.
679 LatticeVal IBRValue = getValueState(IBR->getAddress());
680 BlockAddress *Addr = IBRValue.getBlockAddress();
681 if (!Addr) { // Overdefined or unknown condition?
682 // All destinations are executable!
683 if (!IBRValue.isUnknown())
684 Succs.assign(TI.getNumSuccessors(), true);
685 return;
686 }
687
688 BasicBlock* T = Addr->getBasicBlock();
689 assert(Addr->getFunction() == T->getParent() &&
690 "Block address of a different function ?");
691 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
692 // This is the target.
693 if (IBR->getDestination(i) == T) {
694 Succs[i] = true;
695 return;
696 }
697 }
698
699 // If we didn't find our destination in the IBR successor list, then we
700 // have undefined behavior. Its ok to assume no successor is executable.
Chris Lattneree8b9512009-10-29 01:21:20 +0000701 return;
702 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000703
Davide Italiano33af6fe2016-12-01 08:48:14 +0000704 DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
Chris Lattneree8b9512009-10-29 01:21:20 +0000705 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000706}
707
Chris Lattner13b52e72002-05-02 21:18:01 +0000708// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000709// block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000710bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000711 assert(BBExecutable.count(To) && "Dest should always be alive!");
712
713 // Make sure the source basic block is executable!!
714 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000715
Chris Lattnera3c39d32009-11-02 02:33:50 +0000716 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000717 TerminatorInst *TI = From->getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +0000718 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000719 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000720 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000721
Chris Lattnerf5484032009-11-02 05:55:40 +0000722 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000723
Chris Lattner6df5cec2009-11-02 02:30:06 +0000724 // Overdefined condition variables mean the branch could go either way,
725 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000726 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000727 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000728 return !BCValue.isUnknown();
Jakub Staszak632a3552012-01-18 21:16:33 +0000729
Chris Lattner6df5cec2009-11-02 02:30:06 +0000730 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000731 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000732 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000733
David Majnemer654e1302015-07-31 17:58:14 +0000734 // Unwinding instructions successors are always executable.
735 if (TI->isExceptional())
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000736 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000737
Davide Italianoe3bdd612016-12-01 08:36:12 +0000738 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000739 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000740 return true;
741
Chris Lattnerf5484032009-11-02 05:55:40 +0000742 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000743 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000744
Craig Topperf40110f2014-04-25 05:29:35 +0000745 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000746 return !SCValue.isUnknown();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000747
Chandler Carruth927d8e62017-04-12 07:27:28 +0000748 return SI->findCaseValue(CI)->getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000749 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000750
Xin Tong34888c02017-04-10 00:33:25 +0000751 // In case of indirect branch and its address is a blockaddress, we mark
752 // the target as executable.
753 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
754 LatticeVal IBRValue = getValueState(IBR->getAddress());
755 BlockAddress *Addr = IBRValue.getBlockAddress();
756
757 if (!Addr)
758 return !IBRValue.isUnknown();
759
760 // At this point, the indirectbr is branching on a blockaddress.
761 return Addr->getBasicBlock() == To;
762 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000763
Davide Italiano33af6fe2016-12-01 08:48:14 +0000764 DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
Davide Italianodd04fee2015-11-25 21:03:36 +0000765 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattner13b52e72002-05-02 21:18:01 +0000766}
Chris Lattner347389d2001-06-27 23:38:11 +0000767
Chris Lattnera3c39d32009-11-02 02:33:50 +0000768// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000769// operand made a transition, or the instruction is newly executable. Change
770// the value type of I to reflect these changes if appropriate. This method
771// makes sure to do the following actions:
772//
773// 1. If a phi node merges two constants in, and has conflicting value coming
774// from different branches, or if the PHI node merges in an overdefined
775// value, then the PHI node becomes overdefined.
776// 2. If a phi node merges only constants in, and they all agree on value, the
777// PHI node becomes a constant value equal to that.
778// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
779// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
780// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
781// 6. If a conditional branch has a value that is constant, make the selected
782// destination executable
783// 7. If a conditional branch has a value that is overdefined, make all
784// successors executable.
Chris Lattner074be1f2004-11-15 04:44:20 +0000785void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000786 // If this PN returns a struct, just mark the result overdefined.
787 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000788 if (PN.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000789 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000790
Eli Friedman0a309292011-11-11 01:16:15 +0000791 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000792 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000793
Chris Lattner7a7b1142004-03-16 19:49:59 +0000794 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
795 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000796 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000797 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000798
Chris Lattner6e560792002-04-18 15:13:15 +0000799 // Look at all of the executable operands of the PHI node. If any of them
800 // are overdefined, the PHI becomes overdefined as well. If they are all
801 // constant, and they agree with each other, the PHI becomes the identical
802 // constant. If they are constant and don't agree, the PHI is overdefined.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000803 // If there are no executable operands, the PHI remains unknown.
Craig Topperf40110f2014-04-25 05:29:35 +0000804 Constant *OperandVal = nullptr;
Chris Lattnercccc5c72003-04-25 02:50:03 +0000805 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000806 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +0000807 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000808
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000809 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
810 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000811
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000812 if (IV.isOverdefined()) // PHI node becomes overdefined!
813 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000814
Craig Topperf40110f2014-04-25 05:29:35 +0000815 if (!OperandVal) { // Grab the first value.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000816 OperandVal = IV.getConstant();
817 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000818 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000819
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000820 // There is already a reachable operand. If we conflict with it,
821 // then the PHI node becomes overdefined. If we agree with it, we
822 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000823
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000824 // Check to see if there are two different constants merging, if so, the PHI
825 // node is overdefined.
826 if (IV.getConstant() != OperandVal)
827 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000828 }
829
Chris Lattner6e560792002-04-18 15:13:15 +0000830 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000831 // arguments that agree with each other(and OperandVal is the constant) or
832 // OperandVal is null because there are no defined incoming arguments. If
Davide Italiano0f03ce02016-07-10 00:35:15 +0000833 // this is the case, the PHI remains unknown.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000834 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000835 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000836}
837
Chris Lattnerb4394642004-12-10 08:02:06 +0000838void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000839 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000840
Chris Lattnerb4394642004-12-10 08:02:06 +0000841 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000842 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000843
Devang Patela7a20752008-03-11 05:46:42 +0000844 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000845 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000846 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000847 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000848 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000849 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000850 return;
851 }
852 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000853
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000854 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000855 if (!TrackedMultipleRetVals.empty()) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000856 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000857 if (MRVFunctionsTracked.count(F))
858 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
859 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
860 getStructValueState(ResultOp, i));
Chris Lattnerb4394642004-12-10 08:02:06 +0000861 }
862}
863
Chris Lattner074be1f2004-11-15 04:44:20 +0000864void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000865 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000866 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000867
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000868 BasicBlock *BB = TI.getParent();
869
Chris Lattnera3c39d32009-11-02 02:33:50 +0000870 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000871 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000872 if (SuccFeasible[i])
873 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000874}
875
Chris Lattner074be1f2004-11-15 04:44:20 +0000876void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000877 LatticeVal OpSt = getValueState(I.getOperand(0));
878 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000879 markOverdefined(&I);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000880 else if (OpSt.isConstant()) {
Davide Italianod555bde2016-07-08 19:13:40 +0000881 // Fold the constant as we build.
Davide Italiano63c4ce82016-07-11 18:21:29 +0000882 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
883 I.getType(), DL);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000884 if (isa<UndefValue>(C))
885 return;
886 // Propagate constant value
887 markConstant(&I, C);
888 }
Chris Lattner6e560792002-04-18 15:13:15 +0000889}
890
Dan Gohman041f9d02008-06-20 01:15:44 +0000891void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000892 // If this returns a struct, mark all elements over defined, we don't track
893 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000894 if (EVI.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000895 return markOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000896
Chris Lattner156b8c72009-11-03 23:40:48 +0000897 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000898 if (EVI.getNumIndices() != 1)
899 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000900
Chris Lattner156b8c72009-11-03 23:40:48 +0000901 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000902 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000903 unsigned i = *EVI.idx_begin();
904 LatticeVal EltVal = getStructValueState(AggVal, i);
905 mergeInValue(getValueState(&EVI), &EVI, EltVal);
906 } else {
907 // Otherwise, must be extracting from an array.
908 return markOverdefined(&EVI);
909 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000910}
911
912void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000913 auto *STy = dyn_cast<StructType>(IVI.getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000914 if (!STy)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000915 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000916
Chris Lattner156b8c72009-11-03 23:40:48 +0000917 // If this has more than one index, we can't handle it, drive all results to
918 // undef.
919 if (IVI.getNumIndices() != 1)
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000920 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000921
Chris Lattner156b8c72009-11-03 23:40:48 +0000922 Value *Aggr = IVI.getAggregateOperand();
923 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000924
Chris Lattner156b8c72009-11-03 23:40:48 +0000925 // Compute the result based on what we're inserting.
926 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
927 // This passes through all values that aren't the inserted element.
928 if (i != Idx) {
929 LatticeVal EltVal = getStructValueState(Aggr, i);
930 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
931 continue;
932 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000933
Chris Lattner156b8c72009-11-03 23:40:48 +0000934 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000935 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000936 // We don't track structs in structs.
937 markOverdefined(getStructValueState(&IVI, i), &IVI);
938 else {
939 LatticeVal InVal = getValueState(Val);
940 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
941 }
942 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000943}
944
Chris Lattner074be1f2004-11-15 04:44:20 +0000945void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000946 // If this select returns a struct, just mark the result overdefined.
947 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000948 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000949 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000950
Chris Lattnerf5484032009-11-02 05:55:40 +0000951 LatticeVal CondValue = getValueState(I.getCondition());
Davide Italiano0f03ce02016-07-10 00:35:15 +0000952 if (CondValue.isUnknown())
Chris Lattner06a0ed12006-02-08 02:38:11 +0000953 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000954
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000955 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000956 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
957 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000958 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000959 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000960
Chris Lattner06a0ed12006-02-08 02:38:11 +0000961 // Otherwise, the condition is overdefined or a constant we can't evaluate.
962 // See if we can produce something better than overdefined based on the T/F
963 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000964 LatticeVal TVal = getValueState(I.getTrueValue());
965 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000966
Chris Lattner06a0ed12006-02-08 02:38:11 +0000967 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000968 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000969 TVal.getConstant() == FVal.getConstant())
970 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000971
Davide Italiano0f03ce02016-07-10 00:35:15 +0000972 if (TVal.isUnknown()) // select ?, undef, X -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000973 return mergeInValue(&I, FVal);
Davide Italiano0f03ce02016-07-10 00:35:15 +0000974 if (FVal.isUnknown()) // select ?, X, undef -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000975 return mergeInValue(&I, TVal);
976 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000977}
978
Chris Lattnerf5484032009-11-02 05:55:40 +0000979// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000980void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000981 LatticeVal V1State = getValueState(I.getOperand(0));
982 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000983
Chris Lattner4f031622004-11-15 05:03:30 +0000984 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000985 if (IV.isOverdefined()) return;
986
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000987 if (V1State.isConstant() && V2State.isConstant()) {
988 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
989 V2State.getConstant());
990 // X op Y -> undef.
991 if (isa<UndefValue>(C))
992 return;
993 return markConstant(IV, &I, C);
994 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000995
Chris Lattnerf5484032009-11-02 05:55:40 +0000996 // If something is undef, wait for it to resolve.
997 if (!V1State.isOverdefined() && !V2State.isOverdefined())
998 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000999
Chris Lattnerf5484032009-11-02 05:55:40 +00001000 // Otherwise, one of our operands is overdefined. Try to produce something
1001 // better than overdefined with some tricks.
Davide Italiano6c2c3e02017-01-19 23:07:51 +00001002 // If this is 0 / Y, it doesn't matter that the second operand is
1003 // overdefined, and we can replace it with zero.
1004 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
1005 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
1006 return markConstant(IV, &I, V1State.getConstant());
1007
Davide Italiano93c6c182017-01-19 21:07:42 +00001008 // If this is:
1009 // -> AND/MUL with 0
1010 // -> OR with -1
1011 // it doesn't matter that the other operand is overdefined.
Davide Italiano824d6952016-12-09 03:08:42 +00001012 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
1013 I.getOpcode() == Instruction::Or) {
Craig Topperf40110f2014-04-25 05:29:35 +00001014 LatticeVal *NonOverdefVal = nullptr;
Chris Lattnerf5484032009-11-02 05:55:40 +00001015 if (!V1State.isOverdefined())
1016 NonOverdefVal = &V1State;
1017 else if (!V2State.isOverdefined())
1018 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +00001019
Chris Lattnerf5484032009-11-02 05:55:40 +00001020 if (NonOverdefVal) {
Davide Italianoe7ffae92016-11-22 22:11:25 +00001021 if (NonOverdefVal->isUnknown())
Chris Lattnerf5484032009-11-02 05:55:40 +00001022 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001023
Davide Italiano824d6952016-12-09 03:08:42 +00001024 if (I.getOpcode() == Instruction::And ||
1025 I.getOpcode() == Instruction::Mul) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001026 // X and 0 = 0
Davide Italiano824d6952016-12-09 03:08:42 +00001027 // X * 0 = 0
Chris Lattnerf5484032009-11-02 05:55:40 +00001028 if (NonOverdefVal->getConstant()->isNullValue())
1029 return markConstant(IV, &I, NonOverdefVal->getConstant());
1030 } else {
Davide Italianoe7ffae92016-11-22 22:11:25 +00001031 // X or -1 = -1
Chris Lattnerf5484032009-11-02 05:55:40 +00001032 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
Craig Topper79ab6432017-07-06 18:39:47 +00001033 if (CI->isMinusOne())
Chris Lattnerf5484032009-11-02 05:55:40 +00001034 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +00001035 }
1036 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001037 }
Chris Lattnercbc01612004-12-11 23:15:19 +00001038
Chris Lattnerf5484032009-11-02 05:55:40 +00001039 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +00001040}
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001041
Chris Lattnera3c39d32009-11-02 02:33:50 +00001042// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001043void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001044 LatticeVal V1State = getValueState(I.getOperand(0));
1045 LatticeVal V2State = getValueState(I.getOperand(1));
1046
Reid Spencer266e42b2006-12-23 06:05:41 +00001047 LatticeVal &IV = ValueState[&I];
1048 if (IV.isOverdefined()) return;
1049
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001050 if (V1State.isConstant() && V2State.isConstant()) {
1051 Constant *C = ConstantExpr::getCompare(
1052 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
1053 if (isa<UndefValue>(C))
1054 return;
1055 return markConstant(IV, &I, C);
1056 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001057
Davide Italiano0f03ce02016-07-10 00:35:15 +00001058 // If operands are still unknown, wait for it to resolve.
Chris Lattnerf5484032009-11-02 05:55:40 +00001059 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1060 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001061
Chris Lattnerf5484032009-11-02 05:55:40 +00001062 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +00001063}
1064
Chris Lattnera3c39d32009-11-02 02:33:50 +00001065// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001066// can turn this into a getelementptr ConstantExpr.
Chris Lattner074be1f2004-11-15 04:44:20 +00001067void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001068 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001069
Chris Lattner0e7ec672007-02-02 20:51:48 +00001070 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001071 Operands.reserve(I.getNumOperands());
1072
1073 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001074 LatticeVal State = getValueState(I.getOperand(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001075 if (State.isUnknown())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001076 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001077
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001078 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001079 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001080
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001081 assert(State.isConstant() && "Unknown state!");
1082 Operands.push_back(State.getConstant());
1083 }
1084
1085 Constant *Ptr = Operands[0];
Craig Toppere1d12942014-08-27 05:25:25 +00001086 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001087 Constant *C =
1088 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1089 if (isa<UndefValue>(C))
1090 return;
1091 markConstant(&I, C);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001092}
Brian Gaeke960707c2003-11-11 22:41:34 +00001093
Chris Lattnerf5484032009-11-02 05:55:40 +00001094void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001095 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001096 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001097 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001098
Chris Lattner91dbae62004-12-11 05:15:59 +00001099 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1100 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001101
Chris Lattner91dbae62004-12-11 05:15:59 +00001102 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001103 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001104 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1105
Chris Lattnerf5484032009-11-02 05:55:40 +00001106 // Get the value we are storing into the global, then merge it.
1107 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001108 if (I->second.isOverdefined())
1109 TrackedGlobals.erase(I); // No need to keep tracking this!
1110}
1111
Chris Lattner49f74522004-01-12 04:29:41 +00001112// Handle load instructions. If the operand is a constant pointer to a constant
1113// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001114void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001115 // If this load is of a struct, just mark the result overdefined.
David Majnemerf3b99dd2016-01-07 19:30:13 +00001116 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001117 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001118
Chris Lattnerf5484032009-11-02 05:55:40 +00001119 LatticeVal PtrVal = getValueState(I.getOperand(0));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001120 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001121
Chris Lattner4f031622004-11-15 05:03:30 +00001122 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001123 if (IV.isOverdefined()) return;
1124
Chris Lattnerf5484032009-11-02 05:55:40 +00001125 if (!PtrVal.isConstant() || I.isVolatile())
1126 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001127
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001128 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001129
David Majnemerbae94572016-01-07 19:25:39 +00001130 // load null is undefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001131 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
David Majnemerbae94572016-01-07 19:25:39 +00001132 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001133
Chris Lattnerf5484032009-11-02 05:55:40 +00001134 // Transform load (constant global) into the value loaded.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001135 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001136 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001137 // If we are tracking this global, merge in the known value for it.
1138 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1139 TrackedGlobals.find(GV);
1140 if (It != TrackedGlobals.end()) {
1141 mergeInValue(IV, &I, It->second);
1142 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001143 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001144 }
Chris Lattner49f74522004-01-12 04:29:41 +00001145 }
1146
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001147 // Transform load from a constant into a constant if possible.
Eduard Burtescu14239212016-01-22 01:17:26 +00001148 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001149 if (isa<UndefValue>(C))
1150 return;
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001151 return markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001152 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001153
Chris Lattner49f74522004-01-12 04:29:41 +00001154 // Otherwise we cannot say for certain what value this load will produce.
1155 // Bail out.
1156 markOverdefined(IV, &I);
1157}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001158
Chris Lattnerb4394642004-12-10 08:02:06 +00001159void SCCPSolver::visitCallSite(CallSite CS) {
1160 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001161 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001162
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001163 // The common case is that we aren't tracking the callee, either because we
1164 // are not doing interprocedural analysis or the callee is indirect, or is
1165 // external. Handle these cases first.
Craig Topperf40110f2014-04-25 05:29:35 +00001166 if (!F || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001167CallOverdefined:
1168 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001169 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001170
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001171 // Otherwise, if we have a single return value case, and if the function is
1172 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001173 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Andrew Kaylor647025f2017-06-09 23:18:11 +00001174 canConstantFoldCallTo(CS, F)) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001175 SmallVector<Constant*, 8> Operands;
1176 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1177 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001178 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001179
Davide Italiano0f03ce02016-07-10 00:35:15 +00001180 if (State.isUnknown())
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001181 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001182 if (State.isOverdefined())
1183 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001184 assert(State.isConstant() && "Unknown state!");
1185 Operands.push_back(State.getConstant());
1186 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001187
David Majnemer2098b86f2014-11-07 08:54:19 +00001188 if (getValueState(I).isOverdefined())
1189 return;
1190
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001191 // If we can constant fold this, mark the result of the call as a
1192 // constant.
Andrew Kaylor647025f2017-06-09 23:18:11 +00001193 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001194 // call -> undef.
1195 if (isa<UndefValue>(C))
1196 return;
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001197 return markConstant(I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001198 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001199 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001200
1201 // Otherwise, we don't know anything about this call, mark it overdefined.
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001202 return markOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001203 }
1204
Chris Lattnercde8de52009-11-03 19:24:51 +00001205 // If this is a local function that doesn't have its address taken, mark its
1206 // entry block executable and merge in the actual arguments to the call into
1207 // the formal arguments of the function.
1208 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001209 MarkBlockExecutable(&F->front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001210
Chris Lattnercde8de52009-11-03 19:24:51 +00001211 // Propagate information from this call site into the callee.
1212 CallSite::arg_iterator CAI = CS.arg_begin();
1213 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1214 AI != E; ++AI, ++CAI) {
1215 // If this argument is byval, and if the function is not readonly, there
1216 // will be an implicit copy formed of the input aggregate.
1217 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001218 markOverdefined(&*AI);
Chris Lattnercde8de52009-11-03 19:24:51 +00001219 continue;
1220 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001221
Davide Italianoe3bdd612016-12-01 08:36:12 +00001222 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001223 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1224 LatticeVal CallArg = getStructValueState(*CAI, i);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001225 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
Chris Lattner762b56f2009-11-04 18:57:42 +00001226 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001227 } else {
Florian Hahnd0208b42017-10-30 10:07:42 +00001228 // Most other parts of the Solver still only use the simpler value
1229 // lattice, so we propagate changes for parameters to both lattices.
1230 getParamState(&*AI).mergeIn(getValueState(*CAI).toValueLattice(), DL);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001231 mergeInValue(&*AI, getValueState(*CAI));
Chris Lattner156b8c72009-11-03 23:40:48 +00001232 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001233 }
1234 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001235
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001236 // If this is a single/zero retval case, see if we're tracking the function.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001237 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001238 if (!MRVFunctionsTracked.count(F))
1239 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001240
Chris Lattner156b8c72009-11-03 23:40:48 +00001241 // If we are tracking this callee, propagate the result of the function
1242 // into this call site.
1243 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001244 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001245 TrackedMultipleRetVals[std::make_pair(F, i)]);
1246 } else {
1247 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1248 if (TFRVI == TrackedRetVals.end())
1249 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001250
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001251 // If so, propagate the return value of the callee into this call result.
1252 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001253 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001254}
Chris Lattner074be1f2004-11-15 04:44:20 +00001255
Chris Lattner074be1f2004-11-15 04:44:20 +00001256void SCCPSolver::Solve() {
1257 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001258 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001259 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001260 // Process the overdefined instruction's work list first, which drives other
1261 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001262 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001263 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001264
David Greene389fc3b2010-01-05 01:27:15 +00001265 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001266
Chris Lattner074be1f2004-11-15 04:44:20 +00001267 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001268 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001269 //
1270 // Anything on this worklist that is overdefined need not be visited
1271 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001272 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001273 //
Chandler Carruthcdf47882014-03-09 03:16:01 +00001274 for (User *U : I->users())
Davide Italianoe3bdd612016-12-01 08:36:12 +00001275 if (auto *UI = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +00001276 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001277 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001278
Chris Lattnera3c39d32009-11-02 02:33:50 +00001279 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001280 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001281 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001282
David Greene389fc3b2010-01-05 01:27:15 +00001283 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001284
Chris Lattnerf5484032009-11-02 05:55:40 +00001285 // "I" got into the work list because it made the transition from undef to
1286 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001287 //
1288 // Anything on this worklist that is overdefined need not be visited
1289 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001290 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001291 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001292 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001293 for (User *U : I->users())
Davide Italianoe3bdd612016-12-01 08:36:12 +00001294 if (auto *UI = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +00001295 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001296 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001297
Chris Lattnera3c39d32009-11-02 02:33:50 +00001298 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001299 while (!BBWorkList.empty()) {
1300 BasicBlock *BB = BBWorkList.back();
1301 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001302
David Greene389fc3b2010-01-05 01:27:15 +00001303 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001304
Chris Lattner074be1f2004-11-15 04:44:20 +00001305 // Notify all instructions in this basic block that they are newly
1306 // executable.
1307 visit(BB);
1308 }
1309 }
1310}
1311
Chris Lattner1847f6d2006-12-20 06:21:33 +00001312/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001313/// that branches on undef values cannot reach any of their successors.
1314/// However, this is not a safe assumption. After we solve dataflow, this
1315/// method should be use to handle this. If this returns true, the solver
1316/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001317///
1318/// This method handles this by finding an unresolved branch and marking it one
1319/// of the edges from the block as being feasible, even though the condition
1320/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1321/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001322/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001323/// constraints on the condition of the branch, as that would impact other users
1324/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001325///
1326/// This scan also checks for values that use undefs, whose results are actually
1327/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1328/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1329/// even if X isn't defined.
1330bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001331 for (BasicBlock &BB : F) {
1332 if (!BBExecutable.count(&BB))
Chris Lattneraf170962006-10-22 05:59:17 +00001333 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001334
Benjamin Kramer135f7352016-06-26 12:28:59 +00001335 for (Instruction &I : BB) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001336 // Look for instructions which produce undef values.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001337 if (I.getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001338
Davide Italianoe3bdd612016-12-01 08:36:12 +00001339 if (auto *STy = dyn_cast<StructType>(I.getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001340 // Only a few things that can be structs matter for undef.
1341
1342 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001343 if (CallSite CS = CallSite(&I))
Eli Friedman1815b682011-09-20 23:28:51 +00001344 if (Function *F = CS.getCalledFunction())
1345 if (MRVFunctionsTracked.count(F))
1346 continue;
1347
1348 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001349 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001350 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1351 continue;
1352
1353 // Send the results of everything else to overdefined. We could be
1354 // more precise than this but it isn't worth bothering.
1355 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001356 LatticeVal &LV = getStructValueState(&I, i);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001357 if (LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001358 markOverdefined(LV, &I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001359 }
1360 continue;
1361 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001362
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001363 LatticeVal &LV = getValueState(&I);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001364 if (!LV.isUnknown()) continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001365
Eli Friedmand7749be2011-08-17 18:10:43 +00001366 // extractvalue is safe; check here because the argument is a struct.
1367 if (isa<ExtractValueInst>(I))
1368 continue;
1369
1370 // Compute the operand LatticeVals, for convenience below.
1371 // Anything taking a struct is conservatively assumed to require
1372 // overdefined markings.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001373 if (I.getOperand(0)->getType()->isStructTy()) {
1374 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001375 return true;
1376 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001377 LatticeVal Op0LV = getValueState(I.getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001378 LatticeVal Op1LV;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001379 if (I.getNumOperands() == 2) {
1380 if (I.getOperand(1)->getType()->isStructTy()) {
1381 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001382 return true;
1383 }
1384
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001385 Op1LV = getValueState(I.getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001386 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001387 // If this is an instructions whose result is defined even if the input is
1388 // not fully defined, propagate the information.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001389 Type *ITy = I.getType();
1390 switch (I.getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001391 case Instruction::Add:
1392 case Instruction::Sub:
1393 case Instruction::Trunc:
1394 case Instruction::FPTrunc:
1395 case Instruction::BitCast:
1396 break; // Any undef -> undef
1397 case Instruction::FSub:
1398 case Instruction::FAdd:
1399 case Instruction::FMul:
1400 case Instruction::FDiv:
1401 case Instruction::FRem:
1402 // Floating-point binary operation: be conservative.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001403 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001404 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001405 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001406 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001407 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001408 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001409 case Instruction::SExt:
1410 case Instruction::FPToUI:
1411 case Instruction::FPToSI:
1412 case Instruction::FPExt:
1413 case Instruction::PtrToInt:
1414 case Instruction::IntToPtr:
1415 case Instruction::SIToFP:
1416 case Instruction::UIToFP:
1417 // undef -> 0; some outputs are impossible
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001418 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001419 return true;
1420 case Instruction::Mul:
1421 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001422 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001423 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001424 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001425 // undef * X -> 0. X could be zero.
1426 // undef & X -> 0. X could be zero.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001427 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001428 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001429 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001430 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001431 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001432 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001433 // undef | X -> -1. X could be -1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001434 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001435 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001436 case Instruction::Xor:
1437 // undef ^ undef -> 0; strictly speaking, this is not strictly
1438 // necessary, but we try to be nice to people who expect this
1439 // behavior in simple cases
Davide Italiano0f03ce02016-07-10 00:35:15 +00001440 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001441 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001442 return true;
1443 }
1444 // undef ^ X -> undef
1445 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001446 case Instruction::SDiv:
1447 case Instruction::UDiv:
1448 case Instruction::SRem:
1449 case Instruction::URem:
1450 // X / undef -> undef. No change.
1451 // X % undef -> undef. No change.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001452 if (Op1LV.isUnknown()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001453
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001454 // X / 0 -> undef. No change.
1455 // X % 0 -> undef. No change.
1456 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1457 break;
1458
Chris Lattner1847f6d2006-12-20 06:21:33 +00001459 // undef / X -> 0. X could be maxint.
1460 // undef % X -> 0. X could be 1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001461 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001462 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001463 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001464 // X >>a undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001465 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001466
David Majnemer96f0d382016-05-12 03:07:40 +00001467 // Shifting by the bitwidth or more is undefined.
1468 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001469 if (auto *ShiftAmt = Op1LV.getConstantInt())
1470 if (ShiftAmt->getLimitedValue() >=
1471 ShiftAmt->getType()->getScalarSizeInBits())
1472 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001473 }
1474
Davide Italiano54c683f2016-12-08 22:28:53 +00001475 // undef >>a X -> 0
1476 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001477 return true;
1478 case Instruction::LShr:
1479 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001480 // X << undef -> undef.
1481 // X >> undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001482 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001483
David Majnemer96f0d382016-05-12 03:07:40 +00001484 // Shifting by the bitwidth or more is undefined.
1485 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001486 if (auto *ShiftAmt = Op1LV.getConstantInt())
1487 if (ShiftAmt->getLimitedValue() >=
1488 ShiftAmt->getType()->getScalarSizeInBits())
1489 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001490 }
1491
Eli Friedman0793eb42011-08-16 22:06:31 +00001492 // undef << X -> 0
1493 // undef >> X -> 0
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001494 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001495 return true;
1496 case Instruction::Select:
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001497 Op1LV = getValueState(I.getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001498 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001499 if (Op0LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001500 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001501 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001502 } else if (Op1LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001503 // c ? undef : undef -> undef. No change.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001504 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001505 if (Op1LV.isUnknown())
Chris Lattner1847f6d2006-12-20 06:21:33 +00001506 break;
1507 // Otherwise, c ? undef : x -> x.
1508 } else {
1509 // Leave Op1LV as Operand(1)'s LatticeValue.
1510 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001511
Chris Lattner1847f6d2006-12-20 06:21:33 +00001512 if (Op1LV.isConstant())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001513 markForcedConstant(&I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001514 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001515 markOverdefined(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001516 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001517 case Instruction::Load:
1518 // A load here means one of two things: a load of undef from a global,
1519 // a load from an unknown pointer. Either way, having it return undef
1520 // is okay.
1521 break;
1522 case Instruction::ICmp:
1523 // X == undef -> undef. Other comparisons get more complicated.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001524 if (cast<ICmpInst>(&I)->isEquality())
Eli Friedman0793eb42011-08-16 22:06:31 +00001525 break;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001526 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001527 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001528 case Instruction::Call:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001529 case Instruction::Invoke:
Eli Friedman1815b682011-09-20 23:28:51 +00001530 // There are two reasons a call can have an undef result
1531 // 1. It could be tracked.
1532 // 2. It could be constant-foldable.
1533 // Because of the way we solve return values, tracked calls must
1534 // never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001535 if (Function *F = CallSite(&I).getCalledFunction())
Eli Friedman1815b682011-09-20 23:28:51 +00001536 if (TrackedRetVals.count(F))
1537 break;
1538
1539 // If the call is constant-foldable, we mark it overdefined because
1540 // we do not know what return values are valid.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001541 markOverdefined(&I);
Eli Friedman1815b682011-09-20 23:28:51 +00001542 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001543 default:
1544 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001545 // overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001546 markOverdefined(&I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001547 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001548 }
1549 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001550
Chris Lattneradca6082010-04-05 22:14:48 +00001551 // Check to see if we have a branch or switch on an undefined value. If so
1552 // we force the branch to go one way or the other to make the successor
1553 // values live. It doesn't really matter which way we force it.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001554 TerminatorInst *TI = BB.getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +00001555 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneraf170962006-10-22 05:59:17 +00001556 if (!BI->isConditional()) continue;
Davide Italiano0f03ce02016-07-10 00:35:15 +00001557 if (!getValueState(BI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001558 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001559
Chris Lattneradca6082010-04-05 22:14:48 +00001560 // If the input to SCCP is actually branch on undef, fix the undef to
1561 // false.
1562 if (isa<UndefValue>(BI->getCondition())) {
1563 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Benjamin Kramer135f7352016-06-26 12:28:59 +00001564 markEdgeExecutable(&BB, TI->getSuccessor(1));
Chris Lattneradca6082010-04-05 22:14:48 +00001565 return true;
1566 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001567
Chris Lattneradca6082010-04-05 22:14:48 +00001568 // Otherwise, it is a branch on a symbolic value which is currently
1569 // considered to be undef. Handle this by forcing the input value to the
1570 // branch to false.
1571 markForcedConstant(BI->getCondition(),
1572 ConstantInt::getFalse(TI->getContext()));
1573 return true;
1574 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001575
Xin Tong34888c02017-04-10 00:33:25 +00001576 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1577 // Indirect branch with no successor ?. Its ok to assume it branches
1578 // to no target.
1579 if (IBR->getNumSuccessors() < 1)
1580 continue;
1581
1582 if (!getValueState(IBR->getAddress()).isUnknown())
1583 continue;
1584
1585 // If the input to SCCP is actually branch on undef, fix the undef to
1586 // the first successor of the indirect branch.
1587 if (isa<UndefValue>(IBR->getAddress())) {
1588 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1589 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1590 return true;
1591 }
1592
1593 // Otherwise, it is a branch on a symbolic value which is currently
1594 // considered to be undef. Handle this by forcing the input value to the
1595 // branch to the first successor.
1596 markForcedConstant(IBR->getAddress(),
1597 BlockAddress::get(IBR->getSuccessor(0)));
1598 return true;
1599 }
1600
Davide Italianoe3bdd612016-12-01 08:36:12 +00001601 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Davide Italiano094dadd2016-07-15 18:33:16 +00001602 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001603 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001604
Chris Lattneradca6082010-04-05 22:14:48 +00001605 // If the input to SCCP is actually switch on undef, fix the undef to
1606 // the first constant.
1607 if (isa<UndefValue>(SI->getCondition())) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00001608 SI->setCondition(SI->case_begin()->getCaseValue());
1609 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001610 return true;
1611 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001612
Chandler Carruth927d8e62017-04-12 07:27:28 +00001613 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001614 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001615 }
Chris Lattneraf170962006-10-22 05:59:17 +00001616 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001617
Chris Lattneraf170962006-10-22 05:59:17 +00001618 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001619}
1620
Florian Hahnd0208b42017-10-30 10:07:42 +00001621static bool tryToReplaceWithConstantRange(SCCPSolver &Solver, Value *V) {
1622 bool Changed = false;
1623
1624 // Currently we only use range information for integer values.
1625 if (!V->getType()->isIntegerTy())
1626 return false;
1627
1628 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
1629 if (!IV.isConstantRange())
1630 return false;
1631
1632 for (auto UI = V->uses().begin(), E = V->uses().end(); UI != E;) {
1633 const Use &U = *UI++;
1634 auto *Icmp = dyn_cast<ICmpInst>(U.getUser());
1635 if (!Icmp || !Solver.isBlockExecutable(Icmp->getParent()))
1636 continue;
1637
Davide Italianob480b5c2017-11-22 03:04:55 +00001638 auto getIcmpLatticeValue = [&](Value *Op) {
1639 if (auto *C = dyn_cast<Constant>(Op))
1640 return ValueLatticeElement::get(C);
1641 return Solver.getLatticeValueFor(Op);
1642 };
1643
1644 ValueLatticeElement A = getIcmpLatticeValue(Icmp->getOperand(0));
1645 ValueLatticeElement B = getIcmpLatticeValue(Icmp->getOperand(1));
1646
Florian Hahn0b7c6422018-03-05 17:33:50 +00001647 Constant *C = A.getCompare(Icmp->getPredicate(), Icmp->getType(), B);
Florian Hahnd0208b42017-10-30 10:07:42 +00001648 if (C) {
1649 Icmp->replaceAllUsesWith(C);
1650 DEBUG(dbgs() << "Replacing " << *Icmp << " with " << *C
1651 << ", because of range information " << A << " " << B
1652 << "\n");
1653 Icmp->eraseFromParent();
1654 Changed = true;
1655 }
1656 }
1657 return Changed;
1658}
1659
Davide Italiano6f735882016-07-14 20:25:54 +00001660static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
Davide Italiano296e9782016-07-13 23:20:04 +00001661 Constant *Const = nullptr;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001662 if (V->getType()->isStructTy()) {
1663 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
Eugene Zelenko99241d72017-10-20 21:47:29 +00001664 if (llvm::any_of(IVs,
1665 [](const LatticeVal &LV) { return LV.isOverdefined(); }))
Davide Italiano296e9782016-07-13 23:20:04 +00001666 return false;
1667 std::vector<Constant *> ConstVals;
Davide Italianoe3bdd612016-12-01 08:36:12 +00001668 auto *ST = dyn_cast<StructType>(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001669 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1670 LatticeVal V = IVs[i];
1671 ConstVals.push_back(V.isConstant()
1672 ? V.getConstant()
1673 : UndefValue::get(ST->getElementType(i)));
1674 }
1675 Const = ConstantStruct::get(ST, ConstVals);
1676 } else {
Florian Hahnd0208b42017-10-30 10:07:42 +00001677 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
Davide Italiano296e9782016-07-13 23:20:04 +00001678 if (IV.isOverdefined())
1679 return false;
Florian Hahnd0208b42017-10-30 10:07:42 +00001680
1681 if (IV.isConstantRange()) {
1682 if (IV.getConstantRange().isSingleElement())
1683 Const =
1684 ConstantInt::get(V->getType(), IV.asConstantInteger().getValue());
1685 else
1686 return false;
1687 } else
1688 Const =
1689 IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001690 }
1691 assert(Const && "Constant is nullptr here!");
Reid Kleckner3762a082018-03-01 01:19:18 +00001692
1693 // Replacing `musttail` instructions with constant breaks `musttail` invariant
1694 // unless the call itself can be removed
1695 CallInst *CI = dyn_cast<CallInst>(V);
1696 if (CI && CI->isMustTailCall() && !CI->isSafeToRemove()) {
1697 CallSite CS(CI);
1698 Function *F = CS.getCalledFunction();
1699
1700 // Don't zap returns of the callee
1701 if (F)
1702 Solver.AddMustTailCallee(F);
1703
1704 DEBUG(dbgs() << " Can\'t treat the result of musttail call : " << *CI
1705 << " as a constant\n");
1706 return false;
1707 }
1708
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001709 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
Davide Italiano296e9782016-07-13 23:20:04 +00001710
1711 // Replaces all of the uses of a variable with uses of the constant.
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001712 V->replaceAllUsesWith(Const);
Davide Italiano6ed6d772016-07-14 01:27:29 +00001713 return true;
1714}
1715
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001716// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner074be1f2004-11-15 04:44:20 +00001717// and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001718static bool runSCCP(Function &F, const DataLayout &DL,
1719 const TargetLibraryInfo *TLI) {
David Greene389fc3b2010-01-05 01:27:15 +00001720 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001721 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001722
1723 // Mark the first block of the function as being executable.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001724 Solver.MarkBlockExecutable(&F.front());
Chris Lattner074be1f2004-11-15 04:44:20 +00001725
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001726 // Mark all arguments to the function as being overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001727 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001728 Solver.markOverdefined(&AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001729
Chris Lattner074be1f2004-11-15 04:44:20 +00001730 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001731 bool ResolvedUndefs = true;
1732 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001733 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001734 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001735 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001736 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001737
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001738 bool MadeChanges = false;
1739
1740 // If we decided that there are basic blocks that are dead in this function,
1741 // delete their contents now. Note that we cannot actually delete the blocks,
1742 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001743
Benjamin Kramer135f7352016-06-26 12:28:59 +00001744 for (BasicBlock &BB : F) {
1745 if (!Solver.isBlockExecutable(&BB)) {
1746 DEBUG(dbgs() << " BasicBlock Dead:" << BB);
David Majnemer88542a02016-01-24 06:26:47 +00001747
1748 ++NumDeadBlocks;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001749 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer88542a02016-01-24 06:26:47 +00001750
Chris Lattnere405ed92009-11-02 02:47:51 +00001751 MadeChanges = true;
1752 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001753 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001754
Chris Lattnere405ed92009-11-02 02:47:51 +00001755 // Iterate over all of the instructions in a function, replacing them with
1756 // constants if we have found them to be of constant values.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001757 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001758 Instruction *Inst = &*BI++;
Chris Lattnere405ed92009-11-02 02:47:51 +00001759 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1760 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001761
Sanjoy Dasff855b62016-08-24 18:10:21 +00001762 if (tryToReplaceWithConstant(Solver, Inst)) {
1763 if (isInstructionTriviallyDead(Inst))
1764 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001765 // Hey, we just changed something!
1766 MadeChanges = true;
1767 ++NumInstRemoved;
Davide Italiano00802692016-07-12 19:54:19 +00001768 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001769 }
1770 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001771
1772 return MadeChanges;
1773}
Chris Lattnerb4394642004-12-10 08:02:06 +00001774
Sean Silva36e0d012016-08-09 00:28:15 +00001775PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001776 const DataLayout &DL = F.getParent()->getDataLayout();
1777 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1778 if (!runSCCP(F, DL, &TLI))
1779 return PreservedAnalyses::all();
Davide Italiano484b5ab2016-05-29 00:31:15 +00001780
1781 auto PA = PreservedAnalyses();
1782 PA.preserve<GlobalsAA>();
1783 return PA;
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001784}
1785
1786namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +00001787
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001788//===--------------------------------------------------------------------===//
1789//
1790/// SCCP Class - This class uses the SCCPSolver to implement a per-function
1791/// Sparse Conditional Constant Propagator.
1792///
Davide Italiano46f249b2016-05-19 15:58:02 +00001793class SCCPLegacyPass : public FunctionPass {
1794public:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001795 // Pass identification, replacement for typeid
1796 static char ID;
1797
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001798 SCCPLegacyPass() : FunctionPass(ID) {
1799 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1800 }
1801
Eugene Zelenko99241d72017-10-20 21:47:29 +00001802 void getAnalysisUsage(AnalysisUsage &AU) const override {
1803 AU.addRequired<TargetLibraryInfoWrapperPass>();
1804 AU.addPreserved<GlobalsAAWrapperPass>();
1805 }
1806
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001807 // runOnFunction - Run the Sparse Conditional Constant Propagation
1808 // algorithm, and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001809 bool runOnFunction(Function &F) override {
1810 if (skipFunction(F))
1811 return false;
1812 const DataLayout &DL = F.getParent()->getDataLayout();
1813 const TargetLibraryInfo *TLI =
1814 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1815 return runSCCP(F, DL, TLI);
1816 }
1817};
Eugene Zelenko99241d72017-10-20 21:47:29 +00001818
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001819} // end anonymous namespace
1820
1821char SCCPLegacyPass::ID = 0;
Eugene Zelenko99241d72017-10-20 21:47:29 +00001822
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001823INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1824 "Sparse Conditional Constant Propagation", false, false)
1825INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1826INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1827 "Sparse Conditional Constant Propagation", false, false)
1828
1829// createSCCPPass - This is the public interface to this file.
1830FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1831
Davide Italiano15ff2d62016-07-20 20:17:13 +00001832static void findReturnsToZap(Function &F,
Matthew Simpson22849372017-10-13 17:53:44 +00001833 SmallVector<ReturnInst *, 8> &ReturnsToZap,
1834 SCCPSolver &Solver) {
Davide Italiano15ff2d62016-07-20 20:17:13 +00001835 // We can only do this if we know that nothing else can call the function.
Matthew Simpson22849372017-10-13 17:53:44 +00001836 if (!Solver.isArgumentTrackedFunction(&F))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001837 return;
1838
Reid Kleckner3762a082018-03-01 01:19:18 +00001839 // There is a non-removable musttail call site of this function. Zapping
1840 // returns is not allowed.
1841 if (Solver.isMustTailCallee(&F)) {
1842 DEBUG(dbgs() << "Can't zap returns of the function : " << F.getName()
1843 << " due to present musttail call of it\n");
1844 return;
1845 }
1846
1847 for (BasicBlock &BB : F) {
1848 if (CallInst *CI = BB.getTerminatingMustTailCall()) {
1849 DEBUG(dbgs() << "Can't zap return of the block due to present "
1850 << "musttail call : " << *CI << "\n");
Benjamin Kramerd1cf7ff2018-03-01 11:31:44 +00001851 (void)CI;
Reid Kleckner3762a082018-03-01 01:19:18 +00001852 return;
1853 }
1854
Davide Italianoe3bdd612016-12-01 08:36:12 +00001855 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001856 if (!isa<UndefValue>(RI->getOperand(0)))
1857 ReturnsToZap.push_back(RI);
Reid Kleckner3762a082018-03-01 01:19:18 +00001858 }
Davide Italiano15ff2d62016-07-20 20:17:13 +00001859}
1860
Davide Italianof54f2f02016-05-05 21:05:36 +00001861static bool runIPSCCP(Module &M, const DataLayout &DL,
1862 const TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001863 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001864
1865 // Loop over all functions, marking arguments to those with their addresses
1866 // taken or that are external as overdefined.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001867 for (Function &F : M) {
1868 if (F.isDeclaration())
Chris Lattner47837c52009-11-02 06:34:04 +00001869 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001870
Matthew Simpson22849372017-10-13 17:53:44 +00001871 // Determine if we can track the function's return values. If so, add the
1872 // function to the solver's set of return-tracked functions.
1873 if (canTrackReturnsInterprocedurally(&F))
Davide Italianoe7c56c52016-05-14 20:59:09 +00001874 Solver.AddTrackedFunction(&F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001875
Matthew Simpson22849372017-10-13 17:53:44 +00001876 // Determine if we can track the function's arguments. If so, add the
1877 // function to the solver's set of argument-tracked functions.
1878 if (canTrackArgumentsInterprocedurally(&F)) {
1879 Solver.AddArgumentTrackedFunction(&F);
1880 continue;
Chris Lattnercde8de52009-11-03 19:24:51 +00001881 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001882
1883 // Assume the function is called.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001884 Solver.MarkBlockExecutable(&F.front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001885
Chris Lattnerfb141812009-11-03 03:42:51 +00001886 // Assume nothing about the incoming arguments.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001887 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001888 Solver.markOverdefined(&AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001889 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001890
Matthew Simpson22849372017-10-13 17:53:44 +00001891 // Determine if we can track any of the module's global variables. If so, add
1892 // the global variables we can track to the solver's set of tracked global
1893 // variables.
1894 for (GlobalVariable &G : M.globals()) {
1895 G.removeDeadConstantUsers();
1896 if (canTrackGlobalVariableInterprocedurally(&G))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001897 Solver.TrackValueOfGlobalVariable(&G);
Matthew Simpson22849372017-10-13 17:53:44 +00001898 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001899
Chris Lattnerb4394642004-12-10 08:02:06 +00001900 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001901 bool ResolvedUndefs = true;
1902 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001903 Solver.Solve();
1904
David Greene389fc3b2010-01-05 01:27:15 +00001905 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001906 ResolvedUndefs = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001907 for (Function &F : M)
1908 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001909 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001910
1911 bool MadeChanges = false;
1912
1913 // Iterate over all of the instructions in the module, replacing them with
1914 // constants if we have found them to be of constant values.
Chris Lattner65938fc2008-08-23 23:36:38 +00001915 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001916
Benjamin Kramer135f7352016-06-26 12:28:59 +00001917 for (Function &F : M) {
1918 if (F.isDeclaration())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001919 continue;
1920
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00001921 if (Solver.isBlockExecutable(&F.front()))
Benjamin Kramer135f7352016-06-26 12:28:59 +00001922 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
Florian Hahnd0208b42017-10-30 10:07:42 +00001923 ++AI) {
Davide Italiano5df80802017-11-21 00:21:52 +00001924 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) {
Davide Italiano6ed6d772016-07-14 01:27:29 +00001925 ++IPNumArgsElimed;
Davide Italiano5df80802017-11-21 00:21:52 +00001926 continue;
1927 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001928
Florian Hahnd0208b42017-10-30 10:07:42 +00001929 if (!AI->use_empty() && tryToReplaceWithConstantRange(Solver, &*AI))
1930 ++IPNumRangeInfoUsed;
1931 }
1932
Benjamin Kramer135f7352016-06-26 12:28:59 +00001933 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001934 if (!Solver.isBlockExecutable(&*BB)) {
David Majnemer88542a02016-01-24 06:26:47 +00001935 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001936
David Majnemer88542a02016-01-24 06:26:47 +00001937 ++NumDeadBlocks;
David Majnemere14e7bc2016-06-25 08:19:55 +00001938 NumInstRemoved +=
1939 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
David Majnemer88542a02016-01-24 06:26:47 +00001940
1941 MadeChanges = true;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001942
Benjamin Kramer135f7352016-06-26 12:28:59 +00001943 if (&*BB != &F.front())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001944 BlocksToErase.push_back(&*BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001945 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001946 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001947
Chris Lattnere405ed92009-11-02 02:47:51 +00001948 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001949 Instruction *Inst = &*BI++;
Davide Italiano7dac0272016-07-14 02:51:41 +00001950 if (Inst->getType()->isVoidTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001951 continue;
Sanjoy Dasff855b62016-08-24 18:10:21 +00001952 if (tryToReplaceWithConstant(Solver, Inst)) {
Chris Bienemanabdea262018-01-09 21:58:46 +00001953 if (Inst->isSafeToRemove())
Sanjoy Dasff855b62016-08-24 18:10:21 +00001954 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001955 // Hey, we just changed something!
1956 MadeChanges = true;
1957 ++IPNumInstRemoved;
1958 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001959 }
1960 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001961
1962 // Now that all instructions in the function are constant folded, erase dead
1963 // blocks, because we can now use ConstantFoldTerminator to get rid of
1964 // in-edges.
1965 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1966 // If there are any PHI nodes in this successor, drop entries for BB now.
1967 BasicBlock *DeadBB = BlocksToErase[i];
Chandler Carruthcdf47882014-03-09 03:16:01 +00001968 for (Value::user_iterator UI = DeadBB->user_begin(),
1969 UE = DeadBB->user_end();
1970 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001971 // Grab the user and then increment the iterator early, as the user
1972 // will be deleted. Step past all adjacent uses from the same user.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001973 auto *I = dyn_cast<Instruction>(*UI);
Dan Gohman1f522d92009-11-23 16:13:39 +00001974 do { ++UI; } while (UI != UE && *UI == I);
1975
Dan Gohmand15302a2009-11-20 20:19:14 +00001976 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001977 if (!I) continue;
1978
Davide Italianodf670a12016-12-06 02:26:50 +00001979 bool Folded = ConstantFoldTerminator(I->getParent());
Davide Italianoe15bffe2018-01-07 22:09:44 +00001980 assert(Folded &&
1981 "Expect TermInst on constantint or blockaddress to be folded");
1982 (void) Folded;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001983 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001984
Chris Lattnerbae4b642004-12-10 22:29:08 +00001985 // Finally, delete the basic block.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001986 F.getBasicBlockList().erase(DeadBB);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001987 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001988 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001989 }
Chris Lattner99e12952004-12-11 02:53:57 +00001990
1991 // If we inferred constant or undef return values for a function, we replaced
1992 // all call uses with the inferred value. This means we don't need to bother
1993 // actually returning anything from the function. Replace all return
1994 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001995 //
1996 // Do this in two stages: first identify the functions we should process, then
1997 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001998 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001999 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00002000 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00002001 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00002002
Devang Patela7a20752008-03-11 05:46:42 +00002003 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Benjamin Kramer135f7352016-06-26 12:28:59 +00002004 for (const auto &I : RV) {
2005 Function *F = I.first;
2006 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
Chris Lattnerfb141812009-11-03 03:42:51 +00002007 continue;
Matthew Simpson22849372017-10-13 17:53:44 +00002008 findReturnsToZap(*F, ReturnsToZap, Solver);
Davide Italiano15ff2d62016-07-20 20:17:13 +00002009 }
Jakub Staszak632a3552012-01-18 21:16:33 +00002010
Davide Italiano15ff2d62016-07-20 20:17:13 +00002011 for (const auto &F : Solver.getMRVFunctionsTracked()) {
2012 assert(F->getReturnType()->isStructTy() &&
2013 "The return type should be a struct");
2014 StructType *STy = cast<StructType>(F->getReturnType());
2015 if (Solver.isStructLatticeConstant(F, STy))
Matthew Simpson22849372017-10-13 17:53:44 +00002016 findReturnsToZap(*F, ReturnsToZap, Solver);
Chris Lattnerd887f1d2010-02-27 00:07:42 +00002017 }
2018
2019 // Zap all returns which we've identified as zap to change.
2020 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
2021 Function *F = ReturnsToZap[i]->getParent()->getParent();
2022 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00002023 }
Jakub Staszak632a3552012-01-18 21:16:33 +00002024
Chad Rosierbb2a6da2012-03-28 00:35:33 +00002025 // If we inferred constant or undef values for globals variables, we can
2026 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00002027 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2028 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00002029 E = TG.end(); I != E; ++I) {
2030 GlobalVariable *GV = I->first;
2031 assert(!I->second.isOverdefined() &&
2032 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00002033 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00002034 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002035 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00002036 SI->eraseFromParent();
2037 }
2038 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00002039 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00002040 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002041
Chris Lattnerb4394642004-12-10 08:02:06 +00002042 return MadeChanges;
2043}
Davide Italianof54f2f02016-05-05 21:05:36 +00002044
Sean Silvafd03ac62016-08-09 00:28:38 +00002045PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
Davide Italianof54f2f02016-05-05 21:05:36 +00002046 const DataLayout &DL = M.getDataLayout();
2047 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
2048 if (!runIPSCCP(M, DL, &TLI))
2049 return PreservedAnalyses::all();
2050 return PreservedAnalyses::none();
2051}
2052
2053namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +00002054
Davide Italianof54f2f02016-05-05 21:05:36 +00002055//===--------------------------------------------------------------------===//
2056//
2057/// IPSCCP Class - This class implements interprocedural Sparse Conditional
2058/// Constant Propagation.
2059///
Davide Italiano46f249b2016-05-19 15:58:02 +00002060class IPSCCPLegacyPass : public ModulePass {
2061public:
Davide Italianof54f2f02016-05-05 21:05:36 +00002062 static char ID;
2063
2064 IPSCCPLegacyPass() : ModulePass(ID) {
2065 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
2066 }
2067
2068 bool runOnModule(Module &M) override {
2069 if (skipModule(M))
2070 return false;
2071 const DataLayout &DL = M.getDataLayout();
2072 const TargetLibraryInfo *TLI =
2073 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2074 return runIPSCCP(M, DL, TLI);
2075 }
2076
2077 void getAnalysisUsage(AnalysisUsage &AU) const override {
2078 AU.addRequired<TargetLibraryInfoWrapperPass>();
2079 }
2080};
Eugene Zelenko99241d72017-10-20 21:47:29 +00002081
Davide Italianof54f2f02016-05-05 21:05:36 +00002082} // end anonymous namespace
2083
2084char IPSCCPLegacyPass::ID = 0;
Eugene Zelenko99241d72017-10-20 21:47:29 +00002085
Davide Italianof54f2f02016-05-05 21:05:36 +00002086INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
2087 "Interprocedural Sparse Conditional Constant Propagation",
2088 false, false)
2089INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2090INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
2091 "Interprocedural Sparse Conditional Constant Propagation",
2092 false, false)
2093
2094// createIPSCCPPass - This is the public interface to this file.
2095ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }