blob: 4d09b7ca006b8920d22072a67457d27fdf19dad2 [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
Sean Silva687019f2016-06-13 22:01:25 +000041char LazyValueInfoWrapperPass::ID = 0;
42INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000043 "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)
Sean Silva687019f2016-06-13 22:01:25 +000046INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "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 {
Sean Silva687019f2016-06-13 22:01:25 +000050 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000051}
52
Sean Silva687019f2016-06-13 22:01:25 +000053char LazyValueAnalysis::PassID;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000054
55//===----------------------------------------------------------------------===//
56// LVILatticeVal
57//===----------------------------------------------------------------------===//
58
Sanjay Patel2a385e22015-01-09 16:47:20 +000059/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000060///
61/// FIXME: This is basically just for bringup, this can be made a lot more rich
62/// in the future.
63///
64namespace {
65class LVILatticeVal {
66 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000067 /// This Value has no known value yet. As a result, this implies the
68 /// producing instruction is dead. Caution: We use this as the starting
69 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000070 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000071 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000072
Philip Reames3bb28322016-04-25 18:48:43 +000073 /// This Value has a specific constant value. (For integers, constantrange
74 /// is used instead.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000075 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000076
Philip Reames3bb28322016-04-25 18:48:43 +000077 /// This Value is known to not have the specified value. (For integers,
78 /// constantrange is used instead.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000079 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000080
Philip Reames3bb28322016-04-25 18:48:43 +000081 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000082 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000083
Philip Reames3bb28322016-04-25 18:48:43 +000084 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000085 overdefined
86 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000087
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000088 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000089 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000090 LatticeValueTy Tag;
91 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000092 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000093
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000094public:
Craig Topper9f008862014-04-15 04:59:12 +000095 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000096
Chris Lattner19019ea2009-11-11 22:48:44 +000097 static LVILatticeVal get(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.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000101 return Res;
102 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000103 static LVILatticeVal getNot(Constant *C) {
104 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000105 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000106 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000107 return Res;
108 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000109 static LVILatticeVal getRange(ConstantRange CR) {
110 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000111 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000112 return Res;
113 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000114 static LVILatticeVal getOverdefined() {
115 LVILatticeVal Res;
116 Res.markOverdefined();
117 return Res;
118 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000119
Owen Anderson0f306a42010-08-05 22:59:19 +0000120 bool isUndefined() const { return Tag == undefined; }
121 bool isConstant() const { return Tag == constant; }
122 bool isNotConstant() const { return Tag == notconstant; }
123 bool isConstantRange() const { return Tag == constantrange; }
124 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000125
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000126 Constant *getConstant() const {
127 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000128 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000129 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000130
Chris Lattner565ee2f2009-11-12 04:36:58 +0000131 Constant *getNotConstant() const {
132 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000133 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000134 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000135
Owen Anderson0f306a42010-08-05 22:59:19 +0000136 ConstantRange getConstantRange() const {
137 assert(isConstantRange() &&
138 "Cannot get the constant-range of a non-constant-range!");
139 return Range;
140 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000141
Sanjay Patel2a385e22015-01-09 16:47:20 +0000142 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000143 bool markOverdefined() {
144 if (isOverdefined())
145 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000146 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000147 return true;
148 }
149
Sanjay Patel2a385e22015-01-09 16:47:20 +0000150 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000151 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000152 assert(V && "Marking constant with NULL");
153 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154 return markConstantRange(ConstantRange(CI->getValue()));
155 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000156 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000157
158 assert((!isConstant() || getConstant() == V) &&
159 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000160 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000161 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000162 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000163 return true;
164 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000165
Sanjay Patel2a385e22015-01-09 16:47:20 +0000166 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000167 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000168 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000169 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
170 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
171 if (isa<UndefValue>(V))
172 return false;
173
174 assert((!isConstant() || getConstant() != V) &&
175 "Marking constant !constant with same value");
176 assert((!isNotConstant() || getNotConstant() == V) &&
177 "Marking !constant with different value");
178 assert(isUndefined() || isConstant());
179 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000180 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000181 return true;
182 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000183
Sanjay Patel2a385e22015-01-09 16:47:20 +0000184 /// Return true if this is a change in status.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000185 bool markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000186 if (isConstantRange()) {
187 if (NewR.isEmptySet())
188 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000189
Nuno Lopese6e04902012-06-28 01:16:18 +0000190 bool changed = Range != NewR;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000191 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000192 return changed;
193 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000194
Owen Anderson0f306a42010-08-05 22:59:19 +0000195 assert(isUndefined());
196 if (NewR.isEmptySet())
197 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000198
Owen Anderson0f306a42010-08-05 22:59:19 +0000199 Tag = constantrange;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000200 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000201 return true;
202 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000203
Sanjay Patel2a385e22015-01-09 16:47:20 +0000204 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000205 /// one and returning true if anything changed.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000206 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
Chris Lattner19019ea2009-11-11 22:48:44 +0000207 if (RHS.isUndefined() || isOverdefined()) return false;
208 if (RHS.isOverdefined()) return markOverdefined();
209
Nick Lewycky11678bd2010-12-15 18:57:18 +0000210 if (isUndefined()) {
211 Tag = RHS.Tag;
212 Val = RHS.Val;
213 Range = RHS.Range;
214 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000215 }
216
Nick Lewycky11678bd2010-12-15 18:57:18 +0000217 if (isConstant()) {
218 if (RHS.isConstant()) {
219 if (Val == RHS.Val)
220 return false;
221 return markOverdefined();
222 }
223
224 if (RHS.isNotConstant()) {
225 if (Val == RHS.Val)
226 return markOverdefined();
227
228 // Unless we can prove that the two Constants are different, we must
229 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000230 if (ConstantInt *Res =
231 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
232 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000233 if (Res->isOne())
234 return markNotConstant(RHS.getNotConstant());
235
236 return markOverdefined();
237 }
238
Chris Lattner19019ea2009-11-11 22:48:44 +0000239 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000240 }
241
242 if (isNotConstant()) {
243 if (RHS.isConstant()) {
244 if (Val == RHS.Val)
245 return markOverdefined();
246
247 // Unless we can prove that the two Constants are different, we must
248 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000249 if (ConstantInt *Res =
250 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
251 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000252 if (Res->isOne())
253 return false;
254
255 return markOverdefined();
256 }
257
258 if (RHS.isNotConstant()) {
259 if (Val == RHS.Val)
260 return false;
261 return markOverdefined();
262 }
263
264 return markOverdefined();
265 }
266
267 assert(isConstantRange() && "New LVILattice type?");
268 if (!RHS.isConstantRange())
269 return markOverdefined();
270
271 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
272 if (NewR.isFullSet())
273 return markOverdefined();
274 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000275 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000276};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000277
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000278} // end anonymous namespace.
279
Chris Lattner19019ea2009-11-11 22:48:44 +0000280namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000281raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
282 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000283raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
284 if (Val.isUndefined())
285 return OS << "undefined";
286 if (Val.isOverdefined())
287 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000288
289 if (Val.isNotConstant())
290 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000291 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000292 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
293 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000294 return OS << "constant<" << *Val.getConstant() << '>';
295}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000296}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000297
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000298/// Returns true if this lattice value represents at most one possible value.
299/// This is as precise as any lattice value can get while still representing
300/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000301static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000302 if (Val.isConstantRange() &&
303 Val.getConstantRange().isSingleElement())
304 // Integer constants are single element ranges
305 return true;
306 if (Val.isConstant())
307 // Non integer constants
308 return true;
309 return false;
310}
311
312/// Combine two sets of facts about the same value into a single set of
313/// facts. Note that this method is not suitable for merging facts along
314/// different paths in a CFG; that's what the mergeIn function is for. This
315/// is for merging facts gathered about the same value at the same location
316/// through two independent means.
317/// Notes:
318/// * This method does not promise to return the most precise possible lattice
319/// value implied by A and B. It is allowed to return any lattice element
320/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000321/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000322/// * Due to unreachable code, the intersection of two lattice values could be
323/// contradictory. If this happens, we return some valid lattice value so as
324/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
325/// we do not make this guarantee. TODO: This would be a useful enhancement.
326static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
327 // Undefined is the strongest state. It means the value is known to be along
328 // an unreachable path.
329 if (A.isUndefined())
330 return A;
331 if (B.isUndefined())
332 return B;
333
334 // If we gave up for one, but got a useable fact from the other, use it.
335 if (A.isOverdefined())
336 return B;
337 if (B.isOverdefined())
338 return A;
339
340 // Can't get any more precise than constants.
341 if (hasSingleValue(A))
342 return A;
343 if (hasSingleValue(B))
344 return B;
345
346 // Could be either constant range or not constant here.
347 if (!A.isConstantRange() || !B.isConstantRange()) {
348 // TODO: Arbitrary choice, could be improved
349 return A;
350 }
351
352 // Intersect two constant ranges
353 ConstantRange Range =
354 A.getConstantRange().intersectWith(B.getConstantRange());
355 // Note: An empty range is implicitly converted to overdefined internally.
356 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000357 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000358 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000359}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000360
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000361//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000362// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000363//===----------------------------------------------------------------------===//
364
Chris Lattneraf025d32009-11-15 19:59:49 +0000365namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000366 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000367 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000368 struct LVIValueHandle final : public CallbackVH {
Owen Anderson118ac802011-01-05 21:15:29 +0000369 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000370
Owen Anderson118ac802011-01-05 21:15:29 +0000371 LVIValueHandle(Value *V, LazyValueInfoCache *P)
372 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000373
374 void deleted() override;
375 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000376 deleted();
377 }
378 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000379}
Owen Anderson118ac802011-01-05 21:15:29 +0000380
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000381namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000382 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000383 /// maintains information about queries across the clients' queries.
384 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000385 /// This is all of the cached block information for exactly one Value*.
386 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000387 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000388 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
389 /// memory overhead.
Bruno Cardoso Lopes1846ea32015-08-18 16:54:36 +0000390 typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
391 ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000392
Sanjay Patel2a385e22015-01-09 16:47:20 +0000393 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000394 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000395 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000396
Sanjay Patel2a385e22015-01-09 16:47:20 +0000397 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000398 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000399 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
400 OverDefinedCacheTy;
401 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000402
Sanjay Patel2a385e22015-01-09 16:47:20 +0000403 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000404 /// don't spend time removing unused blocks from our caches.
405 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
406
Sanjay Patel2a385e22015-01-09 16:47:20 +0000407 /// This stack holds the state of the value solver during a query.
408 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000409 /// recursive value lookup process.
410 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000411
Sanjay Patel2a385e22015-01-09 16:47:20 +0000412 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000413 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
414
Sanjay Patel2a385e22015-01-09 16:47:20 +0000415 /// Push BV onto BlockValueStack unless it's already in there.
416 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000417 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000418 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000419 return false; // It's already in the stack.
420
Philip Reames44456b82016-02-02 03:15:40 +0000421 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
422 << "\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000423 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000424 return true;
425 }
426
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000427 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
428 const DataLayout &DL; ///< A mandatory DataLayout
429 DominatorTree *DT; ///< An optional DT pointer.
430
Owen Anderson118ac802011-01-05 21:15:29 +0000431 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000432
Hans Wennborg45172ac2014-11-25 17:23:05 +0000433 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
434 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000435
436 // Insert over-defined values into their own cache to reduce memory
437 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000438 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000439 OverDefinedCache[BB].insert(Val);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000440 else
441 lookup(Val)[BB] = Result;
Hans Wennborg45172ac2014-11-25 17:23:05 +0000442 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000443
NAKAMURA Takumif4c64412016-07-04 01:26:14 +0000444 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
445 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
446 LVILatticeVal &Result, Instruction *CxtI = nullptr);
447 bool hasBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000448
NAKAMURA Takumif4c64412016-07-04 01:26:14 +0000449 // 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);
453 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
454 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
455 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
456 BasicBlock *BB);
457 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
458 BasicBlock *BB);
459 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
460 BasicBlock *BB);
461 void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
462 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000463
NAKAMURA Takumif4c64412016-07-04 01:26:14 +0000464 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000465
NAKAMURA Takumif4c64412016-07-04 01:26:14 +0000466 ValueCacheEntryTy &lookup(Value *V) {
467 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 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000497
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
Benjamin Krameraa209152016-06-26 17:27:42 +0000563 for (auto &I : ValueCache)
564 I.second.erase(BB);
Owen Anderson208636f2010-08-18 18:39:01 +0000565}
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
Philip Reames2ab964e2016-04-27 01:02:25 +0000664 // If this value is a nonnull pointer, record it's range and bailout. Note
665 // that for all other pointer typed values, we terminate the search at the
666 // definition. We could easily extend this to look through geps, bitcasts,
667 // and the like to prove non-nullness, but it's not clear that's worth it
668 // compile time wise. The context-insensative value walk done inside
669 // isKnownNonNull gets most of the profitable cases at much less expense.
670 // This does mean that we have a sensativity to where the defining
671 // instruction is placed, even if it could legally be hoisted much higher.
672 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000673 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
674 if (PT && isKnownNonNull(BBI)) {
675 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000676 insertResult(Val, BB, Res);
677 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000678 }
Davide Italianobd543d02016-05-25 22:29:34 +0000679 if (BBI->getType()->isIntegerTy()) {
Philip Reames2ab964e2016-04-27 01:02:25 +0000680 if (isa<CastInst>(BBI)) {
681 if (!solveBlockValueCast(Res, BBI, BB))
682 return false;
683 insertResult(Val, BB, Res);
684 return true;
685 }
686 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
687 if (BO && isa<ConstantInt>(BO->getOperand(1))) {
688 if (!solveBlockValueBinaryOp(Res, BBI, BB))
689 return false;
690 insertResult(Val, BB, Res);
691 return true;
692 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000693 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000694
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000695 DEBUG(dbgs() << " compute BB '" << BB->getName()
696 << "' - unknown inst def found.\n");
697 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000698 insertResult(Val, BB, Res);
699 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000700}
701
702static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
703 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
704 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000705 GetUnderlyingObject(L->getPointerOperand(),
706 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000707 }
708 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
709 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000710 GetUnderlyingObject(S->getPointerOperand(),
711 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000712 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000713 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
714 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000715
716 // FIXME: check whether it has a valuerange that excludes zero?
717 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
718 if (!Len || Len->isZero()) return false;
719
Eli Friedman7a5fc692011-05-31 20:40:16 +0000720 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000721 if (GetUnderlyingObject(MI->getRawDest(),
722 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000723 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000724 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000725 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000726 if (GetUnderlyingObject(MTI->getRawSource(),
727 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000728 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000729 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000730 return false;
731}
732
Philip Reames3f83dbe2016-04-27 00:30:55 +0000733/// Return true if the allocation associated with Val is ever dereferenced
734/// within the given basic block. This establishes the fact Val is not null,
735/// but does not imply that the memory at Val is dereferenceable. (Val may
736/// point off the end of the dereferenceable part of the object.)
737static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
738 assert(Val->getType()->isPointerTy());
739
740 const DataLayout &DL = BB->getModule()->getDataLayout();
741 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
742 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
743 // inside InstructionDereferencesPointer either.
744 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
745 for (Instruction &I : *BB)
746 if (InstructionDereferencesPointer(&I, UnderlyingVal))
747 return true;
748 return false;
749}
750
Owen Anderson64c2c572010-12-20 18:18:16 +0000751bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
752 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000753 LVILatticeVal Result; // Start Undefined.
754
Nick Lewycky55a700b2010-12-18 01:00:40 +0000755 // If this is the entry block, we must be asking about an argument. The
756 // value is overdefined.
757 if (BB == &BB->getParent()->getEntryBlock()) {
758 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000759 // Bofore giving up, see if we can prove the pointer non-null local to
760 // this particular block.
761 if (Val->getType()->isPointerTy() &&
762 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000763 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000764 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
765 } else {
766 Result.markOverdefined();
767 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000768 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000769 return true;
770 }
771
772 // Loop over all of our predecessors, merging what we know from them into
773 // result.
774 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000775 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000776 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000777 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000778 if (EdgesMissing)
779 continue;
780
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000781 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000782
783 // If we hit overdefined, exit early. The BlockVals entry is already set
784 // to overdefined.
785 if (Result.isOverdefined()) {
786 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000787 << "' - overdefined because of pred (non local).\n");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000788 // Bofore giving up, see if we can prove the pointer non-null local to
789 // this particular block.
790 if (Val->getType()->isPointerTy() &&
791 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000792 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000793 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
794 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000795
Owen Anderson64c2c572010-12-20 18:18:16 +0000796 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000797 return true;
798 }
799 }
800 if (EdgesMissing)
801 return false;
802
803 // Return the merged value, which is more precise than 'overdefined'.
804 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000805 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000806 return true;
807}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000808
Owen Anderson64c2c572010-12-20 18:18:16 +0000809bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
810 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000811 LVILatticeVal Result; // Start Undefined.
812
813 // Loop over all of our predecessors, merging what we know from them into
814 // result.
815 bool EdgesMissing = false;
816 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
817 BasicBlock *PhiBB = PN->getIncomingBlock(i);
818 Value *PhiVal = PN->getIncomingValue(i);
819 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000820 // Note that we can provide PN as the context value to getEdgeValue, even
821 // though the results will be cached, because PN is the value being used as
822 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000823 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000824 if (EdgesMissing)
825 continue;
826
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000827 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000828
829 // If we hit overdefined, exit early. The BlockVals entry is already set
830 // to overdefined.
831 if (Result.isOverdefined()) {
832 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000833 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000834
Owen Anderson64c2c572010-12-20 18:18:16 +0000835 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000836 return true;
837 }
838 }
839 if (EdgesMissing)
840 return false;
841
842 // Return the merged value, which is more precise than 'overdefined'.
843 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000844 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000845 return true;
846}
847
Hal Finkel7e184492014-09-07 20:29:59 +0000848static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
849 LVILatticeVal &Result,
850 bool isTrueDest = true);
851
Philip Reamesd1f829d2016-02-02 21:57:37 +0000852// If we can determine a constraint on the value given conditions assumed by
853// the program, intersect those constraints with BBLV
854void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000855 LVILatticeVal &BBLV,
856 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000857 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
858 if (!BBI)
859 return;
860
Chandler Carruth66b31302015-01-04 12:03:27 +0000861 for (auto &AssumeVH : AC->assumptions()) {
862 if (!AssumeVH)
863 continue;
864 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000865 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000866 continue;
867
868 Value *C = I->getArgOperand(0);
869 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
870 LVILatticeVal Result;
Philip Reamesd1f829d2016-02-02 21:57:37 +0000871 if (getValueFromFromCondition(Val, ICI, Result))
872 BBLV = intersect(BBLV, Result);
Hal Finkel7e184492014-09-07 20:29:59 +0000873 }
874 }
875}
876
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000877bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
878 SelectInst *SI, BasicBlock *BB) {
879
880 // Recurse on our inputs if needed
881 if (!hasBlockValue(SI->getTrueValue(), BB)) {
882 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
883 return false;
884 BBLV.markOverdefined();
885 return true;
886 }
887 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
888 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
889 // extra slots in the table if we can.
890 if (TrueVal.isOverdefined()) {
891 BBLV.markOverdefined();
892 return true;
893 }
894
895 if (!hasBlockValue(SI->getFalseValue(), BB)) {
896 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
897 return false;
898 BBLV.markOverdefined();
899 return true;
900 }
901 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
902 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
903 // extra slots in the table if we can.
904 if (FalseVal.isOverdefined()) {
905 BBLV.markOverdefined();
906 return true;
907 }
908
Philip Reamesadf0e352016-02-26 22:53:59 +0000909 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
910 ConstantRange TrueCR = TrueVal.getConstantRange();
911 ConstantRange FalseCR = FalseVal.getConstantRange();
912 Value *LHS = nullptr;
913 Value *RHS = nullptr;
914 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
915 // Is this a min specifically of our two inputs? (Avoid the risk of
916 // ValueTracking getting smarter looking back past our immediate inputs.)
917 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
918 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
919 switch (SPR.Flavor) {
920 default:
921 llvm_unreachable("unexpected minmax type!");
922 case SPF_SMIN: /// Signed minimum
923 BBLV.markConstantRange(TrueCR.smin(FalseCR));
924 return true;
925 case SPF_UMIN: /// Unsigned minimum
926 BBLV.markConstantRange(TrueCR.umin(FalseCR));
927 return true;
928 case SPF_SMAX: /// Signed maximum
929 BBLV.markConstantRange(TrueCR.smax(FalseCR));
930 return true;
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000931 case SPF_UMAX: /// Unsigned maximum
Philip Reamesadf0e352016-02-26 22:53:59 +0000932 BBLV.markConstantRange(TrueCR.umax(FalseCR));
933 return true;
934 };
935 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000936
Philip Reamesadf0e352016-02-26 22:53:59 +0000937 // TODO: ABS, NABS from the SelectPatternResult
938 }
939
Philip Reames854a84c2016-02-12 00:09:18 +0000940 // Can we constrain the facts about the true and false values by using the
941 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
942 // TODO: We could potentially refine an overdefined true value above.
943 if (auto *ICI = dyn_cast<ICmpInst>(SI->getCondition())) {
944 LVILatticeVal TrueValTaken, FalseValTaken;
945 if (!getValueFromFromCondition(SI->getTrueValue(), ICI,
946 TrueValTaken, true))
947 TrueValTaken.markOverdefined();
948 if (!getValueFromFromCondition(SI->getFalseValue(), ICI,
949 FalseValTaken, false))
950 FalseValTaken.markOverdefined();
951
952 TrueVal = intersect(TrueVal, TrueValTaken);
953 FalseVal = intersect(FalseVal, FalseValTaken);
Philip Reames854a84c2016-02-12 00:09:18 +0000954
Philip Reamesadf0e352016-02-26 22:53:59 +0000955
956 // Handle clamp idioms such as:
957 // %24 = constantrange<0, 17>
958 // %39 = icmp eq i32 %24, 0
959 // %40 = add i32 %24, -1
960 // %siv.next = select i1 %39, i32 16, i32 %40
961 // %siv.next = constantrange<0, 17> not <-1, 17>
962 // In general, this can handle any clamp idiom which tests the edge
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000963 // condition via an equality or inequality.
Philip Reamesadf0e352016-02-26 22:53:59 +0000964 ICmpInst::Predicate Pred = ICI->getPredicate();
965 Value *A = ICI->getOperand(0);
966 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
967 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
968 assert(A->getType() == B->getType());
969 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
970 };
971 // See if either input is A + C2, subject to the constraint from the
972 // condition that A != C when that input is used. We can assume that
973 // that input doesn't include C + C2.
974 ConstantInt *CIAdded;
975 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +0000976 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +0000977 case ICmpInst::ICMP_EQ:
978 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
979 m_ConstantInt(CIAdded)))) {
980 auto ResNot = addConstants(CIBase, CIAdded);
981 FalseVal = intersect(FalseVal,
982 LVILatticeVal::getNot(ResNot));
983 }
984 break;
985 case ICmpInst::ICMP_NE:
986 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
987 m_ConstantInt(CIAdded)))) {
988 auto ResNot = addConstants(CIBase, CIAdded);
989 TrueVal = intersect(TrueVal,
990 LVILatticeVal::getNot(ResNot));
991 }
992 break;
993 };
994 }
995 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000996
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000997 LVILatticeVal Result; // Start Undefined.
998 Result.mergeIn(TrueVal, DL);
999 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001000 BBLV = Result;
1001 return true;
1002}
1003
Philip Reames66715772016-04-25 18:30:31 +00001004bool LazyValueInfoCache::solveBlockValueCast(LVILatticeVal &BBLV,
1005 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001006 BasicBlock *BB) {
1007 if (!BBI->getOperand(0)->getType()->isSized()) {
1008 // Without knowing how wide the input is, we can't analyze it in any useful
1009 // way.
1010 BBLV.markOverdefined();
1011 return true;
1012 }
Philip Reamesf105db42016-04-26 23:27:33 +00001013
1014 // Filter out casts we don't know how to reason about before attempting to
1015 // recurse on our operand. This can cut a long search short if we know we're
1016 // not going to be able to get any useful information anways.
1017 switch (BBI->getOpcode()) {
1018 case Instruction::Trunc:
1019 case Instruction::SExt:
1020 case Instruction::ZExt:
1021 case Instruction::BitCast:
1022 break;
1023 default:
1024 // Unhandled instructions are overdefined.
1025 DEBUG(dbgs() << " compute BB '" << BB->getName()
1026 << "' - overdefined (unknown cast).\n");
1027 BBLV.markOverdefined();
1028 return true;
1029 }
1030
Philip Reames38c87c22016-04-26 21:48:16 +00001031 // Figure out the range of the LHS. If that fails, we still apply the
1032 // transfer rule on the full set since we may be able to locally infer
1033 // interesting facts.
1034 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001035 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001036 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001037 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001038
1039 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001040 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001041 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1042 if (hasBlockValue(BBI->getOperand(0), BB)) {
1043 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1044 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1045 if (LHSVal.isConstantRange())
1046 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001047 }
1048
Philip Reames38c87c22016-04-26 21:48:16 +00001049 const unsigned ResultBitWidth =
1050 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001051
1052 // NOTE: We're currently limited by the set of operations that ConstantRange
1053 // can evaluate symbolically. Enhancing that set will allows us to analyze
1054 // more definitions.
1055 LVILatticeVal Result;
1056 switch (BBI->getOpcode()) {
1057 case Instruction::Trunc:
Philip Reames38c87c22016-04-26 21:48:16 +00001058 Result.markConstantRange(LHSRange.truncate(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001059 break;
1060 case Instruction::SExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001061 Result.markConstantRange(LHSRange.signExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001062 break;
1063 case Instruction::ZExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001064 Result.markConstantRange(LHSRange.zeroExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001065 break;
1066 case Instruction::BitCast:
1067 Result.markConstantRange(LHSRange);
1068 break;
Philip Reames66715772016-04-25 18:30:31 +00001069 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001070 // Should be dead if the code above is correct
1071 llvm_unreachable("inconsistent with above");
Philip Reames66715772016-04-25 18:30:31 +00001072 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001073 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001074
Philip Reames66715772016-04-25 18:30:31 +00001075 BBLV = Result;
1076 return true;
1077}
1078
1079bool LazyValueInfoCache::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
1080 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001081 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001082
Philip Reames053c2a62016-04-26 23:10:35 +00001083 assert(BBI->getOperand(0)->getType()->isSized() &&
1084 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001085
1086 // Filter out operators we don't know how to reason about before attempting to
1087 // recurse on our operand(s). This can cut a long search short if we know
1088 // we're not going to be able to get any useful information anways.
1089 switch (BBI->getOpcode()) {
1090 case Instruction::Add:
1091 case Instruction::Sub:
1092 case Instruction::Mul:
1093 case Instruction::UDiv:
1094 case Instruction::Shl:
1095 case Instruction::LShr:
1096 case Instruction::And:
1097 case Instruction::Or:
1098 // continue into the code below
1099 break;
1100 default:
1101 // Unhandled instructions are overdefined.
1102 DEBUG(dbgs() << " compute BB '" << BB->getName()
1103 << "' - overdefined (unknown binary operator).\n");
1104 BBLV.markOverdefined();
1105 return true;
1106 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001107
Philip Reames053c2a62016-04-26 23:10:35 +00001108 // Figure out the range of the LHS. If that fails, use a conservative range,
1109 // but apply the transfer rule anyways. This lets us pick up facts from
1110 // expressions like "and i32 (call i32 @foo()), 32"
1111 if (!hasBlockValue(BBI->getOperand(0), BB))
1112 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1113 // More work to do before applying this transfer rule.
1114 return false;
1115
1116 const unsigned OperandBitWidth =
1117 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1118 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1119 if (hasBlockValue(BBI->getOperand(0), BB)) {
1120 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1121 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1122 if (LHSVal.isConstantRange())
1123 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001124 }
Philip Reames66715772016-04-25 18:30:31 +00001125
1126 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1127 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1128
Owen Anderson80d19f02010-08-18 21:11:37 +00001129 // NOTE: We're currently limited by the set of operations that ConstantRange
1130 // can evaluate symbolically. Enhancing that set will allows us to analyze
1131 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +00001132 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +00001133 switch (BBI->getOpcode()) {
1134 case Instruction::Add:
1135 Result.markConstantRange(LHSRange.add(RHSRange));
1136 break;
1137 case Instruction::Sub:
1138 Result.markConstantRange(LHSRange.sub(RHSRange));
1139 break;
1140 case Instruction::Mul:
1141 Result.markConstantRange(LHSRange.multiply(RHSRange));
1142 break;
1143 case Instruction::UDiv:
1144 Result.markConstantRange(LHSRange.udiv(RHSRange));
1145 break;
1146 case Instruction::Shl:
1147 Result.markConstantRange(LHSRange.shl(RHSRange));
1148 break;
1149 case Instruction::LShr:
1150 Result.markConstantRange(LHSRange.lshr(RHSRange));
1151 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +00001152 case Instruction::And:
1153 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
1154 break;
1155 case Instruction::Or:
1156 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
1157 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001158 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001159 // Should be dead if the code above is correct
1160 llvm_unreachable("inconsistent with above");
Owen Anderson80d19f02010-08-18 21:11:37 +00001161 break;
1162 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001163
Owen Anderson64c2c572010-12-20 18:18:16 +00001164 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +00001165 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001166}
1167
Hal Finkel7e184492014-09-07 20:29:59 +00001168bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
1169 LVILatticeVal &Result, bool isTrueDest) {
Philip Reames19183842016-04-25 22:21:24 +00001170 assert(ICI && "precondition");
1171 if (isa<Constant>(ICI->getOperand(1))) {
Hal Finkel7e184492014-09-07 20:29:59 +00001172 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
1173 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001174 // false SETNE.
Hal Finkel7e184492014-09-07 20:29:59 +00001175 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
1176 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
1177 else
1178 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
1179 return true;
1180 }
1181
1182 // Recognize the range checking idiom that InstCombine produces.
1183 // (X-C1) u< C2 --> [C1, C1+C2)
1184 ConstantInt *NegOffset = nullptr;
1185 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
1186 match(ICI->getOperand(0), m_Add(m_Specific(Val),
1187 m_ConstantInt(NegOffset)));
1188
1189 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
1190 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Sanjoy Das7182d362015-03-18 00:41:24 +00001191 // Calculate the range of values that are allowed by the comparison
Hal Finkel7e184492014-09-07 20:29:59 +00001192 ConstantRange CmpRange(CI->getValue());
1193 ConstantRange TrueValues =
Sanjoy Das7182d362015-03-18 00:41:24 +00001194 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
Hal Finkel7e184492014-09-07 20:29:59 +00001195
1196 if (NegOffset) // Apply the offset from above.
1197 TrueValues = TrueValues.subtract(NegOffset->getValue());
1198
1199 // If we're interested in the false dest, invert the condition.
1200 if (!isTrueDest) TrueValues = TrueValues.inverse();
1201
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001202 Result = LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001203 return true;
1204 }
1205 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001206
Hal Finkel7e184492014-09-07 20:29:59 +00001207 return false;
1208}
1209
Nuno Lopese6e04902012-06-28 01:16:18 +00001210/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001211/// Val is not constrained on the edge. Result is unspecified if return value
1212/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001213static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1214 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001215 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001216 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001217 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1218 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001219 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001220 if (BI->isConditional() &&
1221 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1222 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1223 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1224 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001225
Chris Lattner19019ea2009-11-11 22:48:44 +00001226 // If V is the condition of the branch itself, then we know exactly what
1227 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001228 if (BI->getCondition() == Val) {
1229 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001230 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001231 return true;
1232 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001233
Chris Lattner19019ea2009-11-11 22:48:44 +00001234 // If the condition of the branch is an equality comparison, we may be
1235 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +00001236 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
1237 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
1238 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001239 }
1240 }
Chris Lattner77358782009-11-15 20:02:12 +00001241
1242 // If the edge was formed by a switch on the value, then we may know exactly
1243 // what it is.
1244 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001245 if (SI->getCondition() != Val)
1246 return false;
1247
1248 bool DefaultCase = SI->getDefaultDest() == BBTo;
1249 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1250 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1251
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001252 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001253 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001254 if (DefaultCase) {
1255 // It is possible that the default destination is the destination of
1256 // some cases. There is no need to perform difference for those cases.
1257 if (i.getCaseSuccessor() != BBTo)
1258 EdgesVals = EdgesVals.difference(EdgeVal);
1259 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001260 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001261 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001262 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001263 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001264 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001265 return false;
1266}
1267
Sanjay Patel938e2792015-01-09 16:35:37 +00001268/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1269/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +00001270bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001271 BasicBlock *BBTo, LVILatticeVal &Result,
1272 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001273 // If already a constant, there is nothing to compute.
1274 if (Constant *VC = dyn_cast<Constant>(Val)) {
1275 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001276 return true;
1277 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001278
Philip Reames44456b82016-02-02 03:15:40 +00001279 LVILatticeVal LocalResult;
1280 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1281 // If we couldn't constrain the value on the edge, LocalResult doesn't
1282 // provide any information.
1283 LocalResult.markOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001284
Philip Reames44456b82016-02-02 03:15:40 +00001285 if (hasSingleValue(LocalResult)) {
1286 // Can't get any more precise here
1287 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001288 return true;
1289 }
1290
1291 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001292 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1293 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001294 // No new information.
1295 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001296 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001297 }
1298
Philip Reames44456b82016-02-02 03:15:40 +00001299 // Try to intersect ranges of the BB and the constraint on the edge.
1300 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001301 intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001302 // We can use the context instruction (generically the ultimate instruction
1303 // the calling pass is trying to simplify) here, even though the result of
1304 // this function is generally cached when called from the solve* functions
1305 // (and that cached result might be used with queries using a different
1306 // context instruction), because when this function is called from the solve*
1307 // functions, the context instruction is not provided. When called from
1308 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1309 // but then the result is not cached.
Philip Reamesd1f829d2016-02-02 21:57:37 +00001310 intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001311
1312 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001313 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001314}
1315
Hal Finkel7e184492014-09-07 20:29:59 +00001316LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1317 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001318 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001319 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001320
Hans Wennborg45172ac2014-11-25 17:23:05 +00001321 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001322 if (!hasBlockValue(V, BB)) {
1323 pushBlockValue(std::make_pair(BB, V));
1324 solve();
1325 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001326 LVILatticeVal Result = getBlockValue(V, BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001327 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001328
1329 DEBUG(dbgs() << " Result = " << Result << "\n");
1330 return Result;
1331}
1332
1333LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1334 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1335 << CxtI->getName() << "'\n");
1336
Philip Reamesbb781b42016-02-10 21:46:32 +00001337 if (auto *C = dyn_cast<Constant>(V))
1338 return LVILatticeVal::get(C);
1339
Philip Reamesd1f829d2016-02-02 21:57:37 +00001340 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001341 if (auto *I = dyn_cast<Instruction>(V))
1342 Result = getFromRangeMetadata(I);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001343 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001344
David Greene37e98092009-12-23 20:43:58 +00001345 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001346 return Result;
1347}
Chris Lattner19019ea2009-11-11 22:48:44 +00001348
Chris Lattneraf025d32009-11-15 19:59:49 +00001349LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001350getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1351 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001352 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001353 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001354
Nick Lewycky55a700b2010-12-18 01:00:40 +00001355 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001356 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001357 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001358 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001359 (void)WasFastQuery;
1360 assert(WasFastQuery && "More work to do after problem solved?");
1361 }
1362
David Greene37e98092009-12-23 20:43:58 +00001363 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001364 return Result;
1365}
1366
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001367void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1368 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001369 // When an edge in the graph has been threaded, values that we could not
1370 // determine a value for before (i.e. were marked overdefined) may be
1371 // possible to solve now. We do NOT try to proactively update these values.
1372 // Instead, we clear their entries from the cache, and allow lazy updating to
1373 // recompute them when needed.
1374
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001375 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001376 // for all values that were marked overdefined in OldSucc, and for those same
1377 // values in any successor of OldSucc (except NewSucc) in which they were
1378 // also marked overdefined.
1379 std::vector<BasicBlock*> worklist;
1380 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001381
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001382 auto I = OverDefinedCache.find(OldSucc);
1383 if (I == OverDefinedCache.end())
1384 return; // Nothing to process here.
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001385 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001386
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001387 // Use a worklist to perform a depth-first search of OldSucc's successors.
1388 // NOTE: We do not need a visited list since any blocks we have already
1389 // visited will have had their overdefined markers cleared already, and we
1390 // thus won't loop to their successors.
1391 while (!worklist.empty()) {
1392 BasicBlock *ToUpdate = worklist.back();
1393 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001394
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001395 // Skip blocks only accessible through NewSucc.
1396 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001397
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001398 bool changed = false;
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001399 for (Value *V : ValsToClear) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001400 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001401 auto OI = OverDefinedCache.find(ToUpdate);
1402 if (OI == OverDefinedCache.end())
1403 continue;
1404 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1405 if (!ValueSet.count(V))
1406 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001407
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001408 ValueSet.erase(V);
1409 if (ValueSet.empty())
1410 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001411
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001412 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001413 // blocks successors too.
1414 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001415 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001416
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001417 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001418
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001419 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1420 }
1421}
1422
Chris Lattneraf025d32009-11-15 19:59:49 +00001423//===----------------------------------------------------------------------===//
1424// LazyValueInfo Impl
1425//===----------------------------------------------------------------------===//
1426
Sanjay Patel2a385e22015-01-09 16:47:20 +00001427/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001428static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001429 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001430 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001431 if (!PImpl) {
1432 assert(DL && "getCache() called with a null DataLayout");
1433 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1434 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001435 return *static_cast<LazyValueInfoCache*>(PImpl);
1436}
1437
Sean Silva687019f2016-06-13 22:01:25 +00001438bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1439 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001440 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001441
1442 DominatorTreeWrapperPass *DTWP =
1443 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001444 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1445 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001446
Sean Silva687019f2016-06-13 22:01:25 +00001447 if (Info.PImpl)
1448 getCache(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001449
Owen Anderson208636f2010-08-18 18:39:01 +00001450 // Fully lazy.
1451 return false;
1452}
1453
Sean Silva687019f2016-06-13 22:01:25 +00001454void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001455 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001456 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001457 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001458}
1459
Sean Silva687019f2016-06-13 22:01:25 +00001460LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1461
1462LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1463
Chris Lattneraf025d32009-11-15 19:59:49 +00001464void LazyValueInfo::releaseMemory() {
1465 // If the cache was allocated, free it.
1466 if (PImpl) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001467 delete &getCache(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001468 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001469 }
1470}
1471
Sean Silva687019f2016-06-13 22:01:25 +00001472void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1473
1474LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1475 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1476 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1477 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1478
1479 return LazyValueInfo(&AC, &TLI, DT);
1480}
1481
Hal Finkel7e184492014-09-07 20:29:59 +00001482Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1483 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001484 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001485 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001486 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001487
Chris Lattner19019ea2009-11-11 22:48:44 +00001488 if (Result.isConstant())
1489 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001490 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001491 ConstantRange CR = Result.getConstantRange();
1492 if (const APInt *SingleVal = CR.getSingleElement())
1493 return ConstantInt::get(V->getContext(), *SingleVal);
1494 }
Craig Topper9f008862014-04-15 04:59:12 +00001495 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001496}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001497
John Regehre1c481d2016-05-02 19:58:00 +00001498ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001499 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001500 assert(V->getType()->isIntegerTy());
1501 unsigned Width = V->getType()->getIntegerBitWidth();
1502 const DataLayout &DL = BB->getModule()->getDataLayout();
1503 LVILatticeVal Result =
1504 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1505 assert(!Result.isConstant());
1506 if (Result.isUndefined())
1507 return ConstantRange(Width, /*isFullSet=*/false);
1508 if (Result.isConstantRange())
1509 return Result.getConstantRange();
Davide Italianobd543d02016-05-25 22:29:34 +00001510 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001511}
1512
Sanjay Patel2a385e22015-01-09 16:47:20 +00001513/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001514/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001515Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001516 BasicBlock *ToBB,
1517 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001518 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001519 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001520 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001521
Chris Lattnerd5e25432009-11-12 01:29:10 +00001522 if (Result.isConstant())
1523 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001524 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001525 ConstantRange CR = Result.getConstantRange();
1526 if (const APInt *SingleVal = CR.getSingleElement())
1527 return ConstantInt::get(V->getContext(), *SingleVal);
1528 }
Craig Topper9f008862014-04-15 04:59:12 +00001529 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001530}
1531
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001532static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1533 LVILatticeVal &Result,
1534 const DataLayout &DL,
1535 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001536
Chris Lattner565ee2f2009-11-12 04:36:58 +00001537 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001538 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001539 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001540 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001541 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001542 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001543 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1544 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001545 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001546
Owen Anderson185fe002010-08-10 20:03:09 +00001547 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001548 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001549 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001550
Owen Anderson185fe002010-08-10 20:03:09 +00001551 ConstantRange CR = Result.getConstantRange();
1552 if (Pred == ICmpInst::ICMP_EQ) {
1553 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001554 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001555
Owen Anderson185fe002010-08-10 20:03:09 +00001556 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001557 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001558 } else if (Pred == ICmpInst::ICMP_NE) {
1559 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001560 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001561
Owen Anderson185fe002010-08-10 20:03:09 +00001562 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001563 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001564 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001565
Owen Anderson185fe002010-08-10 20:03:09 +00001566 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001567 ConstantRange TrueValues =
1568 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1569 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001570 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001571 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001572 return LazyValueInfo::False;
1573 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001574 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001575
Chris Lattneraf025d32009-11-15 19:59:49 +00001576 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001577 // If this is an equality comparison, we can try to fold it knowing that
1578 // "V != C1".
1579 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001580 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001581 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001582 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001583 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001584 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001585 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001586 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001587 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001588 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001589 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001590 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001591 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001592 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001593 }
Hal Finkel7e184492014-09-07 20:29:59 +00001594 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001595 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001596
Hal Finkel7e184492014-09-07 20:29:59 +00001597 return LazyValueInfo::Unknown;
1598}
1599
Sanjay Patel2a385e22015-01-09 16:47:20 +00001600/// Determine whether the specified value comparison with a constant is known to
1601/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001602LazyValueInfo::Tristate
1603LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1604 BasicBlock *FromBB, BasicBlock *ToBB,
1605 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001606 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001607 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001608 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001609
1610 return getPredicateResult(Pred, C, Result, DL, TLI);
1611}
1612
1613LazyValueInfo::Tristate
1614LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1615 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001616 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1617 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001618 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1619 if (Ret != Unknown)
1620 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001621
Philip Reamesaeefae02015-11-04 01:47:04 +00001622 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1623 // LVI as a whole tries to compute a lattice value which is conservatively
1624 // correct at a given location. In this case, we have a predicate which we
1625 // weren't able to prove about the merged result, and we're pushing that
1626 // predicate back along each incoming edge to see if we can prove it
1627 // separately for each input. As a motivating example, consider:
1628 // bb1:
1629 // %v1 = ... ; constantrange<1, 5>
1630 // br label %merge
1631 // bb2:
1632 // %v2 = ... ; constantrange<10, 20>
1633 // br label %merge
1634 // merge:
1635 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1636 // %pred = icmp eq i32 %phi, 8
1637 // We can't tell from the lattice value for '%phi' that '%pred' is false
1638 // along each path, but by checking the predicate over each input separately,
1639 // we can.
1640 // We limit the search to one step backwards from the current BB and value.
1641 // We could consider extending this to search further backwards through the
1642 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001643 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001644 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001645 BasicBlock *BB = CxtI->getParent();
1646
1647 // Function entry or an unreachable block. Bail to avoid confusing
1648 // analysis below.
1649 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1650 if (PI == PE)
1651 return Unknown;
1652
1653 // If V is a PHI node in the same block as the context, we need to ask
1654 // questions about the predicate as applied to the incoming value along
1655 // each edge. This is useful for eliminating cases where the predicate is
1656 // known along all incoming edges.
1657 if (auto *PHI = dyn_cast<PHINode>(V))
1658 if (PHI->getParent() == BB) {
1659 Tristate Baseline = Unknown;
1660 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1661 Value *Incoming = PHI->getIncomingValue(i);
1662 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001663 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001664 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1665 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001666
Philip Reamesbb11d622015-08-31 18:31:48 +00001667 // Keep going as long as we've seen a consistent known result for
1668 // all inputs.
1669 Baseline = (i == 0) ? Result /* First iteration */
1670 : (Baseline == Result ? Baseline : Unknown); /* All others */
1671 if (Baseline == Unknown)
1672 break;
1673 }
1674 if (Baseline != Unknown)
1675 return Baseline;
1676 }
1677
Philip Reames66ab0f02015-06-16 00:49:59 +00001678 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001679 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001680 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001681 if (!isa<Instruction>(V) ||
1682 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001683 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001684 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001685 // the value of the comparison in this block.
1686 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1687 if (Baseline != Unknown) {
1688 // Check that all remaining incoming values match the first one.
1689 while (++PI != PE) {
1690 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1691 if (Ret != Baseline) break;
1692 }
1693 // If we terminated early, then one of the values didn't match.
1694 if (PI == PE) {
1695 return Baseline;
1696 }
1697 }
1698 }
1699 }
1700 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001701}
1702
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001703void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001704 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001705 if (PImpl) {
1706 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1707 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1708 }
Owen Anderson208636f2010-08-18 18:39:01 +00001709}
1710
1711void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001712 if (PImpl) {
1713 const DataLayout &DL = BB->getModule()->getDataLayout();
1714 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1715 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001716}