blob: 9dc550ceaeca777b4d66f94f2d6c7f9e31bf2181 [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
Chris Lattner2c427232009-11-03 20:52:57 +0000226 /// TrackingIncomingArguments - This is the set of functions for whose
227 /// arguments we make optimistic assumptions about and try to prove as
228 /// constants.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000229 SmallPtrSet<Function *, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000230
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000231 /// The reason for two worklists is that overdefined is the lowest state
232 /// on the lattice, and moving things to overdefined as fast as possible
233 /// makes SCCP converge much faster.
234 ///
235 /// By having a separate worklist, we accomplish this because everything
236 /// possibly overdefined will become overdefined at the soonest possible
237 /// point.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000238 SmallVector<Value *, 64> OverdefinedInstWorkList;
239 SmallVector<Value *, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000240
Eugene Zelenko99241d72017-10-20 21:47:29 +0000241 // The BasicBlock work list
242 SmallVector<BasicBlock *, 64> BBWorkList;
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000243
244 /// KnownFeasibleEdges - Entries in this set are edges which have already had
245 /// PHI nodes retriggered.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000246 using Edge = std::pair<BasicBlock *, BasicBlock *>;
Chris Lattner65938fc2008-08-23 23:36:38 +0000247 DenseSet<Edge> KnownFeasibleEdges;
Eugene Zelenko99241d72017-10-20 21:47:29 +0000248
Chris Lattner347389d2001-06-27 23:38:11 +0000249public:
Mehdi Amini46a43552015-03-04 18:43:29 +0000250 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
251 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000252
Chris Lattner074be1f2004-11-15 04:44:20 +0000253 /// MarkBlockExecutable - This method can be used by clients to mark all of
254 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000255 ///
256 /// This returns true if the block was not considered live before.
257 bool MarkBlockExecutable(BasicBlock *BB) {
David Blaikie70573dc2014-11-19 07:49:26 +0000258 if (!BBExecutable.insert(BB).second)
259 return false;
Nick Lewycky5cd95382013-06-26 00:30:18 +0000260 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000261 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000262 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000263 }
264
Chris Lattner91dbae62004-12-11 05:15:59 +0000265 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000266 /// inform the SCCPSolver that it should track loads and stores to the
267 /// specified global variable if it can. This is only legal to call if
268 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000269 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000270 // We only track the contents of scalar globals.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000271 if (GV->getValueType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000272 LatticeVal &IV = TrackedGlobals[GV];
273 if (!isa<UndefValue>(GV->getInitializer()))
274 IV.markConstant(GV->getInitializer());
275 }
276 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000277
278 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
279 /// and out of the specified function (which cannot have its address taken),
280 /// this method must be called.
281 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000282 // Add an entry, F -> undef.
Davide Italianoe3bdd612016-12-01 08:36:12 +0000283 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000284 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000285 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000286 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
287 LatticeVal()));
288 } else
289 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000290 }
291
Chris Lattnercde8de52009-11-03 19:24:51 +0000292 void AddArgumentTrackedFunction(Function *F) {
293 TrackingIncomingArguments.insert(F);
294 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000295
Matthew Simpson22849372017-10-13 17:53:44 +0000296 /// Returns true if the given function is in the solver's set of
297 /// argument-tracked functions.
298 bool isArgumentTrackedFunction(Function *F) {
299 return TrackingIncomingArguments.count(F);
300 }
301
Chris Lattner074be1f2004-11-15 04:44:20 +0000302 /// Solve - Solve for constants and executable blocks.
Chris Lattner074be1f2004-11-15 04:44:20 +0000303 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000304
Chris Lattner1847f6d2006-12-20 06:21:33 +0000305 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000306 /// that branches on undef values cannot reach any of their successors.
307 /// However, this is not a safe assumption. After we solve dataflow, this
308 /// method should be use to handle this. If this returns true, the solver
309 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000310 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000311
Chris Lattneradd44f32008-08-23 23:39:31 +0000312 bool isBlockExecutable(BasicBlock *BB) const {
313 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000314 }
315
Davide Italiano00802692016-07-12 19:54:19 +0000316 std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
317 std::vector<LatticeVal> StructValues;
Davide Italianoe3bdd612016-12-01 08:36:12 +0000318 auto *STy = dyn_cast<StructType>(V->getType());
Davide Italiano00802692016-07-12 19:54:19 +0000319 assert(STy && "getStructLatticeValueFor() can be called only on structs");
320 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
321 auto I = StructValueState.find(std::make_pair(V, i));
322 assert(I != StructValueState.end() && "Value not in valuemap!");
323 StructValues.push_back(I->second);
324 }
325 return StructValues;
326 }
327
Florian Hahnd0208b42017-10-30 10:07:42 +0000328 ValueLatticeElement getLatticeValueFor(Value *V) {
329 assert(!V->getType()->isStructTy() &&
330 "Should use getStructLatticeValueFor");
331 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
332 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
333 ValueLatticeElement &LV = PI.first->second;
334 if (PI.second) {
335 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
336 assert(I != ValueState.end() &&
337 "V not found in ValueState nor Paramstate map!");
338 LV = I->second.toValueLattice();
339 }
340
341 return LV;
Chris Lattner074be1f2004-11-15 04:44:20 +0000342 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000343
Devang Patela7a20752008-03-11 05:46:42 +0000344 /// getTrackedRetVals - Get the inferred return value map.
Devang Patela7a20752008-03-11 05:46:42 +0000345 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
346 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000347 }
348
Chris Lattner91dbae62004-12-11 05:15:59 +0000349 /// getTrackedGlobals - Get and return the set of inferred initializers for
350 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000351 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000352 return TrackedGlobals;
353 }
354
Davide Italiano15ff2d62016-07-20 20:17:13 +0000355 /// getMRVFunctionsTracked - Get the set of functions which return multiple
356 /// values tracked by the pass.
357 const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
358 return MRVFunctionsTracked;
359 }
360
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000361 /// markOverdefined - Mark the specified value overdefined. This
Chris Lattner156b8c72009-11-03 23:40:48 +0000362 /// works with both scalars and structs.
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000363 void markOverdefined(Value *V) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000364 if (auto *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000365 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
366 markOverdefined(getStructValueState(V, i), V);
367 else
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000368 markOverdefined(ValueState[V], V);
Chris Lattner156b8c72009-11-03 23:40:48 +0000369 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000370
Davide Italiano15ff2d62016-07-20 20:17:13 +0000371 // isStructLatticeConstant - Return true if all the lattice values
372 // corresponding to elements of the structure are not overdefined,
373 // false otherwise.
374 bool isStructLatticeConstant(Function *F, StructType *STy) {
375 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
376 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
377 assert(It != TrackedMultipleRetVals.end());
378 LatticeVal LV = It->second;
379 if (LV.isOverdefined())
380 return false;
381 }
382 return true;
383 }
384
Chris Lattner347389d2001-06-27 23:38:11 +0000385private:
Davide Italiano0a1476c2016-12-11 21:19:03 +0000386 // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
Davide Italiano390b7ea2016-07-13 19:33:25 +0000387 void pushToWorkList(LatticeVal &IV, Value *V) {
388 if (IV.isOverdefined())
389 return OverdefinedInstWorkList.push_back(V);
390 InstWorkList.push_back(V);
391 }
392
Chris Lattnerd79334d2004-07-15 23:36:43 +0000393 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000394 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000395 // the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000396 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
397 if (!IV.markConstant(C)) return;
David Greene389fc3b2010-01-05 01:27:15 +0000398 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000399 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000400 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000401
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000402 void markConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000403 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerb4394642004-12-10 08:02:06 +0000404 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000405 }
406
Chris Lattnerf5484032009-11-02 05:55:40 +0000407 void markForcedConstant(Value *V, Constant *C) {
Davide Italiano63266b62016-07-19 18:31:07 +0000408 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000409 LatticeVal &IV = ValueState[V];
410 IV.markForcedConstant(C);
David Greene389fc3b2010-01-05 01:27:15 +0000411 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Davide Italiano390b7ea2016-07-13 19:33:25 +0000412 pushToWorkList(IV, V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000413 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000414
Chris Lattnerd79334d2004-07-15 23:36:43 +0000415 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000416 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000417 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000418 void markOverdefined(LatticeVal &IV, Value *V) {
419 if (!IV.markOverdefined()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000420
David Greene389fc3b2010-01-05 01:27:15 +0000421 DEBUG(dbgs() << "markOverdefined: ";
Davide Italianoe3bdd612016-12-01 08:36:12 +0000422 if (auto *F = dyn_cast<Function>(V))
David Greene389fc3b2010-01-05 01:27:15 +0000423 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000424 else
David Greene389fc3b2010-01-05 01:27:15 +0000425 dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000426 // Only instructions go on the work list
Davide Italiano0a1476c2016-12-11 21:19:03 +0000427 pushToWorkList(IV, V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000428 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000429
Chris Lattnerf5484032009-11-02 05:55:40 +0000430 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000431 if (IV.isOverdefined() || MergeWithV.isUnknown())
Chris Lattnerb4394642004-12-10 08:02:06 +0000432 return; // Noop.
433 if (MergeWithV.isOverdefined())
Davide Italiano21850012016-07-13 19:23:30 +0000434 return markOverdefined(IV, V);
435 if (IV.isUnknown())
436 return markConstant(IV, V, MergeWithV.getConstant());
437 if (IV.getConstant() != MergeWithV.getConstant())
438 return markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000439 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000440
Chris Lattnerf5484032009-11-02 05:55:40 +0000441 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Davide Italiano63266b62016-07-19 18:31:07 +0000442 assert(!V->getType()->isStructTy() &&
443 "non-structs should use markConstant");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000444 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000445 }
446
Chris Lattnerf5484032009-11-02 05:55:40 +0000447 /// getValueState - Return the LatticeVal object that corresponds to the
448 /// value. This function handles the case when the value hasn't been seen yet
449 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000450 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000451 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000452
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000453 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
454 ValueState.insert(std::make_pair(V, LatticeVal()));
455 LatticeVal &LV = I.first->second;
456
457 if (!I.second)
458 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000459
Davide Italianoe3bdd612016-12-01 08:36:12 +0000460 if (auto *C = dyn_cast<Constant>(V)) {
Davide Italiano0f03ce02016-07-10 00:35:15 +0000461 // Undef values remain unknown.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000462 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000463 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000464 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000465
Chris Lattnera3c39d32009-11-02 02:33:50 +0000466 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000467 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000468 }
469
Florian Hahnd0208b42017-10-30 10:07:42 +0000470 ValueLatticeElement &getParamState(Value *V) {
471 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
472
473 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
474 PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
475 ValueLatticeElement &LV = PI.first->second;
476 if (PI.second)
477 LV = getValueState(V).toValueLattice();
478
479 return LV;
480 }
481
Chris Lattner156b8c72009-11-03 23:40:48 +0000482 /// getStructValueState - Return the LatticeVal object that corresponds to the
483 /// value/field pair. This function handles the case when the value hasn't
484 /// been seen yet by properly seeding constants etc.
485 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000486 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000487 assert(i < cast<StructType>(V->getType())->getNumElements() &&
488 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000489
490 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
491 bool> I = StructValueState.insert(
492 std::make_pair(std::make_pair(V, i), LatticeVal()));
493 LatticeVal &LV = I.first->second;
494
495 if (!I.second)
496 return LV; // Common case, already in the map.
497
Davide Italianoe3bdd612016-12-01 08:36:12 +0000498 if (auto *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000499 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000500
Craig Topperf40110f2014-04-25 05:29:35 +0000501 if (!Elt)
Chris Lattner156b8c72009-11-03 23:40:48 +0000502 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000503 else if (isa<UndefValue>(Elt))
Davide Italiano0f03ce02016-07-10 00:35:15 +0000504 ; // Undef values remain unknown.
Chris Lattnerfa775002012-01-26 02:32:04 +0000505 else
506 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000507 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000508
Chris Lattner156b8c72009-11-03 23:40:48 +0000509 // All others are underdefined by default.
510 return LV;
511 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000512
Chris Lattnerf5484032009-11-02 05:55:40 +0000513 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
514 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000515 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
516 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
517 return; // This edge is already known to be executable!
518
Chris Lattner809aee22009-11-02 06:11:23 +0000519 if (!MarkBlockExecutable(Dest)) {
520 // If the destination is already executable, we just made an *edge*
521 // feasible that wasn't before. Revisit the PHI nodes in the block
522 // because they have potentially new operands.
David Greene389fc3b2010-01-05 01:27:15 +0000523 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Nick Lewycky5cd95382013-06-26 00:30:18 +0000524 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000525
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000526 for (PHINode &PN : Dest->phis())
527 visitPHINode(PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000528 }
Chris Lattner347389d2001-06-27 23:38:11 +0000529 }
530
Chris Lattner074be1f2004-11-15 04:44:20 +0000531 // getFeasibleSuccessors - Return a vector of booleans to indicate which
532 // successors are reachable from a given terminator instruction.
Craig Topperb94011f2013-07-14 04:42:23 +0000533 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000534
535 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000536 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000537 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
538
539 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000540 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000541 // information, we need to update the specified user of this instruction.
Chris Lattnerfb141812009-11-03 03:42:51 +0000542 void OperandChangedState(Instruction *I) {
543 if (BBExecutable.count(I->getParent())) // Inst is executable?
544 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000545 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000546
Chris Lattner074be1f2004-11-15 04:44:20 +0000547private:
548 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000549
Chris Lattnera3c39d32009-11-02 02:33:50 +0000550 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000551 // operand made a transition, or the instruction is newly executable. Change
552 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000553 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000554
555 // Terminators
Eugene Zelenko99241d72017-10-20 21:47:29 +0000556
Chris Lattnerb4394642004-12-10 08:02:06 +0000557 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000558 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000559
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000560 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000561 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000562 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000563 void visitCmpInst(CmpInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000564 void visitExtractValueInst(ExtractValueInst &EVI);
565 void visitInsertValueInst(InsertValueInst &IVI);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000566
David Majnemer8a1c45d2015-12-12 05:38:55 +0000567 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000568 markOverdefined(&CPI);
David Majnemereb518bd2015-08-04 08:21:40 +0000569 visitTerminatorInst(CPI);
570 }
Chris Lattner6e560792002-04-18 15:13:15 +0000571
Chris Lattnera3c39d32009-11-02 02:33:50 +0000572 // Instructions that cannot be folded away.
Eugene Zelenko99241d72017-10-20 21:47:29 +0000573
Chris Lattnerf5484032009-11-02 05:55:40 +0000574 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000575 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000576 void visitGetElementPtrInst(GetElementPtrInst &I);
Eugene Zelenko99241d72017-10-20 21:47:29 +0000577
Victor Hernandeze2971492009-10-24 04:23:03 +0000578 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000579 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000580 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000581
Chris Lattnerb4394642004-12-10 08:02:06 +0000582 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000583 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000584 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000585 }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000586
Chris Lattnerb4394642004-12-10 08:02:06 +0000587 void visitCallSite (CallSite CS);
Davide Italianoa7f5e882016-05-04 23:27:13 +0000588 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
589 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
590 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eugene Zelenko99241d72017-10-20 21:47:29 +0000591
Chris Lattner113f4f42002-06-25 16:13:24 +0000592 void visitInstruction(Instruction &I) {
Davide Italiano0b1190a2017-06-16 20:27:17 +0000593 // All the instructions we don't do any special handling for just
594 // go to overdefined.
Davide Italiano463bebc2016-12-13 05:56:04 +0000595 DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
Davide Italiano0b1190a2017-06-16 20:27:17 +0000596 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000597 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000598};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000599
Duncan Sands2be91fc2007-07-20 08:56:21 +0000600} // end anonymous namespace
601
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000602// getFeasibleSuccessors - Return a vector of booleans to indicate which
603// successors are reachable from a given terminator instruction.
Chris Lattner074be1f2004-11-15 04:44:20 +0000604void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000605 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000606 Succs.resize(TI.getNumSuccessors());
Davide Italianoe3bdd612016-12-01 08:36:12 +0000607 if (auto *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000608 if (BI->isUnconditional()) {
609 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000610 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000611 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000612
Chris Lattnerf5484032009-11-02 05:55:40 +0000613 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000614 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000615 if (!CI) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000616 // Overdefined condition variables, and branches on unfoldable constant
617 // conditions, mean the branch could go either way.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000618 if (!BCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000619 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000620 return;
621 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000622
Chris Lattner6df5cec2009-11-02 02:30:06 +0000623 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000624 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000625 return;
626 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000627
David Majnemer654e1302015-07-31 17:58:14 +0000628 // Unwinding instructions successors are always executable.
629 if (TI.isExceptional()) {
630 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattneree8b9512009-10-29 01:21:20 +0000631 return;
632 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000633
Davide Italianoe3bdd612016-12-01 08:36:12 +0000634 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000635 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000636 Succs[0] = true;
637 return;
638 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000639 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000640 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000641
Davide Italiano0f03ce02016-07-10 00:35:15 +0000642 if (!CI) { // Overdefined or unknown condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000643 // All destinations are executable!
Davide Italiano0f03ce02016-07-10 00:35:15 +0000644 if (!SCValue.isUnknown())
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000645 Succs.assign(TI.getNumSuccessors(), true);
646 return;
647 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000648
Chandler Carruth927d8e62017-04-12 07:27:28 +0000649 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000650 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000651 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000652
Xin Tong34888c02017-04-10 00:33:25 +0000653 // In case of indirect branch and its address is a blockaddress, we mark
654 // the target as executable.
655 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
656 // Casts are folded by visitCastInst.
657 LatticeVal IBRValue = getValueState(IBR->getAddress());
658 BlockAddress *Addr = IBRValue.getBlockAddress();
659 if (!Addr) { // Overdefined or unknown condition?
660 // All destinations are executable!
661 if (!IBRValue.isUnknown())
662 Succs.assign(TI.getNumSuccessors(), true);
663 return;
664 }
665
666 BasicBlock* T = Addr->getBasicBlock();
667 assert(Addr->getFunction() == T->getParent() &&
668 "Block address of a different function ?");
669 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
670 // This is the target.
671 if (IBR->getDestination(i) == T) {
672 Succs[i] = true;
673 return;
674 }
675 }
676
677 // If we didn't find our destination in the IBR successor list, then we
678 // have undefined behavior. Its ok to assume no successor is executable.
Chris Lattneree8b9512009-10-29 01:21:20 +0000679 return;
680 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000681
Davide Italiano33af6fe2016-12-01 08:48:14 +0000682 DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
Chris Lattneree8b9512009-10-29 01:21:20 +0000683 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000684}
685
Chris Lattner13b52e72002-05-02 21:18:01 +0000686// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000687// block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000688bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000689 assert(BBExecutable.count(To) && "Dest should always be alive!");
690
691 // Make sure the source basic block is executable!!
692 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000693
Chris Lattnera3c39d32009-11-02 02:33:50 +0000694 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000695 TerminatorInst *TI = From->getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +0000696 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000697 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000698 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000699
Chris Lattnerf5484032009-11-02 05:55:40 +0000700 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000701
Chris Lattner6df5cec2009-11-02 02:30:06 +0000702 // Overdefined condition variables mean the branch could go either way,
703 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000704 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000705 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000706 return !BCValue.isUnknown();
Jakub Staszak632a3552012-01-18 21:16:33 +0000707
Chris Lattner6df5cec2009-11-02 02:30:06 +0000708 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000709 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000710 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000711
David Majnemer654e1302015-07-31 17:58:14 +0000712 // Unwinding instructions successors are always executable.
713 if (TI->isExceptional())
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000714 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000715
Davide Italianoe3bdd612016-12-01 08:36:12 +0000716 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000717 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000718 return true;
719
Chris Lattnerf5484032009-11-02 05:55:40 +0000720 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000721 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000722
Craig Topperf40110f2014-04-25 05:29:35 +0000723 if (!CI)
Davide Italiano0f03ce02016-07-10 00:35:15 +0000724 return !SCValue.isUnknown();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000725
Chandler Carruth927d8e62017-04-12 07:27:28 +0000726 return SI->findCaseValue(CI)->getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000727 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000728
Xin Tong34888c02017-04-10 00:33:25 +0000729 // In case of indirect branch and its address is a blockaddress, we mark
730 // the target as executable.
731 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
732 LatticeVal IBRValue = getValueState(IBR->getAddress());
733 BlockAddress *Addr = IBRValue.getBlockAddress();
734
735 if (!Addr)
736 return !IBRValue.isUnknown();
737
738 // At this point, the indirectbr is branching on a blockaddress.
739 return Addr->getBasicBlock() == To;
740 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000741
Davide Italiano33af6fe2016-12-01 08:48:14 +0000742 DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
Davide Italianodd04fee2015-11-25 21:03:36 +0000743 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattner13b52e72002-05-02 21:18:01 +0000744}
Chris Lattner347389d2001-06-27 23:38:11 +0000745
Chris Lattnera3c39d32009-11-02 02:33:50 +0000746// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000747// operand made a transition, or the instruction is newly executable. Change
748// the value type of I to reflect these changes if appropriate. This method
749// makes sure to do the following actions:
750//
751// 1. If a phi node merges two constants in, and has conflicting value coming
752// from different branches, or if the PHI node merges in an overdefined
753// value, then the PHI node becomes overdefined.
754// 2. If a phi node merges only constants in, and they all agree on value, the
755// PHI node becomes a constant value equal to that.
756// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
757// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
758// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
759// 6. If a conditional branch has a value that is constant, make the selected
760// destination executable
761// 7. If a conditional branch has a value that is overdefined, make all
762// successors executable.
Chris Lattner074be1f2004-11-15 04:44:20 +0000763void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000764 // If this PN returns a struct, just mark the result overdefined.
765 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000766 if (PN.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000767 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000768
Eli Friedman0a309292011-11-11 01:16:15 +0000769 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000770 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000771
Chris Lattner7a7b1142004-03-16 19:49:59 +0000772 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
773 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000774 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000775 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000776
Chris Lattner6e560792002-04-18 15:13:15 +0000777 // Look at all of the executable operands of the PHI node. If any of them
778 // are overdefined, the PHI becomes overdefined as well. If they are all
779 // constant, and they agree with each other, the PHI becomes the identical
780 // constant. If they are constant and don't agree, the PHI is overdefined.
Davide Italiano0f03ce02016-07-10 00:35:15 +0000781 // If there are no executable operands, the PHI remains unknown.
Craig Topperf40110f2014-04-25 05:29:35 +0000782 Constant *OperandVal = nullptr;
Chris Lattnercccc5c72003-04-25 02:50:03 +0000783 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000784 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +0000785 if (IV.isUnknown()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000786
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000787 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
788 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000789
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000790 if (IV.isOverdefined()) // PHI node becomes overdefined!
791 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000792
Craig Topperf40110f2014-04-25 05:29:35 +0000793 if (!OperandVal) { // Grab the first value.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000794 OperandVal = IV.getConstant();
795 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000796 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000797
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000798 // There is already a reachable operand. If we conflict with it,
799 // then the PHI node becomes overdefined. If we agree with it, we
800 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000801
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000802 // Check to see if there are two different constants merging, if so, the PHI
803 // node is overdefined.
804 if (IV.getConstant() != OperandVal)
805 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000806 }
807
Chris Lattner6e560792002-04-18 15:13:15 +0000808 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000809 // arguments that agree with each other(and OperandVal is the constant) or
810 // OperandVal is null because there are no defined incoming arguments. If
Davide Italiano0f03ce02016-07-10 00:35:15 +0000811 // this is the case, the PHI remains unknown.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000812 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000813 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000814}
815
Chris Lattnerb4394642004-12-10 08:02:06 +0000816void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000817 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000818
Chris Lattnerb4394642004-12-10 08:02:06 +0000819 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000820 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000821
Devang Patela7a20752008-03-11 05:46:42 +0000822 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000823 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000824 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000825 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000826 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000827 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000828 return;
829 }
830 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000831
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000832 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000833 if (!TrackedMultipleRetVals.empty()) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000834 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000835 if (MRVFunctionsTracked.count(F))
836 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
837 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
838 getStructValueState(ResultOp, i));
Chris Lattnerb4394642004-12-10 08:02:06 +0000839 }
840}
841
Chris Lattner074be1f2004-11-15 04:44:20 +0000842void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000843 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000844 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000845
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000846 BasicBlock *BB = TI.getParent();
847
Chris Lattnera3c39d32009-11-02 02:33:50 +0000848 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000849 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000850 if (SuccFeasible[i])
851 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000852}
853
Chris Lattner074be1f2004-11-15 04:44:20 +0000854void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000855 LatticeVal OpSt = getValueState(I.getOperand(0));
856 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000857 markOverdefined(&I);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000858 else if (OpSt.isConstant()) {
Davide Italianod555bde2016-07-08 19:13:40 +0000859 // Fold the constant as we build.
Davide Italiano63c4ce82016-07-11 18:21:29 +0000860 Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
861 I.getType(), DL);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000862 if (isa<UndefValue>(C))
863 return;
864 // Propagate constant value
865 markConstant(&I, C);
866 }
Chris Lattner6e560792002-04-18 15:13:15 +0000867}
868
Dan Gohman041f9d02008-06-20 01:15:44 +0000869void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000870 // If this returns a struct, mark all elements over defined, we don't track
871 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000872 if (EVI.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000873 return markOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000874
Chris Lattner156b8c72009-11-03 23:40:48 +0000875 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000876 if (EVI.getNumIndices() != 1)
877 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000878
Chris Lattner156b8c72009-11-03 23:40:48 +0000879 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000880 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000881 unsigned i = *EVI.idx_begin();
882 LatticeVal EltVal = getStructValueState(AggVal, i);
883 mergeInValue(getValueState(&EVI), &EVI, EltVal);
884 } else {
885 // Otherwise, must be extracting from an array.
886 return markOverdefined(&EVI);
887 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000888}
889
890void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Davide Italianoe3bdd612016-12-01 08:36:12 +0000891 auto *STy = dyn_cast<StructType>(IVI.getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000892 if (!STy)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000893 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000894
Chris Lattner156b8c72009-11-03 23:40:48 +0000895 // If this has more than one index, we can't handle it, drive all results to
896 // undef.
897 if (IVI.getNumIndices() != 1)
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000898 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000899
Chris Lattner156b8c72009-11-03 23:40:48 +0000900 Value *Aggr = IVI.getAggregateOperand();
901 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000902
Chris Lattner156b8c72009-11-03 23:40:48 +0000903 // Compute the result based on what we're inserting.
904 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
905 // This passes through all values that aren't the inserted element.
906 if (i != Idx) {
907 LatticeVal EltVal = getStructValueState(Aggr, i);
908 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
909 continue;
910 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000911
Chris Lattner156b8c72009-11-03 23:40:48 +0000912 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000913 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000914 // We don't track structs in structs.
915 markOverdefined(getStructValueState(&IVI, i), &IVI);
916 else {
917 LatticeVal InVal = getValueState(Val);
918 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
919 }
920 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000921}
922
Chris Lattner074be1f2004-11-15 04:44:20 +0000923void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000924 // If this select returns a struct, just mark the result overdefined.
925 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000926 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +0000927 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000928
Chris Lattnerf5484032009-11-02 05:55:40 +0000929 LatticeVal CondValue = getValueState(I.getCondition());
Davide Italiano0f03ce02016-07-10 00:35:15 +0000930 if (CondValue.isUnknown())
Chris Lattner06a0ed12006-02-08 02:38:11 +0000931 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000932
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000933 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000934 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
935 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000936 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000937 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000938
Chris Lattner06a0ed12006-02-08 02:38:11 +0000939 // Otherwise, the condition is overdefined or a constant we can't evaluate.
940 // See if we can produce something better than overdefined based on the T/F
941 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000942 LatticeVal TVal = getValueState(I.getTrueValue());
943 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000944
Chris Lattner06a0ed12006-02-08 02:38:11 +0000945 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000946 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000947 TVal.getConstant() == FVal.getConstant())
948 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000949
Davide Italiano0f03ce02016-07-10 00:35:15 +0000950 if (TVal.isUnknown()) // select ?, undef, X -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000951 return mergeInValue(&I, FVal);
Davide Italiano0f03ce02016-07-10 00:35:15 +0000952 if (FVal.isUnknown()) // select ?, X, undef -> X.
Chris Lattnerf5484032009-11-02 05:55:40 +0000953 return mergeInValue(&I, TVal);
954 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000955}
956
Chris Lattnerf5484032009-11-02 05:55:40 +0000957// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000958void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000959 LatticeVal V1State = getValueState(I.getOperand(0));
960 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000961
Chris Lattner4f031622004-11-15 05:03:30 +0000962 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000963 if (IV.isOverdefined()) return;
964
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000965 if (V1State.isConstant() && V2State.isConstant()) {
966 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
967 V2State.getConstant());
968 // X op Y -> undef.
969 if (isa<UndefValue>(C))
970 return;
971 return markConstant(IV, &I, C);
972 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000973
Chris Lattnerf5484032009-11-02 05:55:40 +0000974 // If something is undef, wait for it to resolve.
975 if (!V1State.isOverdefined() && !V2State.isOverdefined())
976 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000977
Chris Lattnerf5484032009-11-02 05:55:40 +0000978 // Otherwise, one of our operands is overdefined. Try to produce something
979 // better than overdefined with some tricks.
Davide Italiano6c2c3e02017-01-19 23:07:51 +0000980 // If this is 0 / Y, it doesn't matter that the second operand is
981 // overdefined, and we can replace it with zero.
982 if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
983 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
984 return markConstant(IV, &I, V1State.getConstant());
985
Davide Italiano93c6c182017-01-19 21:07:42 +0000986 // If this is:
987 // -> AND/MUL with 0
988 // -> OR with -1
989 // it doesn't matter that the other operand is overdefined.
Davide Italiano824d6952016-12-09 03:08:42 +0000990 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
991 I.getOpcode() == Instruction::Or) {
Craig Topperf40110f2014-04-25 05:29:35 +0000992 LatticeVal *NonOverdefVal = nullptr;
Chris Lattnerf5484032009-11-02 05:55:40 +0000993 if (!V1State.isOverdefined())
994 NonOverdefVal = &V1State;
995 else if (!V2State.isOverdefined())
996 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +0000997
Chris Lattnerf5484032009-11-02 05:55:40 +0000998 if (NonOverdefVal) {
Davide Italianoe7ffae92016-11-22 22:11:25 +0000999 if (NonOverdefVal->isUnknown())
Chris Lattnerf5484032009-11-02 05:55:40 +00001000 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001001
Davide Italiano824d6952016-12-09 03:08:42 +00001002 if (I.getOpcode() == Instruction::And ||
1003 I.getOpcode() == Instruction::Mul) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001004 // X and 0 = 0
Davide Italiano824d6952016-12-09 03:08:42 +00001005 // X * 0 = 0
Chris Lattnerf5484032009-11-02 05:55:40 +00001006 if (NonOverdefVal->getConstant()->isNullValue())
1007 return markConstant(IV, &I, NonOverdefVal->getConstant());
1008 } else {
Davide Italianoe7ffae92016-11-22 22:11:25 +00001009 // X or -1 = -1
Chris Lattnerf5484032009-11-02 05:55:40 +00001010 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
Craig Topper79ab6432017-07-06 18:39:47 +00001011 if (CI->isMinusOne())
Chris Lattnerf5484032009-11-02 05:55:40 +00001012 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +00001013 }
1014 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001015 }
Chris Lattnercbc01612004-12-11 23:15:19 +00001016
Chris Lattnerf5484032009-11-02 05:55:40 +00001017 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +00001018}
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001019
Chris Lattnera3c39d32009-11-02 02:33:50 +00001020// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001021void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001022 LatticeVal V1State = getValueState(I.getOperand(0));
1023 LatticeVal V2State = getValueState(I.getOperand(1));
1024
Reid Spencer266e42b2006-12-23 06:05:41 +00001025 LatticeVal &IV = ValueState[&I];
1026 if (IV.isOverdefined()) return;
1027
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001028 if (V1State.isConstant() && V2State.isConstant()) {
1029 Constant *C = ConstantExpr::getCompare(
1030 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
1031 if (isa<UndefValue>(C))
1032 return;
1033 return markConstant(IV, &I, C);
1034 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001035
Davide Italiano0f03ce02016-07-10 00:35:15 +00001036 // If operands are still unknown, wait for it to resolve.
Chris Lattnerf5484032009-11-02 05:55:40 +00001037 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1038 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001039
Chris Lattnerf5484032009-11-02 05:55:40 +00001040 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +00001041}
1042
Chris Lattnera3c39d32009-11-02 02:33:50 +00001043// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001044// can turn this into a getelementptr ConstantExpr.
Chris Lattner074be1f2004-11-15 04:44:20 +00001045void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001046 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001047
Chris Lattner0e7ec672007-02-02 20:51:48 +00001048 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001049 Operands.reserve(I.getNumOperands());
1050
1051 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001052 LatticeVal State = getValueState(I.getOperand(i));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001053 if (State.isUnknown())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001054 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001055
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001056 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001057 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001058
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001059 assert(State.isConstant() && "Unknown state!");
1060 Operands.push_back(State.getConstant());
1061 }
1062
1063 Constant *Ptr = Operands[0];
Craig Toppere1d12942014-08-27 05:25:25 +00001064 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001065 Constant *C =
1066 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1067 if (isa<UndefValue>(C))
1068 return;
1069 markConstant(&I, C);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001070}
Brian Gaeke960707c2003-11-11 22:41:34 +00001071
Chris Lattnerf5484032009-11-02 05:55:40 +00001072void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001073 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001074 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001075 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001076
Chris Lattner91dbae62004-12-11 05:15:59 +00001077 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1078 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001079
Chris Lattner91dbae62004-12-11 05:15:59 +00001080 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001081 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001082 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1083
Chris Lattnerf5484032009-11-02 05:55:40 +00001084 // Get the value we are storing into the global, then merge it.
1085 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001086 if (I->second.isOverdefined())
1087 TrackedGlobals.erase(I); // No need to keep tracking this!
1088}
1089
Chris Lattner49f74522004-01-12 04:29:41 +00001090// Handle load instructions. If the operand is a constant pointer to a constant
1091// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001092void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001093 // If this load is of a struct, just mark the result overdefined.
David Majnemerf3b99dd2016-01-07 19:30:13 +00001094 if (I.getType()->isStructTy())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001095 return markOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001096
Chris Lattnerf5484032009-11-02 05:55:40 +00001097 LatticeVal PtrVal = getValueState(I.getOperand(0));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001098 if (PtrVal.isUnknown()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001099
Chris Lattner4f031622004-11-15 05:03:30 +00001100 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001101 if (IV.isOverdefined()) return;
1102
Chris Lattnerf5484032009-11-02 05:55:40 +00001103 if (!PtrVal.isConstant() || I.isVolatile())
1104 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001105
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001106 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001107
David Majnemerbae94572016-01-07 19:25:39 +00001108 // load null is undefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001109 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
David Majnemerbae94572016-01-07 19:25:39 +00001110 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001111
Chris Lattnerf5484032009-11-02 05:55:40 +00001112 // Transform load (constant global) into the value loaded.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001113 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001114 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001115 // If we are tracking this global, merge in the known value for it.
1116 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1117 TrackedGlobals.find(GV);
1118 if (It != TrackedGlobals.end()) {
1119 mergeInValue(IV, &I, It->second);
1120 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001121 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001122 }
Chris Lattner49f74522004-01-12 04:29:41 +00001123 }
1124
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001125 // Transform load from a constant into a constant if possible.
Eduard Burtescu14239212016-01-22 01:17:26 +00001126 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001127 if (isa<UndefValue>(C))
1128 return;
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001129 return markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001130 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001131
Chris Lattner49f74522004-01-12 04:29:41 +00001132 // Otherwise we cannot say for certain what value this load will produce.
1133 // Bail out.
1134 markOverdefined(IV, &I);
1135}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001136
Chris Lattnerb4394642004-12-10 08:02:06 +00001137void SCCPSolver::visitCallSite(CallSite CS) {
1138 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001139 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001140
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001141 // The common case is that we aren't tracking the callee, either because we
1142 // are not doing interprocedural analysis or the callee is indirect, or is
1143 // external. Handle these cases first.
Craig Topperf40110f2014-04-25 05:29:35 +00001144 if (!F || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001145CallOverdefined:
1146 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001147 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001148
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001149 // Otherwise, if we have a single return value case, and if the function is
1150 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001151 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Andrew Kaylor647025f2017-06-09 23:18:11 +00001152 canConstantFoldCallTo(CS, F)) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001153 SmallVector<Constant*, 8> Operands;
1154 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1155 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001156 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001157
Davide Italiano0f03ce02016-07-10 00:35:15 +00001158 if (State.isUnknown())
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001159 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001160 if (State.isOverdefined())
1161 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001162 assert(State.isConstant() && "Unknown state!");
1163 Operands.push_back(State.getConstant());
1164 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001165
David Majnemer2098b86f2014-11-07 08:54:19 +00001166 if (getValueState(I).isOverdefined())
1167 return;
1168
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001169 // If we can constant fold this, mark the result of the call as a
1170 // constant.
Andrew Kaylor647025f2017-06-09 23:18:11 +00001171 if (Constant *C = ConstantFoldCall(CS, F, Operands, TLI)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001172 // call -> undef.
1173 if (isa<UndefValue>(C))
1174 return;
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001175 return markConstant(I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001176 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001177 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001178
1179 // Otherwise, we don't know anything about this call, mark it overdefined.
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001180 return markOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001181 }
1182
Chris Lattnercde8de52009-11-03 19:24:51 +00001183 // If this is a local function that doesn't have its address taken, mark its
1184 // entry block executable and merge in the actual arguments to the call into
1185 // the formal arguments of the function.
1186 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001187 MarkBlockExecutable(&F->front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001188
Chris Lattnercde8de52009-11-03 19:24:51 +00001189 // Propagate information from this call site into the callee.
1190 CallSite::arg_iterator CAI = CS.arg_begin();
1191 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1192 AI != E; ++AI, ++CAI) {
1193 // If this argument is byval, and if the function is not readonly, there
1194 // will be an implicit copy formed of the input aggregate.
1195 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001196 markOverdefined(&*AI);
Chris Lattnercde8de52009-11-03 19:24:51 +00001197 continue;
1198 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001199
Davide Italianoe3bdd612016-12-01 08:36:12 +00001200 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001201 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1202 LatticeVal CallArg = getStructValueState(*CAI, i);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001203 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
Chris Lattner762b56f2009-11-04 18:57:42 +00001204 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001205 } else {
Florian Hahnd0208b42017-10-30 10:07:42 +00001206 // Most other parts of the Solver still only use the simpler value
1207 // lattice, so we propagate changes for parameters to both lattices.
1208 getParamState(&*AI).mergeIn(getValueState(*CAI).toValueLattice(), DL);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001209 mergeInValue(&*AI, getValueState(*CAI));
Chris Lattner156b8c72009-11-03 23:40:48 +00001210 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001211 }
1212 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001213
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001214 // If this is a single/zero retval case, see if we're tracking the function.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001215 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001216 if (!MRVFunctionsTracked.count(F))
1217 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001218
Chris Lattner156b8c72009-11-03 23:40:48 +00001219 // If we are tracking this callee, propagate the result of the function
1220 // into this call site.
1221 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001222 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001223 TrackedMultipleRetVals[std::make_pair(F, i)]);
1224 } else {
1225 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1226 if (TFRVI == TrackedRetVals.end())
1227 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001228
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001229 // If so, propagate the return value of the callee into this call result.
1230 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001231 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001232}
Chris Lattner074be1f2004-11-15 04:44:20 +00001233
Chris Lattner074be1f2004-11-15 04:44:20 +00001234void SCCPSolver::Solve() {
1235 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001236 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001237 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001238 // Process the overdefined instruction's work list first, which drives other
1239 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001240 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001241 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001242
David Greene389fc3b2010-01-05 01:27:15 +00001243 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001244
Chris Lattner074be1f2004-11-15 04:44:20 +00001245 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001246 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001247 //
1248 // Anything on this worklist that is overdefined need not be visited
1249 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001250 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001251 //
Chandler Carruthcdf47882014-03-09 03:16:01 +00001252 for (User *U : I->users())
Davide Italianoe3bdd612016-12-01 08:36:12 +00001253 if (auto *UI = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +00001254 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001255 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001256
Chris Lattnera3c39d32009-11-02 02:33:50 +00001257 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001258 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001259 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001260
David Greene389fc3b2010-01-05 01:27:15 +00001261 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001262
Chris Lattnerf5484032009-11-02 05:55:40 +00001263 // "I" got into the work list because it made the transition from undef to
1264 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001265 //
1266 // Anything on this worklist that is overdefined need not be visited
1267 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001268 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001269 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001270 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001271 for (User *U : I->users())
Davide Italianoe3bdd612016-12-01 08:36:12 +00001272 if (auto *UI = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +00001273 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001274 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001275
Chris Lattnera3c39d32009-11-02 02:33:50 +00001276 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001277 while (!BBWorkList.empty()) {
1278 BasicBlock *BB = BBWorkList.back();
1279 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001280
David Greene389fc3b2010-01-05 01:27:15 +00001281 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001282
Chris Lattner074be1f2004-11-15 04:44:20 +00001283 // Notify all instructions in this basic block that they are newly
1284 // executable.
1285 visit(BB);
1286 }
1287 }
1288}
1289
Chris Lattner1847f6d2006-12-20 06:21:33 +00001290/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001291/// that branches on undef values cannot reach any of their successors.
1292/// However, this is not a safe assumption. After we solve dataflow, this
1293/// method should be use to handle this. If this returns true, the solver
1294/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001295///
1296/// This method handles this by finding an unresolved branch and marking it one
1297/// of the edges from the block as being feasible, even though the condition
1298/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1299/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001300/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001301/// constraints on the condition of the branch, as that would impact other users
1302/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001303///
1304/// This scan also checks for values that use undefs, whose results are actually
1305/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1306/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1307/// even if X isn't defined.
1308bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001309 for (BasicBlock &BB : F) {
1310 if (!BBExecutable.count(&BB))
Chris Lattneraf170962006-10-22 05:59:17 +00001311 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001312
Benjamin Kramer135f7352016-06-26 12:28:59 +00001313 for (Instruction &I : BB) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001314 // Look for instructions which produce undef values.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001315 if (I.getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001316
Davide Italianoe3bdd612016-12-01 08:36:12 +00001317 if (auto *STy = dyn_cast<StructType>(I.getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001318 // Only a few things that can be structs matter for undef.
1319
1320 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001321 if (CallSite CS = CallSite(&I))
Eli Friedman1815b682011-09-20 23:28:51 +00001322 if (Function *F = CS.getCalledFunction())
1323 if (MRVFunctionsTracked.count(F))
1324 continue;
1325
1326 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001327 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001328 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1329 continue;
1330
1331 // Send the results of everything else to overdefined. We could be
1332 // more precise than this but it isn't worth bothering.
1333 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001334 LatticeVal &LV = getStructValueState(&I, i);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001335 if (LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001336 markOverdefined(LV, &I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001337 }
1338 continue;
1339 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001340
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001341 LatticeVal &LV = getValueState(&I);
Davide Italiano0f03ce02016-07-10 00:35:15 +00001342 if (!LV.isUnknown()) continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001343
Eli Friedmand7749be2011-08-17 18:10:43 +00001344 // extractvalue is safe; check here because the argument is a struct.
1345 if (isa<ExtractValueInst>(I))
1346 continue;
1347
1348 // Compute the operand LatticeVals, for convenience below.
1349 // Anything taking a struct is conservatively assumed to require
1350 // overdefined markings.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001351 if (I.getOperand(0)->getType()->isStructTy()) {
1352 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001353 return true;
1354 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001355 LatticeVal Op0LV = getValueState(I.getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001356 LatticeVal Op1LV;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001357 if (I.getNumOperands() == 2) {
1358 if (I.getOperand(1)->getType()->isStructTy()) {
1359 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001360 return true;
1361 }
1362
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001363 Op1LV = getValueState(I.getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001364 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001365 // If this is an instructions whose result is defined even if the input is
1366 // not fully defined, propagate the information.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001367 Type *ITy = I.getType();
1368 switch (I.getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001369 case Instruction::Add:
1370 case Instruction::Sub:
1371 case Instruction::Trunc:
1372 case Instruction::FPTrunc:
1373 case Instruction::BitCast:
1374 break; // Any undef -> undef
1375 case Instruction::FSub:
1376 case Instruction::FAdd:
1377 case Instruction::FMul:
1378 case Instruction::FDiv:
1379 case Instruction::FRem:
1380 // Floating-point binary operation: be conservative.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001381 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001382 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001383 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001384 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001385 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001386 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001387 case Instruction::SExt:
1388 case Instruction::FPToUI:
1389 case Instruction::FPToSI:
1390 case Instruction::FPExt:
1391 case Instruction::PtrToInt:
1392 case Instruction::IntToPtr:
1393 case Instruction::SIToFP:
1394 case Instruction::UIToFP:
1395 // undef -> 0; some outputs are impossible
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001396 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001397 return true;
1398 case Instruction::Mul:
1399 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001400 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001401 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001402 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001403 // undef * X -> 0. X could be zero.
1404 // undef & X -> 0. X could be zero.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001405 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001406 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001407 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001408 // Both operands undef -> undef
Davide Italiano0f03ce02016-07-10 00:35:15 +00001409 if (Op0LV.isUnknown() && Op1LV.isUnknown())
Eli Friedman0793eb42011-08-16 22:06:31 +00001410 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001411 // undef | X -> -1. X could be -1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001412 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001413 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001414 case Instruction::Xor:
1415 // undef ^ undef -> 0; strictly speaking, this is not strictly
1416 // necessary, but we try to be nice to people who expect this
1417 // behavior in simple cases
Davide Italiano0f03ce02016-07-10 00:35:15 +00001418 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001419 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001420 return true;
1421 }
1422 // undef ^ X -> undef
1423 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001424 case Instruction::SDiv:
1425 case Instruction::UDiv:
1426 case Instruction::SRem:
1427 case Instruction::URem:
1428 // X / undef -> undef. No change.
1429 // X % undef -> undef. No change.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001430 if (Op1LV.isUnknown()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001431
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001432 // X / 0 -> undef. No change.
1433 // X % 0 -> undef. No change.
1434 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1435 break;
1436
Chris Lattner1847f6d2006-12-20 06:21:33 +00001437 // undef / X -> 0. X could be maxint.
1438 // undef % X -> 0. X could be 1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001439 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001440 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001441 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001442 // X >>a undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001443 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001444
David Majnemer96f0d382016-05-12 03:07:40 +00001445 // Shifting by the bitwidth or more is undefined.
1446 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001447 if (auto *ShiftAmt = Op1LV.getConstantInt())
1448 if (ShiftAmt->getLimitedValue() >=
1449 ShiftAmt->getType()->getScalarSizeInBits())
1450 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001451 }
1452
Davide Italiano54c683f2016-12-08 22:28:53 +00001453 // undef >>a X -> 0
1454 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001455 return true;
1456 case Instruction::LShr:
1457 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001458 // X << undef -> undef.
1459 // X >> undef -> undef.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001460 if (Op1LV.isUnknown()) break;
Eli Friedman0793eb42011-08-16 22:06:31 +00001461
David Majnemer96f0d382016-05-12 03:07:40 +00001462 // Shifting by the bitwidth or more is undefined.
1463 if (Op1LV.isConstant()) {
David Majnemerd1fbf482016-06-23 00:14:29 +00001464 if (auto *ShiftAmt = Op1LV.getConstantInt())
1465 if (ShiftAmt->getLimitedValue() >=
1466 ShiftAmt->getType()->getScalarSizeInBits())
1467 break;
David Majnemer96f0d382016-05-12 03:07:40 +00001468 }
1469
Eli Friedman0793eb42011-08-16 22:06:31 +00001470 // undef << X -> 0
1471 // undef >> X -> 0
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001472 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001473 return true;
1474 case Instruction::Select:
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001475 Op1LV = getValueState(I.getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001476 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
Davide Italiano0f03ce02016-07-10 00:35:15 +00001477 if (Op0LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001478 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001479 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001480 } else if (Op1LV.isUnknown()) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001481 // c ? undef : undef -> undef. No change.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001482 Op1LV = getValueState(I.getOperand(2));
Davide Italiano0f03ce02016-07-10 00:35:15 +00001483 if (Op1LV.isUnknown())
Chris Lattner1847f6d2006-12-20 06:21:33 +00001484 break;
1485 // Otherwise, c ? undef : x -> x.
1486 } else {
1487 // Leave Op1LV as Operand(1)'s LatticeValue.
1488 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001489
Chris Lattner1847f6d2006-12-20 06:21:33 +00001490 if (Op1LV.isConstant())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001491 markForcedConstant(&I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001492 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001493 markOverdefined(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001494 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001495 case Instruction::Load:
1496 // A load here means one of two things: a load of undef from a global,
1497 // a load from an unknown pointer. Either way, having it return undef
1498 // is okay.
1499 break;
1500 case Instruction::ICmp:
1501 // X == undef -> undef. Other comparisons get more complicated.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001502 if (cast<ICmpInst>(&I)->isEquality())
Eli Friedman0793eb42011-08-16 22:06:31 +00001503 break;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001504 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001505 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001506 case Instruction::Call:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001507 case Instruction::Invoke:
Eli Friedman1815b682011-09-20 23:28:51 +00001508 // There are two reasons a call can have an undef result
1509 // 1. It could be tracked.
1510 // 2. It could be constant-foldable.
1511 // Because of the way we solve return values, tracked calls must
1512 // never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001513 if (Function *F = CallSite(&I).getCalledFunction())
Eli Friedman1815b682011-09-20 23:28:51 +00001514 if (TrackedRetVals.count(F))
1515 break;
1516
1517 // If the call is constant-foldable, we mark it overdefined because
1518 // we do not know what return values are valid.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001519 markOverdefined(&I);
Eli Friedman1815b682011-09-20 23:28:51 +00001520 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001521 default:
1522 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001523 // overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001524 markOverdefined(&I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001525 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001526 }
1527 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001528
Chris Lattneradca6082010-04-05 22:14:48 +00001529 // Check to see if we have a branch or switch on an undefined value. If so
1530 // we force the branch to go one way or the other to make the successor
1531 // values live. It doesn't really matter which way we force it.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001532 TerminatorInst *TI = BB.getTerminator();
Davide Italianoe3bdd612016-12-01 08:36:12 +00001533 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneraf170962006-10-22 05:59:17 +00001534 if (!BI->isConditional()) continue;
Davide Italiano0f03ce02016-07-10 00:35:15 +00001535 if (!getValueState(BI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001536 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001537
Chris Lattneradca6082010-04-05 22:14:48 +00001538 // If the input to SCCP is actually branch on undef, fix the undef to
1539 // false.
1540 if (isa<UndefValue>(BI->getCondition())) {
1541 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Benjamin Kramer135f7352016-06-26 12:28:59 +00001542 markEdgeExecutable(&BB, TI->getSuccessor(1));
Chris Lattneradca6082010-04-05 22:14:48 +00001543 return true;
1544 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001545
Chris Lattneradca6082010-04-05 22:14:48 +00001546 // Otherwise, it is a branch on a symbolic value which is currently
1547 // considered to be undef. Handle this by forcing the input value to the
1548 // branch to false.
1549 markForcedConstant(BI->getCondition(),
1550 ConstantInt::getFalse(TI->getContext()));
1551 return true;
1552 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001553
Xin Tong34888c02017-04-10 00:33:25 +00001554 if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1555 // Indirect branch with no successor ?. Its ok to assume it branches
1556 // to no target.
1557 if (IBR->getNumSuccessors() < 1)
1558 continue;
1559
1560 if (!getValueState(IBR->getAddress()).isUnknown())
1561 continue;
1562
1563 // If the input to SCCP is actually branch on undef, fix the undef to
1564 // the first successor of the indirect branch.
1565 if (isa<UndefValue>(IBR->getAddress())) {
1566 IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1567 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1568 return true;
1569 }
1570
1571 // Otherwise, it is a branch on a symbolic value which is currently
1572 // considered to be undef. Handle this by forcing the input value to the
1573 // branch to the first successor.
1574 markForcedConstant(IBR->getAddress(),
1575 BlockAddress::get(IBR->getSuccessor(0)));
1576 return true;
1577 }
1578
Davide Italianoe3bdd612016-12-01 08:36:12 +00001579 if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Davide Italiano094dadd2016-07-15 18:33:16 +00001580 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
Chris Lattneraf170962006-10-22 05:59:17 +00001581 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001582
Chris Lattneradca6082010-04-05 22:14:48 +00001583 // If the input to SCCP is actually switch on undef, fix the undef to
1584 // the first constant.
1585 if (isa<UndefValue>(SI->getCondition())) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00001586 SI->setCondition(SI->case_begin()->getCaseValue());
1587 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001588 return true;
1589 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001590
Chandler Carruth927d8e62017-04-12 07:27:28 +00001591 markForcedConstant(SI->getCondition(), SI->case_begin()->getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001592 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001593 }
Chris Lattneraf170962006-10-22 05:59:17 +00001594 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001595
Chris Lattneraf170962006-10-22 05:59:17 +00001596 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001597}
1598
Florian Hahnd0208b42017-10-30 10:07:42 +00001599static bool tryToReplaceWithConstantRange(SCCPSolver &Solver, Value *V) {
1600 bool Changed = false;
1601
1602 // Currently we only use range information for integer values.
1603 if (!V->getType()->isIntegerTy())
1604 return false;
1605
1606 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
1607 if (!IV.isConstantRange())
1608 return false;
1609
1610 for (auto UI = V->uses().begin(), E = V->uses().end(); UI != E;) {
1611 const Use &U = *UI++;
1612 auto *Icmp = dyn_cast<ICmpInst>(U.getUser());
1613 if (!Icmp || !Solver.isBlockExecutable(Icmp->getParent()))
1614 continue;
1615
Davide Italianob480b5c2017-11-22 03:04:55 +00001616 auto getIcmpLatticeValue = [&](Value *Op) {
1617 if (auto *C = dyn_cast<Constant>(Op))
1618 return ValueLatticeElement::get(C);
1619 return Solver.getLatticeValueFor(Op);
1620 };
1621
1622 ValueLatticeElement A = getIcmpLatticeValue(Icmp->getOperand(0));
1623 ValueLatticeElement B = getIcmpLatticeValue(Icmp->getOperand(1));
1624
Florian Hahnd0208b42017-10-30 10:07:42 +00001625 Constant *C = nullptr;
1626 if (A.satisfiesPredicate(Icmp->getPredicate(), B))
1627 C = ConstantInt::getTrue(Icmp->getType());
1628 else if (A.satisfiesPredicate(Icmp->getInversePredicate(), B))
1629 C = ConstantInt::getFalse(Icmp->getType());
1630
1631 if (C) {
1632 Icmp->replaceAllUsesWith(C);
1633 DEBUG(dbgs() << "Replacing " << *Icmp << " with " << *C
1634 << ", because of range information " << A << " " << B
1635 << "\n");
1636 Icmp->eraseFromParent();
1637 Changed = true;
1638 }
1639 }
1640 return Changed;
1641}
1642
Davide Italiano6f735882016-07-14 20:25:54 +00001643static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
Davide Italiano296e9782016-07-13 23:20:04 +00001644 Constant *Const = nullptr;
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001645 if (V->getType()->isStructTy()) {
1646 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
Eugene Zelenko99241d72017-10-20 21:47:29 +00001647 if (llvm::any_of(IVs,
1648 [](const LatticeVal &LV) { return LV.isOverdefined(); }))
Davide Italiano296e9782016-07-13 23:20:04 +00001649 return false;
1650 std::vector<Constant *> ConstVals;
Davide Italianoe3bdd612016-12-01 08:36:12 +00001651 auto *ST = dyn_cast<StructType>(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001652 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1653 LatticeVal V = IVs[i];
1654 ConstVals.push_back(V.isConstant()
1655 ? V.getConstant()
1656 : UndefValue::get(ST->getElementType(i)));
1657 }
1658 Const = ConstantStruct::get(ST, ConstVals);
1659 } else {
Florian Hahnd0208b42017-10-30 10:07:42 +00001660 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
Davide Italiano296e9782016-07-13 23:20:04 +00001661 if (IV.isOverdefined())
1662 return false;
Florian Hahnd0208b42017-10-30 10:07:42 +00001663
1664 if (IV.isConstantRange()) {
1665 if (IV.getConstantRange().isSingleElement())
1666 Const =
1667 ConstantInt::get(V->getType(), IV.asConstantInteger().getValue());
1668 else
1669 return false;
1670 } else
1671 Const =
1672 IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
Davide Italiano296e9782016-07-13 23:20:04 +00001673 }
1674 assert(Const && "Constant is nullptr here!");
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001675 DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
Davide Italiano296e9782016-07-13 23:20:04 +00001676
1677 // Replaces all of the uses of a variable with uses of the constant.
Davide Italianoed4d5ea2016-07-14 03:02:34 +00001678 V->replaceAllUsesWith(Const);
Davide Italiano6ed6d772016-07-14 01:27:29 +00001679 return true;
1680}
1681
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001682// runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner074be1f2004-11-15 04:44:20 +00001683// and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001684static bool runSCCP(Function &F, const DataLayout &DL,
1685 const TargetLibraryInfo *TLI) {
David Greene389fc3b2010-01-05 01:27:15 +00001686 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001687 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001688
1689 // Mark the first block of the function as being executable.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001690 Solver.MarkBlockExecutable(&F.front());
Chris Lattner074be1f2004-11-15 04:44:20 +00001691
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001692 // Mark all arguments to the function as being overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001693 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001694 Solver.markOverdefined(&AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001695
Chris Lattner074be1f2004-11-15 04:44:20 +00001696 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001697 bool ResolvedUndefs = true;
1698 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001699 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001700 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001701 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001702 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001703
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001704 bool MadeChanges = false;
1705
1706 // If we decided that there are basic blocks that are dead in this function,
1707 // delete their contents now. Note that we cannot actually delete the blocks,
1708 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001709
Benjamin Kramer135f7352016-06-26 12:28:59 +00001710 for (BasicBlock &BB : F) {
1711 if (!Solver.isBlockExecutable(&BB)) {
1712 DEBUG(dbgs() << " BasicBlock Dead:" << BB);
David Majnemer88542a02016-01-24 06:26:47 +00001713
1714 ++NumDeadBlocks;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001715 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer88542a02016-01-24 06:26:47 +00001716
Chris Lattnere405ed92009-11-02 02:47:51 +00001717 MadeChanges = true;
1718 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001719 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001720
Chris Lattnere405ed92009-11-02 02:47:51 +00001721 // Iterate over all of the instructions in a function, replacing them with
1722 // constants if we have found them to be of constant values.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001723 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001724 Instruction *Inst = &*BI++;
Chris Lattnere405ed92009-11-02 02:47:51 +00001725 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1726 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001727
Sanjoy Dasff855b62016-08-24 18:10:21 +00001728 if (tryToReplaceWithConstant(Solver, Inst)) {
1729 if (isInstructionTriviallyDead(Inst))
1730 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001731 // Hey, we just changed something!
1732 MadeChanges = true;
1733 ++NumInstRemoved;
Davide Italiano00802692016-07-12 19:54:19 +00001734 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001735 }
1736 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001737
1738 return MadeChanges;
1739}
Chris Lattnerb4394642004-12-10 08:02:06 +00001740
Sean Silva36e0d012016-08-09 00:28:15 +00001741PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001742 const DataLayout &DL = F.getParent()->getDataLayout();
1743 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1744 if (!runSCCP(F, DL, &TLI))
1745 return PreservedAnalyses::all();
Davide Italiano484b5ab2016-05-29 00:31:15 +00001746
1747 auto PA = PreservedAnalyses();
1748 PA.preserve<GlobalsAA>();
1749 return PA;
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001750}
1751
1752namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +00001753
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001754//===--------------------------------------------------------------------===//
1755//
1756/// SCCP Class - This class uses the SCCPSolver to implement a per-function
1757/// Sparse Conditional Constant Propagator.
1758///
Davide Italiano46f249b2016-05-19 15:58:02 +00001759class SCCPLegacyPass : public FunctionPass {
1760public:
Eugene Zelenko99241d72017-10-20 21:47:29 +00001761 // Pass identification, replacement for typeid
1762 static char ID;
1763
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001764 SCCPLegacyPass() : FunctionPass(ID) {
1765 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1766 }
1767
Eugene Zelenko99241d72017-10-20 21:47:29 +00001768 void getAnalysisUsage(AnalysisUsage &AU) const override {
1769 AU.addRequired<TargetLibraryInfoWrapperPass>();
1770 AU.addPreserved<GlobalsAAWrapperPass>();
1771 }
1772
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001773 // runOnFunction - Run the Sparse Conditional Constant Propagation
1774 // algorithm, and return true if the function was modified.
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001775 bool runOnFunction(Function &F) override {
1776 if (skipFunction(F))
1777 return false;
1778 const DataLayout &DL = F.getParent()->getDataLayout();
1779 const TargetLibraryInfo *TLI =
1780 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1781 return runSCCP(F, DL, TLI);
1782 }
1783};
Eugene Zelenko99241d72017-10-20 21:47:29 +00001784
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001785} // end anonymous namespace
1786
1787char SCCPLegacyPass::ID = 0;
Eugene Zelenko99241d72017-10-20 21:47:29 +00001788
Davide Italiano98f7e0e2016-05-18 15:18:25 +00001789INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1790 "Sparse Conditional Constant Propagation", false, false)
1791INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1792INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1793 "Sparse Conditional Constant Propagation", false, false)
1794
1795// createSCCPPass - This is the public interface to this file.
1796FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1797
Davide Italiano15ff2d62016-07-20 20:17:13 +00001798static void findReturnsToZap(Function &F,
Matthew Simpson22849372017-10-13 17:53:44 +00001799 SmallVector<ReturnInst *, 8> &ReturnsToZap,
1800 SCCPSolver &Solver) {
Davide Italiano15ff2d62016-07-20 20:17:13 +00001801 // We can only do this if we know that nothing else can call the function.
Matthew Simpson22849372017-10-13 17:53:44 +00001802 if (!Solver.isArgumentTrackedFunction(&F))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001803 return;
1804
1805 for (BasicBlock &BB : F)
Davide Italianoe3bdd612016-12-01 08:36:12 +00001806 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Davide Italiano15ff2d62016-07-20 20:17:13 +00001807 if (!isa<UndefValue>(RI->getOperand(0)))
1808 ReturnsToZap.push_back(RI);
1809}
1810
Davide Italianof54f2f02016-05-05 21:05:36 +00001811static bool runIPSCCP(Module &M, const DataLayout &DL,
1812 const TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001813 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001814
1815 // Loop over all functions, marking arguments to those with their addresses
1816 // taken or that are external as overdefined.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001817 for (Function &F : M) {
1818 if (F.isDeclaration())
Chris Lattner47837c52009-11-02 06:34:04 +00001819 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001820
Matthew Simpson22849372017-10-13 17:53:44 +00001821 // Determine if we can track the function's return values. If so, add the
1822 // function to the solver's set of return-tracked functions.
1823 if (canTrackReturnsInterprocedurally(&F))
Davide Italianoe7c56c52016-05-14 20:59:09 +00001824 Solver.AddTrackedFunction(&F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001825
Matthew Simpson22849372017-10-13 17:53:44 +00001826 // Determine if we can track the function's arguments. If so, add the
1827 // function to the solver's set of argument-tracked functions.
1828 if (canTrackArgumentsInterprocedurally(&F)) {
1829 Solver.AddArgumentTrackedFunction(&F);
1830 continue;
Chris Lattnercde8de52009-11-03 19:24:51 +00001831 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001832
1833 // Assume the function is called.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001834 Solver.MarkBlockExecutable(&F.front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001835
Chris Lattnerfb141812009-11-03 03:42:51 +00001836 // Assume nothing about the incoming arguments.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001837 for (Argument &AI : F.args())
Davide Italianob6ddd7a2017-03-08 01:26:37 +00001838 Solver.markOverdefined(&AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001839 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001840
Matthew Simpson22849372017-10-13 17:53:44 +00001841 // Determine if we can track any of the module's global variables. If so, add
1842 // the global variables we can track to the solver's set of tracked global
1843 // variables.
1844 for (GlobalVariable &G : M.globals()) {
1845 G.removeDeadConstantUsers();
1846 if (canTrackGlobalVariableInterprocedurally(&G))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001847 Solver.TrackValueOfGlobalVariable(&G);
Matthew Simpson22849372017-10-13 17:53:44 +00001848 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001849
Chris Lattnerb4394642004-12-10 08:02:06 +00001850 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001851 bool ResolvedUndefs = true;
1852 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001853 Solver.Solve();
1854
David Greene389fc3b2010-01-05 01:27:15 +00001855 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001856 ResolvedUndefs = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001857 for (Function &F : M)
1858 ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001859 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001860
1861 bool MadeChanges = false;
1862
1863 // Iterate over all of the instructions in the module, replacing them with
1864 // constants if we have found them to be of constant values.
Chris Lattner65938fc2008-08-23 23:36:38 +00001865 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001866
Benjamin Kramer135f7352016-06-26 12:28:59 +00001867 for (Function &F : M) {
1868 if (F.isDeclaration())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001869 continue;
1870
Bruno Cardoso Lopes993d2e62017-10-12 20:52:34 +00001871 if (Solver.isBlockExecutable(&F.front()))
Benjamin Kramer135f7352016-06-26 12:28:59 +00001872 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
Florian Hahnd0208b42017-10-30 10:07:42 +00001873 ++AI) {
Davide Italiano5df80802017-11-21 00:21:52 +00001874 if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) {
Davide Italiano6ed6d772016-07-14 01:27:29 +00001875 ++IPNumArgsElimed;
Davide Italiano5df80802017-11-21 00:21:52 +00001876 continue;
1877 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001878
Florian Hahnd0208b42017-10-30 10:07:42 +00001879 if (!AI->use_empty() && tryToReplaceWithConstantRange(Solver, &*AI))
1880 ++IPNumRangeInfoUsed;
1881 }
1882
Benjamin Kramer135f7352016-06-26 12:28:59 +00001883 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001884 if (!Solver.isBlockExecutable(&*BB)) {
David Majnemer88542a02016-01-24 06:26:47 +00001885 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001886
David Majnemer88542a02016-01-24 06:26:47 +00001887 ++NumDeadBlocks;
David Majnemere14e7bc2016-06-25 08:19:55 +00001888 NumInstRemoved +=
1889 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
David Majnemer88542a02016-01-24 06:26:47 +00001890
1891 MadeChanges = true;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001892
Benjamin Kramer135f7352016-06-26 12:28:59 +00001893 if (&*BB != &F.front())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001894 BlocksToErase.push_back(&*BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001895 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001896 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001897
Chris Lattnere405ed92009-11-02 02:47:51 +00001898 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001899 Instruction *Inst = &*BI++;
Davide Italiano7dac0272016-07-14 02:51:41 +00001900 if (Inst->getType()->isVoidTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001901 continue;
Sanjoy Dasff855b62016-08-24 18:10:21 +00001902 if (tryToReplaceWithConstant(Solver, Inst)) {
1903 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1904 Inst->eraseFromParent();
Davide Italiano296e9782016-07-13 23:20:04 +00001905 // Hey, we just changed something!
1906 MadeChanges = true;
1907 ++IPNumInstRemoved;
1908 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001909 }
1910 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001911
1912 // Now that all instructions in the function are constant folded, erase dead
1913 // blocks, because we can now use ConstantFoldTerminator to get rid of
1914 // in-edges.
1915 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1916 // If there are any PHI nodes in this successor, drop entries for BB now.
1917 BasicBlock *DeadBB = BlocksToErase[i];
Chandler Carruthcdf47882014-03-09 03:16:01 +00001918 for (Value::user_iterator UI = DeadBB->user_begin(),
1919 UE = DeadBB->user_end();
1920 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001921 // Grab the user and then increment the iterator early, as the user
1922 // will be deleted. Step past all adjacent uses from the same user.
Davide Italianoe3bdd612016-12-01 08:36:12 +00001923 auto *I = dyn_cast<Instruction>(*UI);
Dan Gohman1f522d92009-11-23 16:13:39 +00001924 do { ++UI; } while (UI != UE && *UI == I);
1925
Dan Gohmand15302a2009-11-20 20:19:14 +00001926 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001927 if (!I) continue;
1928
Davide Italianodf670a12016-12-06 02:26:50 +00001929 bool Folded = ConstantFoldTerminator(I->getParent());
Davide Italiano55b66342017-12-23 15:06:30 +00001930 if (!Folded) {
1931 // The constant folder may not have been able to fold the terminator
1932 // if this is a branch or switch on undef. Fold it manually as a
1933 // branch to the first successor.
1934#ifndef NDEBUG
1935 if (auto *BI = dyn_cast<BranchInst>(I)) {
1936 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1937 "Branch should be foldable!");
1938 } else if (auto *SI = dyn_cast<SwitchInst>(I)) {
1939 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1940 } else {
1941 llvm_unreachable("Didn't fold away reference to block!");
1942 }
1943#endif
1944
1945 // Make this an uncond branch to the first successor.
1946 TerminatorInst *TI = I->getParent()->getTerminator();
1947 BranchInst::Create(TI->getSuccessor(0), TI);
1948
1949 // Remove entries in successor phi nodes to remove edges.
1950 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1951 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1952
1953 // Remove the old terminator.
1954 TI->eraseFromParent();
1955 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001956 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001957
Chris Lattnerbae4b642004-12-10 22:29:08 +00001958 // Finally, delete the basic block.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001959 F.getBasicBlockList().erase(DeadBB);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001960 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001961 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001962 }
Chris Lattner99e12952004-12-11 02:53:57 +00001963
1964 // If we inferred constant or undef return values for a function, we replaced
1965 // all call uses with the inferred value. This means we don't need to bother
1966 // actually returning anything from the function. Replace all return
1967 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001968 //
1969 // Do this in two stages: first identify the functions we should process, then
1970 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001971 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001972 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001973 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001974 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00001975
Devang Patela7a20752008-03-11 05:46:42 +00001976 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Benjamin Kramer135f7352016-06-26 12:28:59 +00001977 for (const auto &I : RV) {
1978 Function *F = I.first;
1979 if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
Chris Lattnerfb141812009-11-03 03:42:51 +00001980 continue;
Matthew Simpson22849372017-10-13 17:53:44 +00001981 findReturnsToZap(*F, ReturnsToZap, Solver);
Davide Italiano15ff2d62016-07-20 20:17:13 +00001982 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001983
Davide Italiano15ff2d62016-07-20 20:17:13 +00001984 for (const auto &F : Solver.getMRVFunctionsTracked()) {
1985 assert(F->getReturnType()->isStructTy() &&
1986 "The return type should be a struct");
1987 StructType *STy = cast<StructType>(F->getReturnType());
1988 if (Solver.isStructLatticeConstant(F, STy))
Matthew Simpson22849372017-10-13 17:53:44 +00001989 findReturnsToZap(*F, ReturnsToZap, Solver);
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001990 }
1991
1992 // Zap all returns which we've identified as zap to change.
1993 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1994 Function *F = ReturnsToZap[i]->getParent()->getParent();
1995 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00001996 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001997
Chad Rosierbb2a6da2012-03-28 00:35:33 +00001998 // If we inferred constant or undef values for globals variables, we can
1999 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00002000 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2001 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00002002 E = TG.end(); I != E; ++I) {
2003 GlobalVariable *GV = I->first;
2004 assert(!I->second.isOverdefined() &&
2005 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00002006 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00002007 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002008 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00002009 SI->eraseFromParent();
2010 }
2011 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00002012 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00002013 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002014
Chris Lattnerb4394642004-12-10 08:02:06 +00002015 return MadeChanges;
2016}
Davide Italianof54f2f02016-05-05 21:05:36 +00002017
Sean Silvafd03ac62016-08-09 00:28:38 +00002018PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
Davide Italianof54f2f02016-05-05 21:05:36 +00002019 const DataLayout &DL = M.getDataLayout();
2020 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
2021 if (!runIPSCCP(M, DL, &TLI))
2022 return PreservedAnalyses::all();
2023 return PreservedAnalyses::none();
2024}
2025
2026namespace {
Eugene Zelenko99241d72017-10-20 21:47:29 +00002027
Davide Italianof54f2f02016-05-05 21:05:36 +00002028//===--------------------------------------------------------------------===//
2029//
2030/// IPSCCP Class - This class implements interprocedural Sparse Conditional
2031/// Constant Propagation.
2032///
Davide Italiano46f249b2016-05-19 15:58:02 +00002033class IPSCCPLegacyPass : public ModulePass {
2034public:
Davide Italianof54f2f02016-05-05 21:05:36 +00002035 static char ID;
2036
2037 IPSCCPLegacyPass() : ModulePass(ID) {
2038 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
2039 }
2040
2041 bool runOnModule(Module &M) override {
2042 if (skipModule(M))
2043 return false;
2044 const DataLayout &DL = M.getDataLayout();
2045 const TargetLibraryInfo *TLI =
2046 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2047 return runIPSCCP(M, DL, TLI);
2048 }
2049
2050 void getAnalysisUsage(AnalysisUsage &AU) const override {
2051 AU.addRequired<TargetLibraryInfoWrapperPass>();
2052 }
2053};
Eugene Zelenko99241d72017-10-20 21:47:29 +00002054
Davide Italianof54f2f02016-05-05 21:05:36 +00002055} // end anonymous namespace
2056
2057char IPSCCPLegacyPass::ID = 0;
Eugene Zelenko99241d72017-10-20 21:47:29 +00002058
Davide Italianof54f2f02016-05-05 21:05:36 +00002059INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
2060 "Interprocedural Sparse Conditional Constant Propagation",
2061 false, false)
2062INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2063INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
2064 "Interprocedural Sparse Conditional Constant Propagation",
2065 false, false)
2066
2067// createIPSCCPPass - This is the public interface to this file.
2068ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }