blob: 0582052936325d908a8d40989e8efa14dedb1dc0 [file] [log] [blame]
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
Chris Lattner741c94c2009-11-11 00:22:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Anna Thomase27b39a2017-03-22 19:27:12 +000022#include "llvm/IR/AssemblyAnnotationWriter.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000024#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +000030#include "llvm/IR/Intrinsics.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000031#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000033#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000034#include "llvm/Support/Debug.h"
Anna Thomase27b39a2017-03-22 19:27:12 +000035#include "llvm/Support/FormattedStream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000037#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000038#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000039using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000040using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000041
Chandler Carruthf1221bd2014-04-22 02:48:03 +000042#define DEBUG_TYPE "lazy-value-info"
43
Daniel Berlin9c92a462017-02-08 15:22:52 +000044// This is the number of worklist items we will process to try to discover an
45// answer for a given value.
46static const unsigned MaxProcessedPerValue = 500;
47
Sean Silva687019f2016-06-13 22:01:25 +000048char LazyValueInfoWrapperPass::ID = 0;
49INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000050 "Lazy Value Information Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000051INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000052INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Sean Silva687019f2016-06-13 22:01:25 +000053INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000054 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000055
56namespace llvm {
Sean Silva687019f2016-06-13 22:01:25 +000057 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000058}
59
Chandler Carruthdab4eae2016-11-23 17:53:26 +000060AnalysisKey LazyValueAnalysis::Key;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000061
62//===----------------------------------------------------------------------===//
63// LVILatticeVal
64//===----------------------------------------------------------------------===//
65
Sanjay Patel2a385e22015-01-09 16:47:20 +000066/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000067///
68/// FIXME: This is basically just for bringup, this can be made a lot more rich
69/// in the future.
70///
71namespace {
72class LVILatticeVal {
73 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000074 /// This Value has no known value yet. As a result, this implies the
75 /// producing instruction is dead. Caution: We use this as the starting
76 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000077 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000078 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000079
Philip Reames02bb6a62016-12-07 04:48:50 +000080 /// This Value has a specific constant value. (For constant integers,
81 /// constantrange is used instead. Integer typed constantexprs can appear
82 /// as constant.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000083 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000084
Philip Reames02bb6a62016-12-07 04:48:50 +000085 /// This Value is known to not have the specified value. (For constant
86 /// integers, constantrange is used instead. As above, integer typed
87 /// constantexprs can appear here.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000088 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000089
Philip Reames3bb28322016-04-25 18:48:43 +000090 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000091 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000092
Philip Reames3bb28322016-04-25 18:48:43 +000093 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000094 overdefined
95 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000096
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000097 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000098 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000099 LatticeValueTy Tag;
100 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +0000101 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000102
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000103public:
Craig Topper9f008862014-04-15 04:59:12 +0000104 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000105
Chris Lattner19019ea2009-11-11 22:48:44 +0000106 static LVILatticeVal get(Constant *C) {
107 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000108 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000109 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000110 return Res;
111 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000112 static LVILatticeVal getNot(Constant *C) {
113 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000114 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000115 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000116 return Res;
117 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000118 static LVILatticeVal getRange(ConstantRange CR) {
119 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000120 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000121 return Res;
122 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000123 static LVILatticeVal getOverdefined() {
124 LVILatticeVal Res;
125 Res.markOverdefined();
126 return Res;
127 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000128
Owen Anderson0f306a42010-08-05 22:59:19 +0000129 bool isUndefined() const { return Tag == undefined; }
130 bool isConstant() const { return Tag == constant; }
131 bool isNotConstant() const { return Tag == notconstant; }
132 bool isConstantRange() const { return Tag == constantrange; }
133 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000134
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000135 Constant *getConstant() const {
136 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000137 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000138 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000139
Chris Lattner565ee2f2009-11-12 04:36:58 +0000140 Constant *getNotConstant() const {
141 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000142 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000143 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000144
Owen Anderson0f306a42010-08-05 22:59:19 +0000145 ConstantRange getConstantRange() const {
146 assert(isConstantRange() &&
147 "Cannot get the constant-range of a non-constant-range!");
148 return Range;
149 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000150
Philip Reames1baaef12016-12-06 03:01:08 +0000151private:
Philip Reames71a49672016-12-07 01:03:56 +0000152 void markOverdefined() {
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000153 if (isOverdefined())
Philip Reames71a49672016-12-07 01:03:56 +0000154 return;
Owen Andersonc3a14132010-08-05 22:10:46 +0000155 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000156 }
157
Philip Reames71a49672016-12-07 01:03:56 +0000158 void markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000159 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000160 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
161 markConstantRange(ConstantRange(CI->getValue()));
162 return;
163 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000164 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000165 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000166
167 assert((!isConstant() || getConstant() == V) &&
168 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000169 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000170 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000171 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000172 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000173
Philip Reames71a49672016-12-07 01:03:56 +0000174 void markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000175 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000176 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
177 markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
178 return;
179 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000180 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000181 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000182
183 assert((!isConstant() || getConstant() != V) &&
184 "Marking constant !constant with same value");
185 assert((!isNotConstant() || getNotConstant() == V) &&
186 "Marking !constant with different value");
187 assert(isUndefined() || isConstant());
188 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000189 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000190 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000191
Philip Reames71a49672016-12-07 01:03:56 +0000192 void markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000193 if (isConstantRange()) {
194 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000195 markOverdefined();
196 else {
Philip Reames71a49672016-12-07 01:03:56 +0000197 Range = std::move(NewR);
198 }
199 return;
Owen Anderson0f306a42010-08-05 22:59:19 +0000200 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000201
Owen Anderson0f306a42010-08-05 22:59:19 +0000202 assert(isUndefined());
203 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000204 markOverdefined();
205 else {
206 Tag = constantrange;
207 Range = std::move(NewR);
208 }
Owen Anderson0f306a42010-08-05 22:59:19 +0000209 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000210
Philip Reamesb2949622016-12-06 02:54:16 +0000211public:
212
Sanjay Patel2a385e22015-01-09 16:47:20 +0000213 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000214 /// one and returning true if anything changed.
Philip Reamesb47a7192016-12-07 00:54:21 +0000215 void mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
216 if (RHS.isUndefined() || isOverdefined())
217 return;
218 if (RHS.isOverdefined()) {
219 markOverdefined();
220 return;
221 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000222
Nick Lewycky11678bd2010-12-15 18:57:18 +0000223 if (isUndefined()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000224 *this = RHS;
225 return;
Chris Lattner22db4b52009-11-12 04:57:13 +0000226 }
227
Nick Lewycky11678bd2010-12-15 18:57:18 +0000228 if (isConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000229 if (RHS.isConstant() && Val == RHS.Val)
230 return;
231 markOverdefined();
232 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000233 }
234
235 if (isNotConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000236 if (RHS.isNotConstant() && Val == RHS.Val)
237 return;
238 markOverdefined();
239 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000240 }
241
242 assert(isConstantRange() && "New LVILattice type?");
Philip Reames02bb6a62016-12-07 04:48:50 +0000243 if (!RHS.isConstantRange()) {
244 // We can get here if we've encountered a constantexpr of integer type
245 // and merge it with a constantrange.
246 markOverdefined();
247 return;
248 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000249 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
250 if (NewR.isFullSet())
Philip Reamesb47a7192016-12-07 00:54:21 +0000251 markOverdefined();
252 else
253 markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000254 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000255};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000256
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000257} // end anonymous namespace.
258
Chris Lattner19019ea2009-11-11 22:48:44 +0000259namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000260raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
261 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000262raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
263 if (Val.isUndefined())
264 return OS << "undefined";
265 if (Val.isOverdefined())
266 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000267
268 if (Val.isNotConstant())
269 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000270 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000271 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
272 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000273 return OS << "constant<" << *Val.getConstant() << '>';
274}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000275}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000276
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000277/// Returns true if this lattice value represents at most one possible value.
278/// This is as precise as any lattice value can get while still representing
279/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000280static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000281 if (Val.isConstantRange() &&
282 Val.getConstantRange().isSingleElement())
283 // Integer constants are single element ranges
284 return true;
285 if (Val.isConstant())
286 // Non integer constants
287 return true;
288 return false;
289}
290
291/// Combine two sets of facts about the same value into a single set of
292/// facts. Note that this method is not suitable for merging facts along
293/// different paths in a CFG; that's what the mergeIn function is for. This
294/// is for merging facts gathered about the same value at the same location
295/// through two independent means.
296/// Notes:
297/// * This method does not promise to return the most precise possible lattice
298/// value implied by A and B. It is allowed to return any lattice element
299/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000300/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000301/// * Due to unreachable code, the intersection of two lattice values could be
302/// contradictory. If this happens, we return some valid lattice value so as
303/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
304/// we do not make this guarantee. TODO: This would be a useful enhancement.
305static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
306 // Undefined is the strongest state. It means the value is known to be along
307 // an unreachable path.
308 if (A.isUndefined())
309 return A;
310 if (B.isUndefined())
311 return B;
312
313 // If we gave up for one, but got a useable fact from the other, use it.
314 if (A.isOverdefined())
315 return B;
316 if (B.isOverdefined())
317 return A;
318
319 // Can't get any more precise than constants.
320 if (hasSingleValue(A))
321 return A;
322 if (hasSingleValue(B))
323 return B;
324
325 // Could be either constant range or not constant here.
326 if (!A.isConstantRange() || !B.isConstantRange()) {
327 // TODO: Arbitrary choice, could be improved
328 return A;
329 }
330
331 // Intersect two constant ranges
332 ConstantRange Range =
333 A.getConstantRange().intersectWith(B.getConstantRange());
334 // Note: An empty range is implicitly converted to overdefined internally.
335 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000336 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000337 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000338}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000339
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000340//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000341// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000342//===----------------------------------------------------------------------===//
343
Chris Lattneraf025d32009-11-15 19:59:49 +0000344namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000345 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000346 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000347 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000348 // Needs to access getValPtr(), which is protected.
349 friend struct DenseMapInfo<LVIValueHandle>;
350
Owen Anderson118ac802011-01-05 21:15:29 +0000351 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000352
Owen Anderson118ac802011-01-05 21:15:29 +0000353 LVIValueHandle(Value *V, LazyValueInfoCache *P)
354 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000355
356 void deleted() override;
357 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000358 deleted();
359 }
360 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000361} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000362
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000363namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000364 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000365 /// maintains information about queries across the clients' queries.
366 class LazyValueInfoCache {
Anna Thomase27b39a2017-03-22 19:27:12 +0000367 friend class LazyValueInfoAnnotatedWriter;
Sanjay Patel2a385e22015-01-09 16:47:20 +0000368 /// This is all of the cached block information for exactly one Value*.
369 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000370 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000371 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
372 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000373 struct ValueCacheEntryTy {
374 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
375 LVIValueHandle Handle;
Chandler Carruth6acdca72017-01-24 12:55:57 +0000376 SmallDenseMap<PoisoningVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
Justin Lebar58b377e2016-07-27 22:33:36 +0000377 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000378
Sanjay Patel2a385e22015-01-09 16:47:20 +0000379 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000380 /// over-defined at the end of that block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000381 typedef DenseMap<PoisoningVH<BasicBlock>, SmallPtrSet<Value *, 4>>
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000382 OverDefinedCacheTy;
Sanjay Patel2a385e22015-01-09 16:47:20 +0000383 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000384 /// don't spend time removing unused blocks from our caches.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000385 DenseSet<PoisoningVH<BasicBlock> > SeenBlocks;
Benjamin Kramer36647082011-12-03 15:16:45 +0000386
Anna Thomase27b39a2017-03-22 19:27:12 +0000387 protected:
388 /// This is all of the cached information for all values,
389 /// mapped from Value* to key information.
390 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
391 OverDefinedCacheTy OverDefinedCache;
392
393
Philip Reames9db79482016-09-12 22:38:44 +0000394 public:
Hans Wennborg45172ac2014-11-25 17:23:05 +0000395 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
396 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000397
398 // Insert over-defined values into their own cache to reduce memory
399 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000400 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000401 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000402 else {
403 auto It = ValueCache.find_as(Val);
404 if (It == ValueCache.end()) {
405 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
406 It = ValueCache.find_as(Val);
407 assert(It != ValueCache.end() && "Val was just added to the map!");
408 }
409 It->second->BlockVals[BB] = Result;
410 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000411 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000412
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000413 bool isOverdefined(Value *V, BasicBlock *BB) const {
414 auto ODI = OverDefinedCache.find(BB);
415
416 if (ODI == OverDefinedCache.end())
417 return false;
418
419 return ODI->second.count(V);
420 }
421
Philip Reames9db79482016-09-12 22:38:44 +0000422 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000423 if (isOverdefined(V, BB))
424 return true;
425
Justin Lebar58b377e2016-07-27 22:33:36 +0000426 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000427 if (I == ValueCache.end())
428 return false;
429
Justin Lebar58b377e2016-07-27 22:33:36 +0000430 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000431 }
432
Philip Reames9db79482016-09-12 22:38:44 +0000433 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000434 if (isOverdefined(V, BB))
435 return LVILatticeVal::getOverdefined();
436
Justin Lebar58b377e2016-07-27 22:33:36 +0000437 auto I = ValueCache.find_as(V);
438 if (I == ValueCache.end())
439 return LVILatticeVal();
440 auto BBI = I->second->BlockVals.find(BB);
441 if (BBI == I->second->BlockVals.end())
442 return LVILatticeVal();
443 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000444 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000445
Anna Thomase27b39a2017-03-22 19:27:12 +0000446 void printCache(Function &F, raw_ostream &OS);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000447 /// clear - Empty the cache.
448 void clear() {
449 SeenBlocks.clear();
450 ValueCache.clear();
451 OverDefinedCache.clear();
452 }
453
Philip Reamesb627aec2016-09-12 22:03:36 +0000454 /// Inform the cache that a given value has been deleted.
455 void eraseValue(Value *V);
456
457 /// This is part of the update interface to inform the cache
458 /// that a block has been deleted.
459 void eraseBlock(BasicBlock *BB);
460
Philip Reames9db79482016-09-12 22:38:44 +0000461 /// Updates the cache to remove any influence an overdefined value in
462 /// OldSucc might have (unless also overdefined in NewSucc). This just
463 /// flushes elements from the cache and does not add any.
464 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
465
Philip Reames92e5e1b2016-09-12 21:46:58 +0000466 friend struct LVIValueHandle;
467 };
Philip Reamesb627aec2016-09-12 22:03:36 +0000468}
Philip Reames92e5e1b2016-09-12 21:46:58 +0000469
Anna Thomase27b39a2017-03-22 19:27:12 +0000470
471namespace {
472
473 /// An assembly annotator class to print LazyValueCache information in
474 /// comments.
475 class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
476 const LazyValueInfoCache* LVICache;
477
478 public:
479 LazyValueInfoAnnotatedWriter(const LazyValueInfoCache *L) : LVICache(L) {}
480
481 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
482 formatted_raw_ostream &OS) {
483 auto ODI = LVICache->OverDefinedCache.find(const_cast<BasicBlock*>(BB));
484 if (ODI == LVICache->OverDefinedCache.end())
485 return;
486 OS << "; OverDefined values for block are: \n";
487 for (auto *V : ODI->second)
488 OS << ";" << *V << "\n";
489 }
490
491 virtual void emitInstructionAnnot(const Instruction *I,
492 formatted_raw_ostream &OS) {
493
494 auto VI = LVICache->ValueCache.find_as(const_cast<Instruction *>(I));
495 if (VI == LVICache->ValueCache.end())
496 return;
497 OS << "; CachedLatticeValues for: '" << *VI->first << "'\n";
498 for (auto &BV : VI->second->BlockVals) {
499 OS << "; at beginning of BasicBlock: '";
500 BV.first->printAsOperand(OS, false);
501 OS << "' LatticeVal: '" << BV.second << "' \n";
502 }
503 }
504};
505}
506
507void LazyValueInfoCache::printCache(Function &F, raw_ostream &OS) {
508 LazyValueInfoAnnotatedWriter Writer(this);
509 F.print(OS, &Writer);
510
511}
512
Philip Reamesb627aec2016-09-12 22:03:36 +0000513void LazyValueInfoCache::eraseValue(Value *V) {
Chandler Carruth41421df2017-01-26 08:31:54 +0000514 for (auto I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E;) {
515 // Copy and increment the iterator immediately so we can erase behind
516 // ourselves.
517 auto Iter = I++;
518 SmallPtrSetImpl<Value *> &ValueSet = Iter->second;
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000519 ValueSet.erase(V);
Philip Reamesb627aec2016-09-12 22:03:36 +0000520 if (ValueSet.empty())
Chandler Carruth41421df2017-01-26 08:31:54 +0000521 OverDefinedCache.erase(Iter);
Philip Reamesb627aec2016-09-12 22:03:36 +0000522 }
Philip Reamesb627aec2016-09-12 22:03:36 +0000523
524 ValueCache.erase(V);
525}
526
527void LVIValueHandle::deleted() {
528 // This erasure deallocates *this, so it MUST happen after we're done
529 // using any and all members of *this.
530 Parent->eraseValue(*this);
531}
532
533void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
534 // Shortcut if we have never seen this block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000535 DenseSet<PoisoningVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
Philip Reamesb627aec2016-09-12 22:03:36 +0000536 if (I == SeenBlocks.end())
537 return;
538 SeenBlocks.erase(I);
539
540 auto ODI = OverDefinedCache.find(BB);
541 if (ODI != OverDefinedCache.end())
542 OverDefinedCache.erase(ODI);
543
544 for (auto &I : ValueCache)
545 I.second->BlockVals.erase(BB);
546}
547
Philip Reames9db79482016-09-12 22:38:44 +0000548void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
549 BasicBlock *NewSucc) {
550 // When an edge in the graph has been threaded, values that we could not
551 // determine a value for before (i.e. were marked overdefined) may be
552 // possible to solve now. We do NOT try to proactively update these values.
553 // Instead, we clear their entries from the cache, and allow lazy updating to
554 // recompute them when needed.
555
556 // The updating process is fairly simple: we need to drop cached info
557 // for all values that were marked overdefined in OldSucc, and for those same
558 // values in any successor of OldSucc (except NewSucc) in which they were
559 // also marked overdefined.
560 std::vector<BasicBlock*> worklist;
561 worklist.push_back(OldSucc);
562
563 auto I = OverDefinedCache.find(OldSucc);
564 if (I == OverDefinedCache.end())
565 return; // Nothing to process here.
566 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
567
568 // Use a worklist to perform a depth-first search of OldSucc's successors.
569 // NOTE: We do not need a visited list since any blocks we have already
570 // visited will have had their overdefined markers cleared already, and we
571 // thus won't loop to their successors.
572 while (!worklist.empty()) {
573 BasicBlock *ToUpdate = worklist.back();
574 worklist.pop_back();
575
576 // Skip blocks only accessible through NewSucc.
577 if (ToUpdate == NewSucc) continue;
578
Philip Reames1e48efc2016-12-30 17:56:47 +0000579 // If a value was marked overdefined in OldSucc, and is here too...
580 auto OI = OverDefinedCache.find(ToUpdate);
581 if (OI == OverDefinedCache.end())
582 continue;
583 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
584
Philip Reames9db79482016-09-12 22:38:44 +0000585 bool changed = false;
586 for (Value *V : ValsToClear) {
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000587 if (!ValueSet.erase(V))
Philip Reames9db79482016-09-12 22:38:44 +0000588 continue;
589
Philip Reames9db79482016-09-12 22:38:44 +0000590 // If we removed anything, then we potentially need to update
591 // blocks successors too.
592 changed = true;
Philip Reames1e48efc2016-12-30 17:56:47 +0000593
594 if (ValueSet.empty()) {
595 OverDefinedCache.erase(OI);
596 break;
597 }
Philip Reames9db79482016-09-12 22:38:44 +0000598 }
599
600 if (!changed) continue;
601
602 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
603 }
604}
605
Philip Reamesb627aec2016-09-12 22:03:36 +0000606namespace {
Philip Reames92e5e1b2016-09-12 21:46:58 +0000607 // The actual implementation of the lazy analysis and update. Note that the
608 // inheritance from LazyValueInfoCache is intended to be temporary while
609 // splitting the code and then transitioning to a has-a relationship.
Philip Reames9db79482016-09-12 22:38:44 +0000610 class LazyValueInfoImpl {
611
612 /// Cached results from previous queries
613 LazyValueInfoCache TheCache;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000614
615 /// This stack holds the state of the value solver during a query.
616 /// It basically emulates the callstack of the naive
617 /// recursive value lookup process.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000618 SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000619
620 /// Keeps track of which block-value pairs are in BlockValueStack.
621 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
622
623 /// Push BV onto BlockValueStack unless it's already in there.
624 /// Returns true on success.
625 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
626 if (!BlockValueSet.insert(BV).second)
627 return false; // It's already in the stack.
628
629 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
630 << "\n");
Daniel Berlin9c92a462017-02-08 15:22:52 +0000631 BlockValueStack.push_back(BV);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000632 return true;
633 }
634
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000635 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
Philip Reames92e5e1b2016-09-12 21:46:58 +0000636 const DataLayout &DL; ///< A mandatory DataLayout
637 DominatorTree *DT; ///< An optional DT pointer.
638
639 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
640 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
641 LVILatticeVal &Result, Instruction *CxtI = nullptr);
642 bool hasBlockValue(Value *Val, BasicBlock *BB);
643
644 // These methods process one work item and may add more. A false value
645 // returned means that the work item was not completely processed and must
646 // be revisited after going through the new items.
647 bool solveBlockValue(Value *Val, BasicBlock *BB);
Philip Reames05c435e2016-12-06 03:22:03 +0000648 bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000649 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
650 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
651 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
652 BasicBlock *BB);
653 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
654 BasicBlock *BB);
655 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
656 BasicBlock *BB);
657 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
658 LVILatticeVal &BBLV,
659 Instruction *BBI);
660
661 void solve();
662
663 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000664 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000665 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000666 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
667 Instruction *CxtI = nullptr);
668
Sanjay Patel2a385e22015-01-09 16:47:20 +0000669 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000670 /// value for the specified Value* at the specified instruction (generally
671 /// from an assume intrinsic).
672 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000673
Sanjay Patel2a385e22015-01-09 16:47:20 +0000674 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000675 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000676 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
677 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000678
Philip Reames9db79482016-09-12 22:38:44 +0000679 /// Complete flush all previously computed values
680 void clear() {
681 TheCache.clear();
682 }
683
Anna Thomase27b39a2017-03-22 19:27:12 +0000684 /// Printing the LazyValueInfoCache.
685 void printCache(Function &F, raw_ostream &OS) {
686 TheCache.printCache(F, OS);
687 }
688
Philip Reames9db79482016-09-12 22:38:44 +0000689 /// This is part of the update interface to inform the cache
690 /// that a block has been deleted.
691 void eraseBlock(BasicBlock *BB) {
692 TheCache.eraseBlock(BB);
693 }
694
Sanjay Patel2a385e22015-01-09 16:47:20 +0000695 /// This is the update interface to inform the cache that an edge from
696 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000697 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000698
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000699 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
700 DominatorTree *DT = nullptr)
701 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000702 };
703} // end anonymous namespace
704
Philip Reames92e5e1b2016-09-12 21:46:58 +0000705void LazyValueInfoImpl::solve() {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000706 SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
707 BlockValueStack.begin(), BlockValueStack.end());
708
709 unsigned processedCount = 0;
Owen Anderson6f060af2011-01-05 23:26:22 +0000710 while (!BlockValueStack.empty()) {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000711 processedCount++;
712 // Abort if we have to process too many values to get a result for this one.
713 // Because of the design of the overdefined cache currently being per-block
714 // to avoid naming-related issues (IE it wants to try to give different
715 // results for the same name in different blocks), overdefined results don't
716 // get cached globally, which in turn means we will often try to rediscover
717 // the same overdefined result again and again. Once something like
718 // PredicateInfo is used in LVI or CVP, we should be able to make the
719 // overdefined cache global, and remove this throttle.
720 if (processedCount > MaxProcessedPerValue) {
721 DEBUG(dbgs() << "Giving up on stack because we are getting too deep\n");
722 // Fill in the original values
723 while (!StartingStack.empty()) {
724 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
725 TheCache.insertResult(e.second, e.first,
726 LVILatticeVal::getOverdefined());
727 StartingStack.pop_back();
728 }
729 BlockValueSet.clear();
730 BlockValueStack.clear();
731 return;
732 }
Vitaly Buka9987d982017-02-09 09:28:05 +0000733 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000734 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
735
Nuno Lopese6e04902012-06-28 01:16:18 +0000736 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000737 // The work item was completely processed.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000738 assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
Philip Reames9db79482016-09-12 22:38:44 +0000739 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000740 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000741
Philip Reames44456b82016-02-02 03:15:40 +0000742 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000743 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000744
Daniel Berlin9c92a462017-02-08 15:22:52 +0000745 BlockValueStack.pop_back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000746 BlockValueSet.erase(e);
747 } else {
748 // More work needs to be done before revisiting.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000749 assert(BlockValueStack.back() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000750 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000751 }
752}
753
Philip Reames92e5e1b2016-09-12 21:46:58 +0000754bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000755 // If already a constant, there is nothing to compute.
756 if (isa<Constant>(Val))
757 return true;
758
Philip Reames9db79482016-09-12 22:38:44 +0000759 return TheCache.hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000760}
761
Philip Reames92e5e1b2016-09-12 21:46:58 +0000762LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000763 // If already a constant, there is nothing to compute.
764 if (Constant *VC = dyn_cast<Constant>(Val))
765 return LVILatticeVal::get(VC);
766
Philip Reames9db79482016-09-12 22:38:44 +0000767 return TheCache.getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000768}
769
Philip Reameseb3e9da2015-10-29 03:57:17 +0000770static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
771 switch (BBI->getOpcode()) {
772 default: break;
773 case Instruction::Load:
774 case Instruction::Call:
775 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000776 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000777 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000778 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000779 }
780 break;
781 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000782 // Nothing known - will be intersected with other facts
783 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000784}
785
Philip Reames92e5e1b2016-09-12 21:46:58 +0000786bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000787 if (isa<Constant>(Val))
788 return true;
789
Philip Reames9db79482016-09-12 22:38:44 +0000790 if (TheCache.hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000791 // If we have a cached value, use that.
792 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000793 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000794
Hans Wennborg45172ac2014-11-25 17:23:05 +0000795 // Since we're reusing a cached value, we don't need to update the
796 // OverDefinedCache. The cache will have been properly updated whenever the
797 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000798 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000799 }
800
Hans Wennborg45172ac2014-11-25 17:23:05 +0000801 // Hold off inserting this value into the Cache in case we have to return
802 // false and come back later.
803 LVILatticeVal Res;
Philip Reames05c435e2016-12-06 03:22:03 +0000804 if (!solveBlockValueImpl(Res, Val, BB))
805 // Work pushed, will revisit
806 return false;
807
808 TheCache.insertResult(Val, BB, Res);
809 return true;
810}
811
812bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
813 Value *Val, BasicBlock *BB) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000814
Chris Lattneraf025d32009-11-15 19:59:49 +0000815 Instruction *BBI = dyn_cast<Instruction>(Val);
Philip Reames05c435e2016-12-06 03:22:03 +0000816 if (!BBI || BBI->getParent() != BB)
817 return solveBlockValueNonLocal(Res, Val, BB);
Chris Lattner2c708562009-11-15 20:00:52 +0000818
Philip Reames05c435e2016-12-06 03:22:03 +0000819 if (PHINode *PN = dyn_cast<PHINode>(BBI))
820 return solveBlockValuePHINode(Res, PN, BB);
Owen Anderson80d19f02010-08-18 21:11:37 +0000821
Philip Reames05c435e2016-12-06 03:22:03 +0000822 if (auto *SI = dyn_cast<SelectInst>(BBI))
823 return solveBlockValueSelect(Res, SI, BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000824
Philip Reames2ab964e2016-04-27 01:02:25 +0000825 // If this value is a nonnull pointer, record it's range and bailout. Note
826 // that for all other pointer typed values, we terminate the search at the
827 // definition. We could easily extend this to look through geps, bitcasts,
828 // and the like to prove non-nullness, but it's not clear that's worth it
829 // compile time wise. The context-insensative value walk done inside
830 // isKnownNonNull gets most of the profitable cases at much less expense.
831 // This does mean that we have a sensativity to where the defining
832 // instruction is placed, even if it could legally be hoisted much higher.
833 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000834 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
835 if (PT && isKnownNonNull(BBI)) {
836 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000837 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000838 }
Davide Italianobd543d02016-05-25 22:29:34 +0000839 if (BBI->getType()->isIntegerTy()) {
Philip Reames05c435e2016-12-06 03:22:03 +0000840 if (isa<CastInst>(BBI))
841 return solveBlockValueCast(Res, BBI, BB);
842
Philip Reames2ab964e2016-04-27 01:02:25 +0000843 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
Philip Reames05c435e2016-12-06 03:22:03 +0000844 if (BO && isa<ConstantInt>(BO->getOperand(1)))
845 return solveBlockValueBinaryOp(Res, BBI, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000846 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000847
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000848 DEBUG(dbgs() << " compute BB '" << BB->getName()
849 << "' - unknown inst def found.\n");
850 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000851 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000852}
853
854static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
855 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
856 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000857 GetUnderlyingObject(L->getPointerOperand(),
858 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000859 }
860 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
861 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000862 GetUnderlyingObject(S->getPointerOperand(),
863 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000864 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000865 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
866 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000867
868 // FIXME: check whether it has a valuerange that excludes zero?
869 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
870 if (!Len || Len->isZero()) return false;
871
Eli Friedman7a5fc692011-05-31 20:40:16 +0000872 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000873 if (GetUnderlyingObject(MI->getRawDest(),
874 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000875 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000876 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000877 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000878 if (GetUnderlyingObject(MTI->getRawSource(),
879 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000880 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000881 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000882 return false;
883}
884
Philip Reames3f83dbe2016-04-27 00:30:55 +0000885/// Return true if the allocation associated with Val is ever dereferenced
886/// within the given basic block. This establishes the fact Val is not null,
887/// but does not imply that the memory at Val is dereferenceable. (Val may
888/// point off the end of the dereferenceable part of the object.)
889static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
890 assert(Val->getType()->isPointerTy());
891
892 const DataLayout &DL = BB->getModule()->getDataLayout();
893 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
894 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
895 // inside InstructionDereferencesPointer either.
896 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
897 for (Instruction &I : *BB)
898 if (InstructionDereferencesPointer(&I, UnderlyingVal))
899 return true;
900 return false;
901}
902
Philip Reames92e5e1b2016-09-12 21:46:58 +0000903bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000904 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000905 LVILatticeVal Result; // Start Undefined.
906
Nick Lewycky55a700b2010-12-18 01:00:40 +0000907 // If this is the entry block, we must be asking about an argument. The
908 // value is overdefined.
909 if (BB == &BB->getParent()->getEntryBlock()) {
910 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000911 // Bofore giving up, see if we can prove the pointer non-null local to
912 // this particular block.
913 if (Val->getType()->isPointerTy() &&
914 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000915 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000916 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
917 } else {
Philip Reames1baaef12016-12-06 03:01:08 +0000918 Result = LVILatticeVal::getOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000919 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000920 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000921 return true;
922 }
923
924 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000925 // result. If we encounter an unexplored predecessor, we eagerly explore it
926 // in a depth first manner. In practice, this has the effect of discovering
927 // paths we can't analyze eagerly without spending compile times analyzing
928 // other paths. This heuristic benefits from the fact that predecessors are
929 // frequently arranged such that dominating ones come first and we quickly
930 // find a path to function entry. TODO: We should consider explicitly
931 // canonicalizing to make this true rather than relying on this happy
932 // accident.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000933 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000934 LVILatticeVal EdgeResult;
Philip Reamesc80bd042017-02-07 00:25:24 +0000935 if (!getEdgeValue(Val, *PI, BB, EdgeResult))
936 // Explore that input, then return here
937 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000938
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000940
941 // If we hit overdefined, exit early. The BlockVals entry is already set
942 // to overdefined.
943 if (Result.isOverdefined()) {
944 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000945 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000946 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000947 // this particular block.
948 if (Val->getType()->isPointerTy() &&
949 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000950 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000951 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
952 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000953
Owen Anderson64c2c572010-12-20 18:18:16 +0000954 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000955 return true;
956 }
957 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000958
959 // Return the merged value, which is more precise than 'overdefined'.
960 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000961 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000962 return true;
963}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000964
Philip Reames92e5e1b2016-09-12 21:46:58 +0000965bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000966 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000967 LVILatticeVal Result; // Start Undefined.
968
969 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000970 // result. See the comment about the chosen traversal order in
971 // solveBlockValueNonLocal; the same reasoning applies here.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000972 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
973 BasicBlock *PhiBB = PN->getIncomingBlock(i);
974 Value *PhiVal = PN->getIncomingValue(i);
975 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000976 // Note that we can provide PN as the context value to getEdgeValue, even
977 // though the results will be cached, because PN is the value being used as
978 // the cache key in the caller.
Philip Reamesc80bd042017-02-07 00:25:24 +0000979 if (!getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN))
980 // Explore that input, then return here
981 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000982
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000983 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000984
985 // If we hit overdefined, exit early. The BlockVals entry is already set
986 // to overdefined.
987 if (Result.isOverdefined()) {
988 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000989 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000990
Owen Anderson64c2c572010-12-20 18:18:16 +0000991 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000992 return true;
993 }
994 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000995
996 // Return the merged value, which is more precise than 'overdefined'.
997 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000998 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000999 return true;
1000}
1001
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001002static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
1003 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +00001004
Philip Reamesd1f829d2016-02-02 21:57:37 +00001005// If we can determine a constraint on the value given conditions assumed by
1006// the program, intersect those constraints with BBLV
Philip Reames92e5e1b2016-09-12 21:46:58 +00001007void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001008 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001009 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
1010 if (!BBI)
1011 return;
1012
Hal Finkel8a9a7832017-01-11 13:24:24 +00001013 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001014 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +00001015 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001016 auto *I = cast<CallInst>(AssumeVH);
1017 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +00001018 continue;
1019
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001020 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +00001021 }
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001022
1023 // If guards are not used in the module, don't spend time looking for them
1024 auto *GuardDecl = BBI->getModule()->getFunction(
1025 Intrinsic::getName(Intrinsic::experimental_guard));
1026 if (!GuardDecl || GuardDecl->use_empty())
1027 return;
1028
Artur Pilipenko47dc0982016-10-21 15:02:21 +00001029 for (Instruction &I : make_range(BBI->getIterator().getReverse(),
1030 BBI->getParent()->rend())) {
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001031 Value *Cond = nullptr;
Artur Pilipenko47dc0982016-10-21 15:02:21 +00001032 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
1033 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001034 }
Hal Finkel7e184492014-09-07 20:29:59 +00001035}
1036
Philip Reames92e5e1b2016-09-12 21:46:58 +00001037bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001038 SelectInst *SI, BasicBlock *BB) {
1039
1040 // Recurse on our inputs if needed
1041 if (!hasBlockValue(SI->getTrueValue(), BB)) {
1042 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
1043 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001044 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001045 return true;
1046 }
1047 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
1048 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1049 // extra slots in the table if we can.
1050 if (TrueVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001051 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001052 return true;
1053 }
1054
1055 if (!hasBlockValue(SI->getFalseValue(), BB)) {
1056 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
1057 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001058 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001059 return true;
1060 }
1061 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
1062 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1063 // extra slots in the table if we can.
1064 if (FalseVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001065 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001066 return true;
1067 }
1068
Philip Reamesadf0e352016-02-26 22:53:59 +00001069 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
1070 ConstantRange TrueCR = TrueVal.getConstantRange();
1071 ConstantRange FalseCR = FalseVal.getConstantRange();
1072 Value *LHS = nullptr;
1073 Value *RHS = nullptr;
1074 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
1075 // Is this a min specifically of our two inputs? (Avoid the risk of
1076 // ValueTracking getting smarter looking back past our immediate inputs.)
1077 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
1078 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
Philip Reamesb2949622016-12-06 02:54:16 +00001079 ConstantRange ResultCR = [&]() {
1080 switch (SPR.Flavor) {
1081 default:
1082 llvm_unreachable("unexpected minmax type!");
1083 case SPF_SMIN: /// Signed minimum
1084 return TrueCR.smin(FalseCR);
1085 case SPF_UMIN: /// Unsigned minimum
1086 return TrueCR.umin(FalseCR);
1087 case SPF_SMAX: /// Signed maximum
1088 return TrueCR.smax(FalseCR);
1089 case SPF_UMAX: /// Unsigned maximum
1090 return TrueCR.umax(FalseCR);
1091 };
1092 }();
1093 BBLV = LVILatticeVal::getRange(ResultCR);
1094 return true;
Philip Reamesadf0e352016-02-26 22:53:59 +00001095 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001096
Philip Reamesadf0e352016-02-26 22:53:59 +00001097 // TODO: ABS, NABS from the SelectPatternResult
1098 }
1099
Philip Reames854a84c2016-02-12 00:09:18 +00001100 // Can we constrain the facts about the true and false values by using the
1101 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
1102 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001103 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001104 TrueVal = intersect(TrueVal,
1105 getValueFromCondition(SI->getTrueValue(), Cond, true));
1106 FalseVal = intersect(FalseVal,
1107 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +00001108
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001109 // Handle clamp idioms such as:
1110 // %24 = constantrange<0, 17>
1111 // %39 = icmp eq i32 %24, 0
1112 // %40 = add i32 %24, -1
1113 // %siv.next = select i1 %39, i32 16, i32 %40
1114 // %siv.next = constantrange<0, 17> not <-1, 17>
1115 // In general, this can handle any clamp idiom which tests the edge
1116 // condition via an equality or inequality.
1117 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +00001118 ICmpInst::Predicate Pred = ICI->getPredicate();
1119 Value *A = ICI->getOperand(0);
1120 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1121 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1122 assert(A->getType() == B->getType());
1123 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1124 };
1125 // See if either input is A + C2, subject to the constraint from the
1126 // condition that A != C when that input is used. We can assume that
1127 // that input doesn't include C + C2.
1128 ConstantInt *CIAdded;
1129 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +00001130 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +00001131 case ICmpInst::ICMP_EQ:
1132 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1133 m_ConstantInt(CIAdded)))) {
1134 auto ResNot = addConstants(CIBase, CIAdded);
1135 FalseVal = intersect(FalseVal,
1136 LVILatticeVal::getNot(ResNot));
1137 }
1138 break;
1139 case ICmpInst::ICMP_NE:
1140 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1141 m_ConstantInt(CIAdded)))) {
1142 auto ResNot = addConstants(CIBase, CIAdded);
1143 TrueVal = intersect(TrueVal,
1144 LVILatticeVal::getNot(ResNot));
1145 }
1146 break;
1147 };
1148 }
1149 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001150
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001151 LVILatticeVal Result; // Start Undefined.
1152 Result.mergeIn(TrueVal, DL);
1153 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001154 BBLV = Result;
1155 return true;
1156}
1157
Philip Reames92e5e1b2016-09-12 21:46:58 +00001158bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001159 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001160 BasicBlock *BB) {
1161 if (!BBI->getOperand(0)->getType()->isSized()) {
1162 // Without knowing how wide the input is, we can't analyze it in any useful
1163 // way.
Philip Reames1baaef12016-12-06 03:01:08 +00001164 BBLV = LVILatticeVal::getOverdefined();
Philip Reamese5030e82016-04-26 22:52:30 +00001165 return true;
1166 }
Philip Reamesf105db42016-04-26 23:27:33 +00001167
1168 // Filter out casts we don't know how to reason about before attempting to
1169 // recurse on our operand. This can cut a long search short if we know we're
1170 // not going to be able to get any useful information anways.
1171 switch (BBI->getOpcode()) {
1172 case Instruction::Trunc:
1173 case Instruction::SExt:
1174 case Instruction::ZExt:
1175 case Instruction::BitCast:
1176 break;
1177 default:
1178 // Unhandled instructions are overdefined.
1179 DEBUG(dbgs() << " compute BB '" << BB->getName()
1180 << "' - overdefined (unknown cast).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001181 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001182 return true;
1183 }
1184
Philip Reames38c87c22016-04-26 21:48:16 +00001185 // Figure out the range of the LHS. If that fails, we still apply the
1186 // transfer rule on the full set since we may be able to locally infer
1187 // interesting facts.
1188 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001189 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001190 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001191 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001192
1193 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001194 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001195 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1196 if (hasBlockValue(BBI->getOperand(0), BB)) {
1197 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001198 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1199 BBI);
Philip Reames38c87c22016-04-26 21:48:16 +00001200 if (LHSVal.isConstantRange())
1201 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001202 }
1203
Philip Reames38c87c22016-04-26 21:48:16 +00001204 const unsigned ResultBitWidth =
1205 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001206
1207 // NOTE: We're currently limited by the set of operations that ConstantRange
1208 // can evaluate symbolically. Enhancing that set will allows us to analyze
1209 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001210 auto CastOp = (Instruction::CastOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001211 BBLV = LVILatticeVal::getRange(LHSRange.castOp(CastOp, ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001212 return true;
1213}
1214
Philip Reames92e5e1b2016-09-12 21:46:58 +00001215bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001216 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001217 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001218
Philip Reames053c2a62016-04-26 23:10:35 +00001219 assert(BBI->getOperand(0)->getType()->isSized() &&
1220 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001221
1222 // Filter out operators we don't know how to reason about before attempting to
1223 // recurse on our operand(s). This can cut a long search short if we know
1224 // we're not going to be able to get any useful information anways.
1225 switch (BBI->getOpcode()) {
1226 case Instruction::Add:
1227 case Instruction::Sub:
1228 case Instruction::Mul:
1229 case Instruction::UDiv:
1230 case Instruction::Shl:
1231 case Instruction::LShr:
1232 case Instruction::And:
1233 case Instruction::Or:
1234 // continue into the code below
1235 break;
1236 default:
1237 // Unhandled instructions are overdefined.
1238 DEBUG(dbgs() << " compute BB '" << BB->getName()
1239 << "' - overdefined (unknown binary operator).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001240 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001241 return true;
1242 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001243
Philip Reames053c2a62016-04-26 23:10:35 +00001244 // Figure out the range of the LHS. If that fails, use a conservative range,
1245 // but apply the transfer rule anyways. This lets us pick up facts from
1246 // expressions like "and i32 (call i32 @foo()), 32"
1247 if (!hasBlockValue(BBI->getOperand(0), BB))
1248 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1249 // More work to do before applying this transfer rule.
1250 return false;
1251
1252 const unsigned OperandBitWidth =
1253 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1254 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1255 if (hasBlockValue(BBI->getOperand(0), BB)) {
1256 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001257 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1258 BBI);
Philip Reames053c2a62016-04-26 23:10:35 +00001259 if (LHSVal.isConstantRange())
1260 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001261 }
Philip Reames66715772016-04-25 18:30:31 +00001262
1263 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1264 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1265
Owen Anderson80d19f02010-08-18 21:11:37 +00001266 // NOTE: We're currently limited by the set of operations that ConstantRange
1267 // can evaluate symbolically. Enhancing that set will allows us to analyze
1268 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001269 auto BinOp = (Instruction::BinaryOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001270 BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001271 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001272}
1273
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001274static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1275 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001276 Value *LHS = ICI->getOperand(0);
1277 Value *RHS = ICI->getOperand(1);
1278 CmpInst::Predicate Predicate = ICI->getPredicate();
1279
1280 if (isa<Constant>(RHS)) {
1281 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001282 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001283 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001284 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001285 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001286 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001287 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001288 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001289 }
Hal Finkel7e184492014-09-07 20:29:59 +00001290
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001291 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001292 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001293
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001294 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1295 // range of Val guaranteed by the condition. Recognize comparisons in the from
1296 // of:
1297 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001298 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001299 // The latter is the range checking idiom that InstCombine produces. Subtract
1300 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001301
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001302 // Val or (add Val, Offset) can be on either hand of the comparison
1303 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1304 std::swap(LHS, RHS);
1305 Predicate = CmpInst::getSwappedPredicate(Predicate);
1306 }
Hal Finkel7e184492014-09-07 20:29:59 +00001307
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001308 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001309 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001310 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001311
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001312 if (LHS == Val || Offset) {
1313 // Calculate the range of values that are allowed by the comparison
1314 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1315 /*isFullSet=*/true);
1316 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1317 RHSRange = ConstantRange(CI->getValue());
Artur Pilipenko6669f252016-08-12 10:14:11 +00001318 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1319 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1320 RHSRange = getConstantRangeFromMetadata(*Ranges);
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001321
1322 // If we're interested in the false dest, invert the condition
1323 CmpInst::Predicate Pred =
1324 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1325 ConstantRange TrueValues =
1326 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1327
1328 if (Offset) // Apply the offset from above.
1329 TrueValues = TrueValues.subtract(Offset->getValue());
1330
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001331 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001332 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001333
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001334 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001335}
1336
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001337static LVILatticeVal
1338getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1339 DenseMap<Value*, LVILatticeVal> &Visited);
1340
1341static LVILatticeVal
1342getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1343 DenseMap<Value*, LVILatticeVal> &Visited) {
1344 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1345 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1346
1347 // Handle conditions in the form of (cond1 && cond2), we know that on the
1348 // true dest path both of the conditions hold.
1349 if (!isTrueDest)
1350 return LVILatticeVal::getOverdefined();
1351
1352 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1353 if (!BO || BO->getOpcode() != BinaryOperator::And)
1354 return LVILatticeVal::getOverdefined();
1355
1356 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1357 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1358 return intersect(RHS, LHS);
1359}
1360
1361static LVILatticeVal
1362getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1363 DenseMap<Value*, LVILatticeVal> &Visited) {
1364 auto I = Visited.find(Cond);
1365 if (I != Visited.end())
1366 return I->second;
Artur Pilipenkob6230882016-08-12 15:08:15 +00001367
1368 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1369 Visited[Cond] = Result;
1370 return Result;
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001371}
1372
1373LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1374 assert(Cond && "precondition");
1375 DenseMap<Value*, LVILatticeVal> Visited;
1376 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1377}
1378
Nuno Lopese6e04902012-06-28 01:16:18 +00001379/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001380/// Val is not constrained on the edge. Result is unspecified if return value
1381/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001382static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1383 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001384 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001385 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001386 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1387 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001388 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001389 if (BI->isConditional() &&
1390 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1391 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1392 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1393 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001394
Chris Lattner19019ea2009-11-11 22:48:44 +00001395 // If V is the condition of the branch itself, then we know exactly what
1396 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001397 if (BI->getCondition() == Val) {
1398 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001399 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001400 return true;
1401 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001402
Chris Lattner19019ea2009-11-11 22:48:44 +00001403 // If the condition of the branch is an equality comparison, we may be
1404 // able to infer the value.
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001405 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1406 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001407 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001408 }
1409 }
Chris Lattner77358782009-11-15 20:02:12 +00001410
1411 // If the edge was formed by a switch on the value, then we may know exactly
1412 // what it is.
1413 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001414 if (SI->getCondition() != Val)
1415 return false;
1416
1417 bool DefaultCase = SI->getDefaultDest() == BBTo;
1418 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1419 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1420
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001421 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001422 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001423 if (DefaultCase) {
1424 // It is possible that the default destination is the destination of
1425 // some cases. There is no need to perform difference for those cases.
1426 if (i.getCaseSuccessor() != BBTo)
1427 EdgesVals = EdgesVals.difference(EdgeVal);
1428 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001429 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001430 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001431 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001432 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001433 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001434 return false;
1435}
1436
Sanjay Patel938e2792015-01-09 16:35:37 +00001437/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1438/// the basic block if the edge does not constrain Val.
Philip Reames92e5e1b2016-09-12 21:46:58 +00001439bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Xin Tong68ea9aa2017-02-24 20:59:26 +00001440 BasicBlock *BBTo, LVILatticeVal &Result,
1441 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001442 // If already a constant, there is nothing to compute.
1443 if (Constant *VC = dyn_cast<Constant>(Val)) {
1444 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001445 return true;
1446 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001447
Philip Reames44456b82016-02-02 03:15:40 +00001448 LVILatticeVal LocalResult;
1449 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1450 // If we couldn't constrain the value on the edge, LocalResult doesn't
1451 // provide any information.
Philip Reames1baaef12016-12-06 03:01:08 +00001452 LocalResult = LVILatticeVal::getOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001453
Philip Reames44456b82016-02-02 03:15:40 +00001454 if (hasSingleValue(LocalResult)) {
1455 // Can't get any more precise here
1456 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001457 return true;
1458 }
1459
1460 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001461 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1462 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001463 // No new information.
1464 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001465 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001466 }
1467
Philip Reames44456b82016-02-02 03:15:40 +00001468 // Try to intersect ranges of the BB and the constraint on the edge.
1469 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001470 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1471 BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001472 // We can use the context instruction (generically the ultimate instruction
1473 // the calling pass is trying to simplify) here, even though the result of
1474 // this function is generally cached when called from the solve* functions
1475 // (and that cached result might be used with queries using a different
1476 // context instruction), because when this function is called from the solve*
1477 // functions, the context instruction is not provided. When called from
Philip Reames92e5e1b2016-09-12 21:46:58 +00001478 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
Hal Finkel2400c962014-10-16 00:40:05 +00001479 // but then the result is not cached.
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001480 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001481
1482 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001483 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001484}
1485
Philip Reames92e5e1b2016-09-12 21:46:58 +00001486LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Hal Finkel7e184492014-09-07 20:29:59 +00001487 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001488 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001489 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001490
Hans Wennborg45172ac2014-11-25 17:23:05 +00001491 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001492 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001493 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001494 solve();
1495 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001496 LVILatticeVal Result = getBlockValue(V, BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001497 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001498
1499 DEBUG(dbgs() << " Result = " << Result << "\n");
1500 return Result;
1501}
1502
Philip Reames92e5e1b2016-09-12 21:46:58 +00001503LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001504 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1505 << CxtI->getName() << "'\n");
1506
Philip Reamesbb781b42016-02-10 21:46:32 +00001507 if (auto *C = dyn_cast<Constant>(V))
1508 return LVILatticeVal::get(C);
1509
Philip Reamesd1f829d2016-02-02 21:57:37 +00001510 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001511 if (auto *I = dyn_cast<Instruction>(V))
1512 Result = getFromRangeMetadata(I);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001513 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001514
David Greene37e98092009-12-23 20:43:58 +00001515 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001516 return Result;
1517}
Chris Lattner19019ea2009-11-11 22:48:44 +00001518
Philip Reames92e5e1b2016-09-12 21:46:58 +00001519LVILatticeVal LazyValueInfoImpl::
Hal Finkel7e184492014-09-07 20:29:59 +00001520getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1521 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001522 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001523 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001524
Nick Lewycky55a700b2010-12-18 01:00:40 +00001525 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001526 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001527 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001528 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001529 (void)WasFastQuery;
1530 assert(WasFastQuery && "More work to do after problem solved?");
1531 }
1532
David Greene37e98092009-12-23 20:43:58 +00001533 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001534 return Result;
1535}
1536
Philip Reames92e5e1b2016-09-12 21:46:58 +00001537void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Philip Reames9db79482016-09-12 22:38:44 +00001538 BasicBlock *NewSucc) {
1539 TheCache.threadEdgeImpl(OldSucc, NewSucc);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001540}
1541
Chris Lattneraf025d32009-11-15 19:59:49 +00001542//===----------------------------------------------------------------------===//
1543// LazyValueInfo Impl
1544//===----------------------------------------------------------------------===//
1545
Philip Reames92e5e1b2016-09-12 21:46:58 +00001546/// This lazily constructs the LazyValueInfoImpl.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001547static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1548 const DataLayout *DL,
Philip Reames92e5e1b2016-09-12 21:46:58 +00001549 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001550 if (!PImpl) {
1551 assert(DL && "getCache() called with a null DataLayout");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001552 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001553 }
Philip Reames92e5e1b2016-09-12 21:46:58 +00001554 return *static_cast<LazyValueInfoImpl*>(PImpl);
Chris Lattneraf025d32009-11-15 19:59:49 +00001555}
1556
Sean Silva687019f2016-06-13 22:01:25 +00001557bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001558 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001559 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001560
1561 DominatorTreeWrapperPass *DTWP =
1562 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001563 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1564 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001565
Sean Silva687019f2016-06-13 22:01:25 +00001566 if (Info.PImpl)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001567 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001568
Owen Anderson208636f2010-08-18 18:39:01 +00001569 // Fully lazy.
1570 return false;
1571}
1572
Sean Silva687019f2016-06-13 22:01:25 +00001573void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001574 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001575 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001576 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001577}
1578
Sean Silva687019f2016-06-13 22:01:25 +00001579LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1580
1581LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1582
Chris Lattneraf025d32009-11-15 19:59:49 +00001583void LazyValueInfo::releaseMemory() {
1584 // If the cache was allocated, free it.
1585 if (PImpl) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001586 delete &getImpl(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001587 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001588 }
1589}
1590
Chandler Carrutha504f2b2017-01-23 06:35:12 +00001591bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1592 FunctionAnalysisManager::Invalidator &Inv) {
1593 // We need to invalidate if we have either failed to preserve this analyses
1594 // result directly or if any of its dependencies have been invalidated.
1595 auto PAC = PA.getChecker<LazyValueAnalysis>();
1596 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
1597 (DT && Inv.invalidate<DominatorTreeAnalysis>(F, PA)))
1598 return true;
1599
1600 return false;
1601}
1602
Sean Silva687019f2016-06-13 22:01:25 +00001603void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1604
1605LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001606 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
Sean Silva687019f2016-06-13 22:01:25 +00001607 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1608 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1609
Anna Thomasa10e3e42017-03-12 14:06:41 +00001610 return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI, DT);
Sean Silva687019f2016-06-13 22:01:25 +00001611}
1612
Wei Mif160e342016-09-15 06:28:34 +00001613/// Returns true if we can statically tell that this value will never be a
1614/// "useful" constant. In practice, this means we've got something like an
1615/// alloca or a malloc call for which a comparison against a constant can
1616/// only be guarding dead code. Note that we are potentially giving up some
1617/// precision in dead code (a constant result) in favour of avoiding a
1618/// expensive search for a easily answered common query.
1619static bool isKnownNonConstant(Value *V) {
1620 V = V->stripPointerCasts();
1621 // The return val of alloc cannot be a Constant.
1622 if (isa<AllocaInst>(V))
1623 return true;
1624 return false;
1625}
1626
Hal Finkel7e184492014-09-07 20:29:59 +00001627Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1628 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001629 // Bail out early if V is known not to be a Constant.
1630 if (isKnownNonConstant(V))
1631 return nullptr;
1632
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001633 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001634 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001635 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001636
Chris Lattner19019ea2009-11-11 22:48:44 +00001637 if (Result.isConstant())
1638 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001639 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001640 ConstantRange CR = Result.getConstantRange();
1641 if (const APInt *SingleVal = CR.getSingleElement())
1642 return ConstantInt::get(V->getContext(), *SingleVal);
1643 }
Craig Topper9f008862014-04-15 04:59:12 +00001644 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001645}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001646
John Regehre1c481d2016-05-02 19:58:00 +00001647ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001648 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001649 assert(V->getType()->isIntegerTy());
1650 unsigned Width = V->getType()->getIntegerBitWidth();
1651 const DataLayout &DL = BB->getModule()->getDataLayout();
1652 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001653 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001654 if (Result.isUndefined())
1655 return ConstantRange(Width, /*isFullSet=*/false);
1656 if (Result.isConstantRange())
1657 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001658 // We represent ConstantInt constants as constant ranges but other kinds
1659 // of integer constants, i.e. ConstantExpr will be tagged as constants
1660 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1661 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001662 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001663}
1664
Sanjay Patel2a385e22015-01-09 16:47:20 +00001665/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001666/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001667Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001668 BasicBlock *ToBB,
1669 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001670 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001671 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001672 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001673
Chris Lattnerd5e25432009-11-12 01:29:10 +00001674 if (Result.isConstant())
1675 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001676 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001677 ConstantRange CR = Result.getConstantRange();
1678 if (const APInt *SingleVal = CR.getSingleElement())
1679 return ConstantInt::get(V->getContext(), *SingleVal);
1680 }
Craig Topper9f008862014-04-15 04:59:12 +00001681 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001682}
1683
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001684static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1685 LVILatticeVal &Result,
1686 const DataLayout &DL,
1687 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001688
Chris Lattner565ee2f2009-11-12 04:36:58 +00001689 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001690 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001691 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001692 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001693 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001694 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001695 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1696 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001697 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001698
Owen Anderson185fe002010-08-10 20:03:09 +00001699 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001700 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001701 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001702
Owen Anderson185fe002010-08-10 20:03:09 +00001703 ConstantRange CR = Result.getConstantRange();
1704 if (Pred == ICmpInst::ICMP_EQ) {
1705 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001706 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001707
Owen Anderson185fe002010-08-10 20:03:09 +00001708 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001709 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001710 } else if (Pred == ICmpInst::ICMP_NE) {
1711 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001712 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001713
Owen Anderson185fe002010-08-10 20:03:09 +00001714 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001715 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001716 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001717
Owen Anderson185fe002010-08-10 20:03:09 +00001718 // Handle more complex predicates.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00001719 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1720 (ICmpInst::Predicate)Pred, CI->getValue());
Nick Lewycky11678bd2010-12-15 18:57:18 +00001721 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001722 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001723 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001724 return LazyValueInfo::False;
1725 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001726 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001727
Chris Lattneraf025d32009-11-15 19:59:49 +00001728 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001729 // If this is an equality comparison, we can try to fold it knowing that
1730 // "V != C1".
1731 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001732 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001733 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001734 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001735 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001736 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001737 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001738 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001739 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001740 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001741 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001742 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001743 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001744 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001745 }
Hal Finkel7e184492014-09-07 20:29:59 +00001746 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001747 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001748
Hal Finkel7e184492014-09-07 20:29:59 +00001749 return LazyValueInfo::Unknown;
1750}
1751
Sanjay Patel2a385e22015-01-09 16:47:20 +00001752/// Determine whether the specified value comparison with a constant is known to
1753/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001754LazyValueInfo::Tristate
1755LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1756 BasicBlock *FromBB, BasicBlock *ToBB,
1757 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001758 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001759 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001760 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001761
1762 return getPredicateResult(Pred, C, Result, DL, TLI);
1763}
1764
1765LazyValueInfo::Tristate
1766LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1767 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001768 // Is or is not NonNull are common predicates being queried. If
1769 // isKnownNonNull can tell us the result of the predicate, we can
1770 // return it quickly. But this is only a fastpath, and falling
1771 // through would still be correct.
1772 if (V->getType()->isPointerTy() && C->isNullValue() &&
1773 isKnownNonNull(V->stripPointerCasts())) {
1774 if (Pred == ICmpInst::ICMP_EQ)
1775 return LazyValueInfo::False;
1776 else if (Pred == ICmpInst::ICMP_NE)
1777 return LazyValueInfo::True;
1778 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001779 const DataLayout &DL = CxtI->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001780 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001781 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1782 if (Ret != Unknown)
1783 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001784
Philip Reamesaeefae02015-11-04 01:47:04 +00001785 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1786 // LVI as a whole tries to compute a lattice value which is conservatively
1787 // correct at a given location. In this case, we have a predicate which we
1788 // weren't able to prove about the merged result, and we're pushing that
1789 // predicate back along each incoming edge to see if we can prove it
1790 // separately for each input. As a motivating example, consider:
1791 // bb1:
1792 // %v1 = ... ; constantrange<1, 5>
1793 // br label %merge
1794 // bb2:
1795 // %v2 = ... ; constantrange<10, 20>
1796 // br label %merge
1797 // merge:
1798 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1799 // %pred = icmp eq i32 %phi, 8
1800 // We can't tell from the lattice value for '%phi' that '%pred' is false
1801 // along each path, but by checking the predicate over each input separately,
1802 // we can.
1803 // We limit the search to one step backwards from the current BB and value.
1804 // We could consider extending this to search further backwards through the
1805 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001806 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001807 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001808 BasicBlock *BB = CxtI->getParent();
1809
1810 // Function entry or an unreachable block. Bail to avoid confusing
1811 // analysis below.
1812 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1813 if (PI == PE)
1814 return Unknown;
1815
1816 // If V is a PHI node in the same block as the context, we need to ask
1817 // questions about the predicate as applied to the incoming value along
1818 // each edge. This is useful for eliminating cases where the predicate is
1819 // known along all incoming edges.
1820 if (auto *PHI = dyn_cast<PHINode>(V))
1821 if (PHI->getParent() == BB) {
1822 Tristate Baseline = Unknown;
1823 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1824 Value *Incoming = PHI->getIncomingValue(i);
1825 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001826 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001827 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1828 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001829
Philip Reamesbb11d622015-08-31 18:31:48 +00001830 // Keep going as long as we've seen a consistent known result for
1831 // all inputs.
1832 Baseline = (i == 0) ? Result /* First iteration */
1833 : (Baseline == Result ? Baseline : Unknown); /* All others */
1834 if (Baseline == Unknown)
1835 break;
1836 }
1837 if (Baseline != Unknown)
1838 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001839 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001840
Philip Reames66ab0f02015-06-16 00:49:59 +00001841 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001842 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001843 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001844 if (!isa<Instruction>(V) ||
1845 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001846 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001847 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001848 // the value of the comparison in this block.
1849 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1850 if (Baseline != Unknown) {
1851 // Check that all remaining incoming values match the first one.
1852 while (++PI != PE) {
1853 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1854 if (Ret != Baseline) break;
1855 }
1856 // If we terminated early, then one of the values didn't match.
1857 if (PI == PE) {
1858 return Baseline;
1859 }
1860 }
1861 }
1862 }
1863 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001864}
1865
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001866void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001867 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001868 if (PImpl) {
1869 const DataLayout &DL = PredBB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001870 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001871 }
Owen Anderson208636f2010-08-18 18:39:01 +00001872}
1873
1874void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001875 if (PImpl) {
1876 const DataLayout &DL = BB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001877 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001878 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001879}
Anna Thomase27b39a2017-03-22 19:27:12 +00001880
1881
1882void LazyValueInfo::printCache(Function &F, raw_ostream &OS) {
1883 if (PImpl) {
1884 getImpl(PImpl, AC, DL, DT).printCache(F, OS);
1885 }
1886}
1887
1888namespace {
1889// Printer class for LazyValueInfo results.
1890class LazyValueInfoPrinter : public FunctionPass {
1891public:
1892 static char ID; // Pass identification, replacement for typeid
1893 LazyValueInfoPrinter() : FunctionPass(ID) {
1894 initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
1895 }
1896
1897 void getAnalysisUsage(AnalysisUsage &AU) const override {
1898 AU.setPreservesAll();
1899 AU.addRequired<LazyValueInfoWrapperPass>();
1900 }
1901
1902 bool runOnFunction(Function &F) override {
1903 dbgs() << "LVI for function '" << F.getName() << "':\n";
1904 auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1905 LVI.printCache(F, dbgs());
1906 return false;
1907 }
1908};
1909}
1910
1911char LazyValueInfoPrinter::ID = 0;
1912INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
1913 "Lazy Value Info Printer Pass", false, false)
1914INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1915INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
1916 "Lazy Value Info Printer Pass", false, false)