blob: 6a7fe1154be5b499a6581529778d2eee1b14dabb [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"
Chandler Carruth66b31302015-01-04 12:03:27 +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"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000029#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000030#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000031#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000032#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000034#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000035#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000036using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000037using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000038
Chandler Carruthf1221bd2014-04-22 02:48:03 +000039#define DEBUG_TYPE "lazy-value-info"
40
Chris Lattner741c94c2009-11-11 00:22:30 +000041char LazyValueInfo::ID = 0;
Chad Rosier43a33062011-12-02 01:26:24 +000042INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
43 "Lazy Value Information Analysis", false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +000044INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000045INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chad Rosier43a33062011-12-02 01:26:24 +000046INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000047 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000048
49namespace llvm {
50 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
51}
52
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000053
54//===----------------------------------------------------------------------===//
55// LVILatticeVal
56//===----------------------------------------------------------------------===//
57
Sanjay Patel2a385e22015-01-09 16:47:20 +000058/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000059///
60/// FIXME: This is basically just for bringup, this can be made a lot more rich
61/// in the future.
62///
63namespace {
64class LVILatticeVal {
65 enum LatticeValueTy {
Sanjay Patel2a385e22015-01-09 16:47:20 +000066 /// This Value has no known value yet.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000067 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000068
Sanjay Patel2a385e22015-01-09 16:47:20 +000069 /// This Value has a specific constant value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000070 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000071
Sanjay Patel2a385e22015-01-09 16:47:20 +000072 /// This Value is known to not have the specified value.
Chris Lattner565ee2f2009-11-12 04:36:58 +000073 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000074
Sanjay Patel2a385e22015-01-09 16:47:20 +000075 /// The Value falls within this range.
Owen Anderson0f306a42010-08-05 22:59:19 +000076 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000077
Sanjay Patel2a385e22015-01-09 16:47:20 +000078 /// This value is not known to be constant, and we know that it has a value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000079 overdefined
80 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000081
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000082 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000083 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000084 LatticeValueTy Tag;
85 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000086 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000087
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000088public:
Craig Topper9f008862014-04-15 04:59:12 +000089 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000090
Chris Lattner19019ea2009-11-11 22:48:44 +000091 static LVILatticeVal get(Constant *C) {
92 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000093 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000094 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +000095 return Res;
96 }
Chris Lattner565ee2f2009-11-12 04:36:58 +000097 static LVILatticeVal getNot(Constant *C) {
98 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000099 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000100 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000101 return Res;
102 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000103 static LVILatticeVal getRange(ConstantRange CR) {
104 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000105 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000106 return Res;
107 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000108 static LVILatticeVal getOverdefined() {
109 LVILatticeVal Res;
110 Res.markOverdefined();
111 return Res;
112 }
113
Owen Anderson0f306a42010-08-05 22:59:19 +0000114 bool isUndefined() const { return Tag == undefined; }
115 bool isConstant() const { return Tag == constant; }
116 bool isNotConstant() const { return Tag == notconstant; }
117 bool isConstantRange() const { return Tag == constantrange; }
118 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000119
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000120 Constant *getConstant() const {
121 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000122 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000123 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000124
Chris Lattner565ee2f2009-11-12 04:36:58 +0000125 Constant *getNotConstant() const {
126 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000127 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000128 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000129
Owen Anderson0f306a42010-08-05 22:59:19 +0000130 ConstantRange getConstantRange() const {
131 assert(isConstantRange() &&
132 "Cannot get the constant-range of a non-constant-range!");
133 return Range;
134 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000135
Sanjay Patel2a385e22015-01-09 16:47:20 +0000136 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000137 bool markOverdefined() {
138 if (isOverdefined())
139 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000140 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000141 return true;
142 }
143
Sanjay Patel2a385e22015-01-09 16:47:20 +0000144 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000145 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000146 assert(V && "Marking constant with NULL");
147 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
148 return markConstantRange(ConstantRange(CI->getValue()));
149 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000150 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000151
152 assert((!isConstant() || getConstant() == V) &&
153 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000154 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000155 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000156 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000157 return true;
158 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000159
Sanjay Patel2a385e22015-01-09 16:47:20 +0000160 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000161 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000162 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000163 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
164 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
165 if (isa<UndefValue>(V))
166 return false;
167
168 assert((!isConstant() || getConstant() != V) &&
169 "Marking constant !constant with same value");
170 assert((!isNotConstant() || getNotConstant() == V) &&
171 "Marking !constant with different value");
172 assert(isUndefined() || isConstant());
173 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000174 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000175 return true;
176 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000177
Sanjay Patel2a385e22015-01-09 16:47:20 +0000178 /// Return true if this is a change in status.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000179 bool markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000180 if (isConstantRange()) {
181 if (NewR.isEmptySet())
182 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000183
Nuno Lopese6e04902012-06-28 01:16:18 +0000184 bool changed = Range != NewR;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000185 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000186 return changed;
187 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000188
Owen Anderson0f306a42010-08-05 22:59:19 +0000189 assert(isUndefined());
190 if (NewR.isEmptySet())
191 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000192
Owen Anderson0f306a42010-08-05 22:59:19 +0000193 Tag = constantrange;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000194 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000195 return true;
196 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000197
Sanjay Patel2a385e22015-01-09 16:47:20 +0000198 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000199 /// one and returning true if anything changed.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000200 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
Chris Lattner19019ea2009-11-11 22:48:44 +0000201 if (RHS.isUndefined() || isOverdefined()) return false;
202 if (RHS.isOverdefined()) return markOverdefined();
203
Nick Lewycky11678bd2010-12-15 18:57:18 +0000204 if (isUndefined()) {
205 Tag = RHS.Tag;
206 Val = RHS.Val;
207 Range = RHS.Range;
208 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000209 }
210
Nick Lewycky11678bd2010-12-15 18:57:18 +0000211 if (isConstant()) {
212 if (RHS.isConstant()) {
213 if (Val == RHS.Val)
214 return false;
215 return markOverdefined();
216 }
217
218 if (RHS.isNotConstant()) {
219 if (Val == RHS.Val)
220 return markOverdefined();
221
222 // Unless we can prove that the two Constants are different, we must
223 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224 if (ConstantInt *Res =
225 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
226 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000227 if (Res->isOne())
228 return markNotConstant(RHS.getNotConstant());
229
230 return markOverdefined();
231 }
232
233 // RHS is a ConstantRange, LHS is a non-integer Constant.
234
235 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
236 // a function. The correct result is to pick up RHS.
237
Chris Lattner19019ea2009-11-11 22:48:44 +0000238 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000239 }
240
241 if (isNotConstant()) {
242 if (RHS.isConstant()) {
243 if (Val == RHS.Val)
244 return markOverdefined();
245
246 // Unless we can prove that the two Constants are different, we must
247 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248 if (ConstantInt *Res =
249 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
250 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000251 if (Res->isOne())
252 return false;
253
254 return markOverdefined();
255 }
256
257 if (RHS.isNotConstant()) {
258 if (Val == RHS.Val)
259 return false;
260 return markOverdefined();
261 }
262
263 return markOverdefined();
264 }
265
266 assert(isConstantRange() && "New LVILattice type?");
267 if (!RHS.isConstantRange())
268 return markOverdefined();
269
270 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
271 if (NewR.isFullSet())
272 return markOverdefined();
273 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000274 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000275};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000276
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000277} // end anonymous namespace.
278
Chris Lattner19019ea2009-11-11 22:48:44 +0000279namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000280raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
281 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000282raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
283 if (Val.isUndefined())
284 return OS << "undefined";
285 if (Val.isOverdefined())
286 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000287
288 if (Val.isNotConstant())
289 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson8afac042010-08-09 20:50:46 +0000290 else if (Val.isConstantRange())
291 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
292 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000293 return OS << "constant<" << *Val.getConstant() << '>';
294}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000295}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000296
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000297/// Returns true if this lattice value represents at most one possible value.
298/// This is as precise as any lattice value can get while still representing
299/// reachable code.
300static bool hasSingleValue(LVILatticeVal Val) {
301 if (Val.isConstantRange() &&
302 Val.getConstantRange().isSingleElement())
303 // Integer constants are single element ranges
304 return true;
305 if (Val.isConstant())
306 // Non integer constants
307 return true;
308 return false;
309}
310
311/// Combine two sets of facts about the same value into a single set of
312/// facts. Note that this method is not suitable for merging facts along
313/// different paths in a CFG; that's what the mergeIn function is for. This
314/// is for merging facts gathered about the same value at the same location
315/// through two independent means.
316/// Notes:
317/// * This method does not promise to return the most precise possible lattice
318/// value implied by A and B. It is allowed to return any lattice element
319/// which is at least as strong as *either* A or B (unless our facts
320/// conflict, see below).
321/// * Due to unreachable code, the intersection of two lattice values could be
322/// contradictory. If this happens, we return some valid lattice value so as
323/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
324/// we do not make this guarantee. TODO: This would be a useful enhancement.
325static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
326 // Undefined is the strongest state. It means the value is known to be along
327 // an unreachable path.
328 if (A.isUndefined())
329 return A;
330 if (B.isUndefined())
331 return B;
332
333 // If we gave up for one, but got a useable fact from the other, use it.
334 if (A.isOverdefined())
335 return B;
336 if (B.isOverdefined())
337 return A;
338
339 // Can't get any more precise than constants.
340 if (hasSingleValue(A))
341 return A;
342 if (hasSingleValue(B))
343 return B;
344
345 // Could be either constant range or not constant here.
346 if (!A.isConstantRange() || !B.isConstantRange()) {
347 // TODO: Arbitrary choice, could be improved
348 return A;
349 }
350
351 // Intersect two constant ranges
352 ConstantRange Range =
353 A.getConstantRange().intersectWith(B.getConstantRange());
354 // Note: An empty range is implicitly converted to overdefined internally.
355 // TODO: We could instead use Undefined here since we've proven a conflict
356 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000357 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000358}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000359
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000360//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000361// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000362//===----------------------------------------------------------------------===//
363
Chris Lattneraf025d32009-11-15 19:59:49 +0000364namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000365 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000366 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000367 struct LVIValueHandle final : public CallbackVH {
Owen Anderson118ac802011-01-05 21:15:29 +0000368 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000369
Owen Anderson118ac802011-01-05 21:15:29 +0000370 LVIValueHandle(Value *V, LazyValueInfoCache *P)
371 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000372
373 void deleted() override;
374 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000375 deleted();
376 }
377 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000378}
Owen Anderson118ac802011-01-05 21:15:29 +0000379
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000380namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000381 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000382 /// maintains information about queries across the clients' queries.
383 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000384 /// This is all of the cached block information for exactly one Value*.
385 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000386 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000387 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
388 /// memory overhead.
Bruno Cardoso Lopes1846ea32015-08-18 16:54:36 +0000389 typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
390 ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000391
Sanjay Patel2a385e22015-01-09 16:47:20 +0000392 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000393 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000394 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000395
Sanjay Patel2a385e22015-01-09 16:47:20 +0000396 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000397 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000398 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
399 OverDefinedCacheTy;
400 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000401
Sanjay Patel2a385e22015-01-09 16:47:20 +0000402 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000403 /// don't spend time removing unused blocks from our caches.
404 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
405
Sanjay Patel2a385e22015-01-09 16:47:20 +0000406 /// This stack holds the state of the value solver during a query.
407 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000408 /// recursive value lookup process.
409 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000410
Sanjay Patel2a385e22015-01-09 16:47:20 +0000411 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000412 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
413
Sanjay Patel2a385e22015-01-09 16:47:20 +0000414 /// Push BV onto BlockValueStack unless it's already in there.
415 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000416 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000417 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000418 return false; // It's already in the stack.
419
Philip Reames44456b82016-02-02 03:15:40 +0000420 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
421 << "\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000422 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000423 return true;
424 }
425
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000426 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
427 const DataLayout &DL; ///< A mandatory DataLayout
428 DominatorTree *DT; ///< An optional DT pointer.
429
Owen Anderson118ac802011-01-05 21:15:29 +0000430 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000431
Hans Wennborg45172ac2014-11-25 17:23:05 +0000432 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
433 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000434
435 // Insert over-defined values into their own cache to reduce memory
436 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000437 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000438 OverDefinedCache[BB].insert(Val);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000439 else
440 lookup(Val)[BB] = Result;
Hans Wennborg45172ac2014-11-25 17:23:05 +0000441 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000442
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000443 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000444 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000445 LVILatticeVal &Result,
446 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000447 bool hasBlockValue(Value *Val, BasicBlock *BB);
448
449 // These methods process one work item and may add more. A false value
450 // returned means that the work item was not completely processed and must
451 // be revisited after going through the new items.
452 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000453 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
454 Value *Val, BasicBlock *BB);
455 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
456 PHINode *PN, BasicBlock *BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000457 bool solveBlockValueSelect(LVILatticeVal &BBLV,
458 SelectInst *S, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000459 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
460 Instruction *BBI, BasicBlock *BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +0000461 void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
Hal Finkel7e184492014-09-07 20:29:59 +0000462 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000463
464 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000465
Nick Lewycky11678bd2010-12-15 18:57:18 +0000466 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000467 return ValueCache[LVIValueHandle(V, this)];
468 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000469
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000470 bool isOverdefined(Value *V, BasicBlock *BB) const {
471 auto ODI = OverDefinedCache.find(BB);
472
473 if (ODI == OverDefinedCache.end())
474 return false;
475
476 return ODI->second.count(V);
477 }
478
479 bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
480 if (isOverdefined(V, BB))
481 return true;
482
483 LVIValueHandle ValHandle(V, this);
484 auto I = ValueCache.find(ValHandle);
485 if (I == ValueCache.end())
486 return false;
487
488 return I->second.count(BB);
489 }
490
491 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
492 if (isOverdefined(V, BB))
493 return LVILatticeVal::getOverdefined();
494
495 return lookup(V)[BB];
496 }
497
Chris Lattneraf025d32009-11-15 19:59:49 +0000498 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000499 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000500 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000501 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
502 Instruction *CxtI = nullptr);
503
Sanjay Patel2a385e22015-01-09 16:47:20 +0000504 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000505 /// value for the specified Value* at the specified instruction (generally
506 /// from an assume intrinsic).
507 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000508
Sanjay Patel2a385e22015-01-09 16:47:20 +0000509 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000510 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000511 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
512 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000513
Sanjay Patel2a385e22015-01-09 16:47:20 +0000514 /// This is the update interface to inform the cache that an edge from
515 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000516 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000517
Sanjay Patel2a385e22015-01-09 16:47:20 +0000518 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000519 /// that a block has been deleted.
520 void eraseBlock(BasicBlock *BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000521
Owen Anderson208636f2010-08-18 18:39:01 +0000522 /// clear - Empty the cache.
523 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000524 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000525 ValueCache.clear();
526 OverDefinedCache.clear();
527 }
Hal Finkel7e184492014-09-07 20:29:59 +0000528
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000529 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000530 DominatorTree *DT = nullptr)
531 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000532 };
533} // end anonymous namespace
534
Owen Anderson118ac802011-01-05 21:15:29 +0000535void LVIValueHandle::deleted() {
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000536 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
537 for (auto &I : Parent->OverDefinedCache) {
538 SmallPtrSetImpl<Value *> &ValueSet = I.second;
539 if (ValueSet.count(getValPtr()))
540 ValueSet.erase(getValPtr());
541 if (ValueSet.empty())
542 ToErase.push_back(I.first);
543 }
544 for (auto &BB : ToErase)
545 Parent->OverDefinedCache.erase(BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000546
Owen Anderson7b974a42010-08-11 22:36:04 +0000547 // This erasure deallocates *this, so it MUST happen after we're done
548 // using any and all members of *this.
549 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000550}
551
Owen Anderson208636f2010-08-18 18:39:01 +0000552void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000553 // Shortcut if we have never seen this block.
554 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
555 if (I == SeenBlocks.end())
556 return;
557 SeenBlocks.erase(I);
558
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000559 auto ODI = OverDefinedCache.find(BB);
560 if (ODI != OverDefinedCache.end())
561 OverDefinedCache.erase(ODI);
Owen Anderson208636f2010-08-18 18:39:01 +0000562
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000563 for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
Owen Anderson208636f2010-08-18 18:39:01 +0000564 I->second.erase(BB);
565}
Owen Andersonc1561b82010-07-30 23:59:40 +0000566
Nick Lewycky55a700b2010-12-18 01:00:40 +0000567void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000568 while (!BlockValueStack.empty()) {
569 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000570 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
571
Nuno Lopese6e04902012-06-28 01:16:18 +0000572 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000573 // The work item was completely processed.
574 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000575 assert(hasCachedValueInfo(e.second, e.first) &&
576 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000577
Philip Reames44456b82016-02-02 03:15:40 +0000578 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000579 << " = " << getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000580
Owen Anderson6f060af2011-01-05 23:26:22 +0000581 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000582 BlockValueSet.erase(e);
583 } else {
584 // More work needs to be done before revisiting.
585 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000586 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000587 }
588}
589
590bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
591 // If already a constant, there is nothing to compute.
592 if (isa<Constant>(Val))
593 return true;
594
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000595 return hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000596}
597
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000598LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000599 // If already a constant, there is nothing to compute.
600 if (Constant *VC = dyn_cast<Constant>(Val))
601 return LVILatticeVal::get(VC);
602
Benjamin Kramer36647082011-12-03 15:16:45 +0000603 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000604 return getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000605}
606
Philip Reameseb3e9da2015-10-29 03:57:17 +0000607static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
608 switch (BBI->getOpcode()) {
609 default: break;
610 case Instruction::Load:
611 case Instruction::Call:
612 case Instruction::Invoke:
613 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000614 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000615 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000616 }
617 break;
618 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000619 // Nothing known - will be intersected with other facts
620 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000621}
622
Nick Lewycky55a700b2010-12-18 01:00:40 +0000623bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
624 if (isa<Constant>(Val))
625 return true;
626
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000627 if (hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000628 // If we have a cached value, use that.
629 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000630 << "' val=" << getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000631
Hans Wennborg45172ac2014-11-25 17:23:05 +0000632 // Since we're reusing a cached value, we don't need to update the
633 // OverDefinedCache. The cache will have been properly updated whenever the
634 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000635 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000636 }
637
Hans Wennborg45172ac2014-11-25 17:23:05 +0000638 // Hold off inserting this value into the Cache in case we have to return
639 // false and come back later.
640 LVILatticeVal Res;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000641
Chris Lattneraf025d32009-11-15 19:59:49 +0000642 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000643 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000644 if (!solveBlockValueNonLocal(Res, Val, BB))
645 return false;
646 insertResult(Val, BB, Res);
647 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000648 }
Chris Lattner2c708562009-11-15 20:00:52 +0000649
Nick Lewycky55a700b2010-12-18 01:00:40 +0000650 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000651 if (!solveBlockValuePHINode(Res, PN, BB))
652 return false;
653 insertResult(Val, BB, Res);
654 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000655 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000656
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000657 if (auto *SI = dyn_cast<SelectInst>(BBI)) {
658 if (!solveBlockValueSelect(Res, SI, BB))
659 return false;
660 insertResult(Val, BB, Res);
661 return true;
662 }
663
Igor Laevsky0fa48192015-09-18 13:01:48 +0000664 // If this value is a nonnull pointer, record it's range and bailout.
665 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
666 if (PT && isKnownNonNull(BBI)) {
667 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000668 insertResult(Val, BB, Res);
669 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000670 }
671
Philip Reamesd1f829d2016-02-02 21:57:37 +0000672 // If this is an instruction which supports range metadata, intersect the
673 // implied range.
674 Res = intersect(Res, getFromRangeMetadata(BBI));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000675
Owen Anderson80d19f02010-08-18 21:11:37 +0000676 // We can only analyze the definitions of certain classes of instructions
677 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000678 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000679 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
680 !BBI->getType()->isIntegerTy()) {
681 DEBUG(dbgs() << " compute BB '" << BB->getName()
682 << "' - overdefined because inst def found.\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000683 Res.markOverdefined();
684 insertResult(Val, BB, Res);
685 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000686 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000687
Owen Anderson80d19f02010-08-18 21:11:37 +0000688 // FIXME: We're currently limited to binops with a constant RHS. This should
689 // be improved.
690 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
691 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
692 DEBUG(dbgs() << " compute BB '" << BB->getName()
693 << "' - overdefined because inst def found.\n");
694
Hans Wennborg45172ac2014-11-25 17:23:05 +0000695 Res.markOverdefined();
696 insertResult(Val, BB, Res);
697 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000698 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000699
Hans Wennborg45172ac2014-11-25 17:23:05 +0000700 if (!solveBlockValueConstantRange(Res, BBI, BB))
701 return false;
702 insertResult(Val, BB, Res);
703 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000704}
705
706static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
707 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
708 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000709 GetUnderlyingObject(L->getPointerOperand(),
710 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000711 }
712 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
713 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000714 GetUnderlyingObject(S->getPointerOperand(),
715 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000716 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000717 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
718 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000719
720 // FIXME: check whether it has a valuerange that excludes zero?
721 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
722 if (!Len || Len->isZero()) return false;
723
Eli Friedman7a5fc692011-05-31 20:40:16 +0000724 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000725 if (GetUnderlyingObject(MI->getRawDest(),
726 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000727 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000728 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000729 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000730 if (GetUnderlyingObject(MTI->getRawSource(),
731 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000732 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000733 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000734 return false;
735}
736
Owen Anderson64c2c572010-12-20 18:18:16 +0000737bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
738 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000739 LVILatticeVal Result; // Start Undefined.
740
741 // If this is a pointer, and there's a load from that pointer in this BB,
742 // then we know that the pointer can't be NULL.
743 bool NotNull = false;
744 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000745 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000746 NotNull = true;
747 } else {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000748 const DataLayout &DL = BB->getModule()->getDataLayout();
749 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000750 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
751 // inside InstructionDereferencesPointer either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000752 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000753 for (Instruction &I : *BB) {
754 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000755 NotNull = true;
756 break;
757 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000758 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000759 }
760 }
761 }
762
763 // If this is the entry block, we must be asking about an argument. The
764 // value is overdefined.
765 if (BB == &BB->getParent()->getEntryBlock()) {
766 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
767 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000768 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000769 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
770 } else {
771 Result.markOverdefined();
772 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000773 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000774 return true;
775 }
776
777 // Loop over all of our predecessors, merging what we know from them into
778 // result.
779 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000780 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000781 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000782 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000783 if (EdgesMissing)
784 continue;
785
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000786 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000787
788 // If we hit overdefined, exit early. The BlockVals entry is already set
789 // to overdefined.
790 if (Result.isOverdefined()) {
791 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000792 << "' - overdefined because of pred (non local).\n");
Nick Lewycky55a700b2010-12-18 01:00:40 +0000793 // If we previously determined that this is a pointer that can't be null
794 // then return that rather than giving up entirely.
795 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000796 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000797 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
798 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000799
Owen Anderson64c2c572010-12-20 18:18:16 +0000800 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000801 return true;
802 }
803 }
804 if (EdgesMissing)
805 return false;
806
807 // Return the merged value, which is more precise than 'overdefined'.
808 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000809 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000810 return true;
811}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000812
Owen Anderson64c2c572010-12-20 18:18:16 +0000813bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
814 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000815 LVILatticeVal Result; // Start Undefined.
816
817 // Loop over all of our predecessors, merging what we know from them into
818 // result.
819 bool EdgesMissing = false;
820 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
821 BasicBlock *PhiBB = PN->getIncomingBlock(i);
822 Value *PhiVal = PN->getIncomingValue(i);
823 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000824 // Note that we can provide PN as the context value to getEdgeValue, even
825 // though the results will be cached, because PN is the value being used as
826 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000827 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000828 if (EdgesMissing)
829 continue;
830
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000831 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000832
833 // If we hit overdefined, exit early. The BlockVals entry is already set
834 // to overdefined.
835 if (Result.isOverdefined()) {
836 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000837 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000838
Owen Anderson64c2c572010-12-20 18:18:16 +0000839 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000840 return true;
841 }
842 }
843 if (EdgesMissing)
844 return false;
845
846 // Return the merged value, which is more precise than 'overdefined'.
847 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000848 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000849 return true;
850}
851
Hal Finkel7e184492014-09-07 20:29:59 +0000852static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
853 LVILatticeVal &Result,
854 bool isTrueDest = true);
855
Philip Reamesd1f829d2016-02-02 21:57:37 +0000856// If we can determine a constraint on the value given conditions assumed by
857// the program, intersect those constraints with BBLV
858void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000859 LVILatticeVal &BBLV,
860 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000861 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
862 if (!BBI)
863 return;
864
Chandler Carruth66b31302015-01-04 12:03:27 +0000865 for (auto &AssumeVH : AC->assumptions()) {
866 if (!AssumeVH)
867 continue;
868 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000869 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000870 continue;
871
872 Value *C = I->getArgOperand(0);
873 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
874 LVILatticeVal Result;
Philip Reamesd1f829d2016-02-02 21:57:37 +0000875 if (getValueFromFromCondition(Val, ICI, Result))
876 BBLV = intersect(BBLV, Result);
Hal Finkel7e184492014-09-07 20:29:59 +0000877 }
878 }
879}
880
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000881bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
882 SelectInst *SI, BasicBlock *BB) {
883
884 // Recurse on our inputs if needed
885 if (!hasBlockValue(SI->getTrueValue(), BB)) {
886 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
887 return false;
888 BBLV.markOverdefined();
889 return true;
890 }
891 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
892 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
893 // extra slots in the table if we can.
894 if (TrueVal.isOverdefined()) {
895 BBLV.markOverdefined();
896 return true;
897 }
898
899 if (!hasBlockValue(SI->getFalseValue(), BB)) {
900 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
901 return false;
902 BBLV.markOverdefined();
903 return true;
904 }
905 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
906 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
907 // extra slots in the table if we can.
908 if (FalseVal.isOverdefined()) {
909 BBLV.markOverdefined();
910 return true;
911 }
912
Philip Reames854a84c2016-02-12 00:09:18 +0000913 // Can we constrain the facts about the true and false values by using the
914 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
915 // TODO: We could potentially refine an overdefined true value above.
916 if (auto *ICI = dyn_cast<ICmpInst>(SI->getCondition())) {
917 LVILatticeVal TrueValTaken, FalseValTaken;
918 if (!getValueFromFromCondition(SI->getTrueValue(), ICI,
919 TrueValTaken, true))
920 TrueValTaken.markOverdefined();
921 if (!getValueFromFromCondition(SI->getFalseValue(), ICI,
922 FalseValTaken, false))
923 FalseValTaken.markOverdefined();
924
925 TrueVal = intersect(TrueVal, TrueValTaken);
926 FalseVal = intersect(FalseVal, FalseValTaken);
927 }
928
929 // TODO: handle idioms like min & max where we can use a more precise merge
930 // when our inputs are constant ranges.
931
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000932 LVILatticeVal Result; // Start Undefined.
933 Result.mergeIn(TrueVal, DL);
934 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000935 BBLV = Result;
936 return true;
937}
938
Owen Anderson64c2c572010-12-20 18:18:16 +0000939bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
940 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000941 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000942 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000943 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000944 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
945 return false;
946 BBLV.markOverdefined();
947 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000948 }
949
Nick Lewycky55a700b2010-12-18 01:00:40 +0000950 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +0000951 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000952 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000953 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000954 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000955 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000956
Owen Anderson80d19f02010-08-18 21:11:37 +0000957 ConstantRange LHSRange = LHSVal.getConstantRange();
958 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000959 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000960 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000961 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
962 RHSRange = ConstantRange(RHS->getValue());
963 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000964 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000965 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000966 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000967 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000968
Owen Anderson80d19f02010-08-18 21:11:37 +0000969 // NOTE: We're currently limited by the set of operations that ConstantRange
970 // can evaluate symbolically. Enhancing that set will allows us to analyze
971 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000972 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000973 switch (BBI->getOpcode()) {
974 case Instruction::Add:
975 Result.markConstantRange(LHSRange.add(RHSRange));
976 break;
977 case Instruction::Sub:
978 Result.markConstantRange(LHSRange.sub(RHSRange));
979 break;
980 case Instruction::Mul:
981 Result.markConstantRange(LHSRange.multiply(RHSRange));
982 break;
983 case Instruction::UDiv:
984 Result.markConstantRange(LHSRange.udiv(RHSRange));
985 break;
986 case Instruction::Shl:
987 Result.markConstantRange(LHSRange.shl(RHSRange));
988 break;
989 case Instruction::LShr:
990 Result.markConstantRange(LHSRange.lshr(RHSRange));
991 break;
992 case Instruction::Trunc:
993 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
994 break;
995 case Instruction::SExt:
996 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
997 break;
998 case Instruction::ZExt:
999 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
1000 break;
1001 case Instruction::BitCast:
1002 Result.markConstantRange(LHSRange);
1003 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +00001004 case Instruction::And:
1005 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
1006 break;
1007 case Instruction::Or:
1008 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
1009 break;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001010
Owen Anderson80d19f02010-08-18 21:11:37 +00001011 // Unhandled instructions are overdefined.
1012 default:
1013 DEBUG(dbgs() << " compute BB '" << BB->getName()
1014 << "' - overdefined because inst def found.\n");
1015 Result.markOverdefined();
1016 break;
1017 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001018
Owen Anderson64c2c572010-12-20 18:18:16 +00001019 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +00001020 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001021}
1022
Hal Finkel7e184492014-09-07 20:29:59 +00001023bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
1024 LVILatticeVal &Result, bool isTrueDest) {
1025 if (ICI && isa<Constant>(ICI->getOperand(1))) {
1026 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
1027 // We know that V has the RHS constant if this is a true SETEQ or
1028 // false SETNE.
1029 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
1030 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
1031 else
1032 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
1033 return true;
1034 }
1035
1036 // Recognize the range checking idiom that InstCombine produces.
1037 // (X-C1) u< C2 --> [C1, C1+C2)
1038 ConstantInt *NegOffset = nullptr;
1039 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
1040 match(ICI->getOperand(0), m_Add(m_Specific(Val),
1041 m_ConstantInt(NegOffset)));
1042
1043 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
1044 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Sanjoy Das7182d362015-03-18 00:41:24 +00001045 // Calculate the range of values that are allowed by the comparison
Hal Finkel7e184492014-09-07 20:29:59 +00001046 ConstantRange CmpRange(CI->getValue());
1047 ConstantRange TrueValues =
Sanjoy Das7182d362015-03-18 00:41:24 +00001048 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
Hal Finkel7e184492014-09-07 20:29:59 +00001049
1050 if (NegOffset) // Apply the offset from above.
1051 TrueValues = TrueValues.subtract(NegOffset->getValue());
1052
1053 // If we're interested in the false dest, invert the condition.
1054 if (!isTrueDest) TrueValues = TrueValues.inverse();
1055
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001056 Result = LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001057 return true;
1058 }
1059 }
1060
1061 return false;
1062}
1063
Nuno Lopese6e04902012-06-28 01:16:18 +00001064/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001065/// Val is not constrained on the edge. Result is unspecified if return value
1066/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001067static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1068 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001069 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001070 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001071 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1072 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001073 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001074 if (BI->isConditional() &&
1075 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1076 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1077 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1078 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001079
Chris Lattner19019ea2009-11-11 22:48:44 +00001080 // If V is the condition of the branch itself, then we know exactly what
1081 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001082 if (BI->getCondition() == Val) {
1083 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001084 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001085 return true;
1086 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001087
Chris Lattner19019ea2009-11-11 22:48:44 +00001088 // If the condition of the branch is an equality comparison, we may be
1089 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +00001090 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
1091 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
1092 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001093 }
1094 }
Chris Lattner77358782009-11-15 20:02:12 +00001095
1096 // If the edge was formed by a switch on the value, then we may know exactly
1097 // what it is.
1098 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001099 if (SI->getCondition() != Val)
1100 return false;
1101
1102 bool DefaultCase = SI->getDefaultDest() == BBTo;
1103 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1104 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1105
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001106 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001107 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001108 if (DefaultCase) {
1109 // It is possible that the default destination is the destination of
1110 // some cases. There is no need to perform difference for those cases.
1111 if (i.getCaseSuccessor() != BBTo)
1112 EdgesVals = EdgesVals.difference(EdgeVal);
1113 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001114 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001115 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001116 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001117 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001118 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001119 return false;
1120}
1121
Sanjay Patel938e2792015-01-09 16:35:37 +00001122/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1123/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +00001124bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001125 BasicBlock *BBTo, LVILatticeVal &Result,
1126 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001127 // If already a constant, there is nothing to compute.
1128 if (Constant *VC = dyn_cast<Constant>(Val)) {
1129 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001130 return true;
1131 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001132
Philip Reames44456b82016-02-02 03:15:40 +00001133 LVILatticeVal LocalResult;
1134 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1135 // If we couldn't constrain the value on the edge, LocalResult doesn't
1136 // provide any information.
1137 LocalResult.markOverdefined();
1138
1139 if (hasSingleValue(LocalResult)) {
1140 // Can't get any more precise here
1141 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001142 return true;
1143 }
1144
1145 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001146 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1147 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001148 // No new information.
1149 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001150 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001151 }
1152
Philip Reames44456b82016-02-02 03:15:40 +00001153 // Try to intersect ranges of the BB and the constraint on the edge.
1154 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001155 intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001156 // We can use the context instruction (generically the ultimate instruction
1157 // the calling pass is trying to simplify) here, even though the result of
1158 // this function is generally cached when called from the solve* functions
1159 // (and that cached result might be used with queries using a different
1160 // context instruction), because when this function is called from the solve*
1161 // functions, the context instruction is not provided. When called from
1162 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1163 // but then the result is not cached.
Philip Reamesd1f829d2016-02-02 21:57:37 +00001164 intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001165
1166 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001167 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001168}
1169
Hal Finkel7e184492014-09-07 20:29:59 +00001170LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1171 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001172 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001173 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001174
Hans Wennborg45172ac2014-11-25 17:23:05 +00001175 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001176 if (!hasBlockValue(V, BB)) {
1177 pushBlockValue(std::make_pair(BB, V));
1178 solve();
1179 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001180 LVILatticeVal Result = getBlockValue(V, BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001181 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001182
1183 DEBUG(dbgs() << " Result = " << Result << "\n");
1184 return Result;
1185}
1186
1187LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1188 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1189 << CxtI->getName() << "'\n");
1190
Philip Reamesbb781b42016-02-10 21:46:32 +00001191 if (auto *C = dyn_cast<Constant>(V))
1192 return LVILatticeVal::get(C);
1193
Philip Reamesd1f829d2016-02-02 21:57:37 +00001194 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001195 if (auto *I = dyn_cast<Instruction>(V))
1196 Result = getFromRangeMetadata(I);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001197 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001198
David Greene37e98092009-12-23 20:43:58 +00001199 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001200 return Result;
1201}
Chris Lattner19019ea2009-11-11 22:48:44 +00001202
Chris Lattneraf025d32009-11-15 19:59:49 +00001203LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001204getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1205 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001206 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001207 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001208
Nick Lewycky55a700b2010-12-18 01:00:40 +00001209 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001210 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001211 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001212 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001213 (void)WasFastQuery;
1214 assert(WasFastQuery && "More work to do after problem solved?");
1215 }
1216
David Greene37e98092009-12-23 20:43:58 +00001217 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001218 return Result;
1219}
1220
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001221void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1222 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001223 // When an edge in the graph has been threaded, values that we could not
1224 // determine a value for before (i.e. were marked overdefined) may be
1225 // possible to solve now. We do NOT try to proactively update these values.
1226 // Instead, we clear their entries from the cache, and allow lazy updating to
1227 // recompute them when needed.
1228
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001229 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001230 // for all values that were marked overdefined in OldSucc, and for those same
1231 // values in any successor of OldSucc (except NewSucc) in which they were
1232 // also marked overdefined.
1233 std::vector<BasicBlock*> worklist;
1234 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001235
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001236 auto I = OverDefinedCache.find(OldSucc);
1237 if (I == OverDefinedCache.end())
1238 return; // Nothing to process here.
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001239 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001240
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001241 // Use a worklist to perform a depth-first search of OldSucc's successors.
1242 // NOTE: We do not need a visited list since any blocks we have already
1243 // visited will have had their overdefined markers cleared already, and we
1244 // thus won't loop to their successors.
1245 while (!worklist.empty()) {
1246 BasicBlock *ToUpdate = worklist.back();
1247 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001248
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001249 // Skip blocks only accessible through NewSucc.
1250 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001251
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001252 bool changed = false;
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001253 for (Value *V : ValsToClear) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001254 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001255 auto OI = OverDefinedCache.find(ToUpdate);
1256 if (OI == OverDefinedCache.end())
1257 continue;
1258 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1259 if (!ValueSet.count(V))
1260 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001261
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001262 ValueSet.erase(V);
1263 if (ValueSet.empty())
1264 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001265
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001266 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001267 // blocks successors too.
1268 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001269 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001270
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001271 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001272
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001273 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1274 }
1275}
1276
Chris Lattneraf025d32009-11-15 19:59:49 +00001277//===----------------------------------------------------------------------===//
1278// LazyValueInfo Impl
1279//===----------------------------------------------------------------------===//
1280
Sanjay Patel2a385e22015-01-09 16:47:20 +00001281/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001282static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001283 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001284 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001285 if (!PImpl) {
1286 assert(DL && "getCache() called with a null DataLayout");
1287 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1288 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001289 return *static_cast<LazyValueInfoCache*>(PImpl);
1290}
1291
Owen Anderson208636f2010-08-18 18:39:01 +00001292bool LazyValueInfo::runOnFunction(Function &F) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001293 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001294 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001295
1296 DominatorTreeWrapperPass *DTWP =
1297 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1298 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001299
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001300 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001301
Hal Finkel7e184492014-09-07 20:29:59 +00001302 if (PImpl)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001303 getCache(PImpl, AC, &DL, DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001304
Owen Anderson208636f2010-08-18 18:39:01 +00001305 // Fully lazy.
1306 return false;
1307}
1308
Chad Rosier43a33062011-12-02 01:26:24 +00001309void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1310 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001311 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001312 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001313}
1314
Chris Lattneraf025d32009-11-15 19:59:49 +00001315void LazyValueInfo::releaseMemory() {
1316 // If the cache was allocated, free it.
1317 if (PImpl) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001318 delete &getCache(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001319 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001320 }
1321}
1322
Hal Finkel7e184492014-09-07 20:29:59 +00001323Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1324 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001325 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001326 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001327 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001328
Chris Lattner19019ea2009-11-11 22:48:44 +00001329 if (Result.isConstant())
1330 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001331 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001332 ConstantRange CR = Result.getConstantRange();
1333 if (const APInt *SingleVal = CR.getSingleElement())
1334 return ConstantInt::get(V->getContext(), *SingleVal);
1335 }
Craig Topper9f008862014-04-15 04:59:12 +00001336 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001337}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001338
Sanjay Patel2a385e22015-01-09 16:47:20 +00001339/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001340/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001341Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001342 BasicBlock *ToBB,
1343 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001344 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001345 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001346 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001347
Chris Lattnerd5e25432009-11-12 01:29:10 +00001348 if (Result.isConstant())
1349 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001350 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001351 ConstantRange CR = Result.getConstantRange();
1352 if (const APInt *SingleVal = CR.getSingleElement())
1353 return ConstantInt::get(V->getContext(), *SingleVal);
1354 }
Craig Topper9f008862014-04-15 04:59:12 +00001355 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001356}
1357
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001358static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1359 LVILatticeVal &Result,
1360 const DataLayout &DL,
1361 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001362
Chris Lattner565ee2f2009-11-12 04:36:58 +00001363 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001364 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001365 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001366 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001367 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001368 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001369 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1370 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001371 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001372
Owen Anderson185fe002010-08-10 20:03:09 +00001373 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001374 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001375 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001376
Owen Anderson185fe002010-08-10 20:03:09 +00001377 ConstantRange CR = Result.getConstantRange();
1378 if (Pred == ICmpInst::ICMP_EQ) {
1379 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001380 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001381
Owen Anderson185fe002010-08-10 20:03:09 +00001382 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001383 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001384 } else if (Pred == ICmpInst::ICMP_NE) {
1385 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001386 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001387
Owen Anderson185fe002010-08-10 20:03:09 +00001388 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001389 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001390 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001391
Owen Anderson185fe002010-08-10 20:03:09 +00001392 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001393 ConstantRange TrueValues =
1394 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1395 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001396 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001397 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001398 return LazyValueInfo::False;
1399 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001400 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001401
Chris Lattneraf025d32009-11-15 19:59:49 +00001402 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001403 // If this is an equality comparison, we can try to fold it knowing that
1404 // "V != C1".
1405 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001406 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001407 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001408 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001409 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001410 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001411 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001412 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001413 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001414 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001415 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001416 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001417 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001418 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001419 }
Hal Finkel7e184492014-09-07 20:29:59 +00001420 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001421 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001422
Hal Finkel7e184492014-09-07 20:29:59 +00001423 return LazyValueInfo::Unknown;
1424}
1425
Sanjay Patel2a385e22015-01-09 16:47:20 +00001426/// Determine whether the specified value comparison with a constant is known to
1427/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001428LazyValueInfo::Tristate
1429LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1430 BasicBlock *FromBB, BasicBlock *ToBB,
1431 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001432 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001433 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001434 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001435
1436 return getPredicateResult(Pred, C, Result, DL, TLI);
1437}
1438
1439LazyValueInfo::Tristate
1440LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1441 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001442 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1443 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001444 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1445 if (Ret != Unknown)
1446 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001447
Philip Reamesaeefae02015-11-04 01:47:04 +00001448 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1449 // LVI as a whole tries to compute a lattice value which is conservatively
1450 // correct at a given location. In this case, we have a predicate which we
1451 // weren't able to prove about the merged result, and we're pushing that
1452 // predicate back along each incoming edge to see if we can prove it
1453 // separately for each input. As a motivating example, consider:
1454 // bb1:
1455 // %v1 = ... ; constantrange<1, 5>
1456 // br label %merge
1457 // bb2:
1458 // %v2 = ... ; constantrange<10, 20>
1459 // br label %merge
1460 // merge:
1461 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1462 // %pred = icmp eq i32 %phi, 8
1463 // We can't tell from the lattice value for '%phi' that '%pred' is false
1464 // along each path, but by checking the predicate over each input separately,
1465 // we can.
1466 // We limit the search to one step backwards from the current BB and value.
1467 // We could consider extending this to search further backwards through the
1468 // CFG and/or value graph, but there are non-obvious compile time vs quality
1469 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001470 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001471 BasicBlock *BB = CxtI->getParent();
1472
1473 // Function entry or an unreachable block. Bail to avoid confusing
1474 // analysis below.
1475 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1476 if (PI == PE)
1477 return Unknown;
1478
1479 // If V is a PHI node in the same block as the context, we need to ask
1480 // questions about the predicate as applied to the incoming value along
1481 // each edge. This is useful for eliminating cases where the predicate is
1482 // known along all incoming edges.
1483 if (auto *PHI = dyn_cast<PHINode>(V))
1484 if (PHI->getParent() == BB) {
1485 Tristate Baseline = Unknown;
1486 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1487 Value *Incoming = PHI->getIncomingValue(i);
1488 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1489 // Note that PredBB may be BB itself.
1490 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1491 CxtI);
1492
1493 // Keep going as long as we've seen a consistent known result for
1494 // all inputs.
1495 Baseline = (i == 0) ? Result /* First iteration */
1496 : (Baseline == Result ? Baseline : Unknown); /* All others */
1497 if (Baseline == Unknown)
1498 break;
1499 }
1500 if (Baseline != Unknown)
1501 return Baseline;
1502 }
1503
Philip Reames66ab0f02015-06-16 00:49:59 +00001504 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001505 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001506 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001507 if (!isa<Instruction>(V) ||
1508 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001509 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001510 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001511 // the value of the comparison in this block.
1512 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1513 if (Baseline != Unknown) {
1514 // Check that all remaining incoming values match the first one.
1515 while (++PI != PE) {
1516 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1517 if (Ret != Baseline) break;
1518 }
1519 // If we terminated early, then one of the values didn't match.
1520 if (PI == PE) {
1521 return Baseline;
1522 }
1523 }
1524 }
1525 }
1526 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001527}
1528
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001529void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001530 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001531 if (PImpl) {
1532 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1533 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1534 }
Owen Anderson208636f2010-08-18 18:39:01 +00001535}
1536
1537void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001538 if (PImpl) {
1539 const DataLayout &DL = BB->getModule()->getDataLayout();
1540 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1541 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001542}