blob: 62568f298793b1cbf2500a86fd52afa7df4008a8 [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
70 /// "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 }
119
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
321/// conflict, see below).
322/// * 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
357 // 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
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000444 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000445 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000446 LVILatticeVal &Result,
447 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000448 bool hasBlockValue(Value *Val, BasicBlock *BB);
449
450 // These methods process one work item and may add more. A false value
451 // returned means that the work item was not completely processed and must
452 // be revisited after going through the new items.
453 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000454 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
455 Value *Val, BasicBlock *BB);
456 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
457 PHINode *PN, BasicBlock *BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000458 bool solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +0000459 SelectInst *S, BasicBlock *BB);
460 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV,
461 Instruction *BBI, BasicBlock *BB);
462 bool solveBlockValueCast(LVILatticeVal &BBLV,
463 Instruction *BBI, BasicBlock *BB);
464 void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
Hal Finkel7e184492014-09-07 20:29:59 +0000465 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000466
467 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000468
Nick Lewycky11678bd2010-12-15 18:57:18 +0000469 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000470 return ValueCache[LVIValueHandle(V, this)];
471 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000472
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000473 bool isOverdefined(Value *V, BasicBlock *BB) const {
474 auto ODI = OverDefinedCache.find(BB);
475
476 if (ODI == OverDefinedCache.end())
477 return false;
478
479 return ODI->second.count(V);
480 }
481
482 bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
483 if (isOverdefined(V, BB))
484 return true;
485
486 LVIValueHandle ValHandle(V, this);
487 auto I = ValueCache.find(ValHandle);
488 if (I == ValueCache.end())
489 return false;
490
491 return I->second.count(BB);
492 }
493
494 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
495 if (isOverdefined(V, BB))
496 return LVILatticeVal::getOverdefined();
497
498 return lookup(V)[BB];
499 }
500
Chris Lattneraf025d32009-11-15 19:59:49 +0000501 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000502 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000503 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000504 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
505 Instruction *CxtI = nullptr);
506
Sanjay Patel2a385e22015-01-09 16:47:20 +0000507 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000508 /// value for the specified Value* at the specified instruction (generally
509 /// from an assume intrinsic).
510 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000511
Sanjay Patel2a385e22015-01-09 16:47:20 +0000512 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000513 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000514 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
515 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000516
Sanjay Patel2a385e22015-01-09 16:47:20 +0000517 /// This is the update interface to inform the cache that an edge from
518 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000519 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000520
Sanjay Patel2a385e22015-01-09 16:47:20 +0000521 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000522 /// that a block has been deleted.
523 void eraseBlock(BasicBlock *BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000524
Owen Anderson208636f2010-08-18 18:39:01 +0000525 /// clear - Empty the cache.
526 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000527 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000528 ValueCache.clear();
529 OverDefinedCache.clear();
530 }
Hal Finkel7e184492014-09-07 20:29:59 +0000531
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000532 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000533 DominatorTree *DT = nullptr)
534 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000535 };
536} // end anonymous namespace
537
Owen Anderson118ac802011-01-05 21:15:29 +0000538void LVIValueHandle::deleted() {
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000539 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
540 for (auto &I : Parent->OverDefinedCache) {
541 SmallPtrSetImpl<Value *> &ValueSet = I.second;
542 if (ValueSet.count(getValPtr()))
543 ValueSet.erase(getValPtr());
544 if (ValueSet.empty())
545 ToErase.push_back(I.first);
546 }
547 for (auto &BB : ToErase)
548 Parent->OverDefinedCache.erase(BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000549
Owen Anderson7b974a42010-08-11 22:36:04 +0000550 // This erasure deallocates *this, so it MUST happen after we're done
551 // using any and all members of *this.
552 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000553}
554
Owen Anderson208636f2010-08-18 18:39:01 +0000555void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000556 // Shortcut if we have never seen this block.
557 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
558 if (I == SeenBlocks.end())
559 return;
560 SeenBlocks.erase(I);
561
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000562 auto ODI = OverDefinedCache.find(BB);
563 if (ODI != OverDefinedCache.end())
564 OverDefinedCache.erase(ODI);
Owen Anderson208636f2010-08-18 18:39:01 +0000565
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000566 for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
Owen Anderson208636f2010-08-18 18:39:01 +0000567 I->second.erase(BB);
568}
Owen Andersonc1561b82010-07-30 23:59:40 +0000569
Nick Lewycky55a700b2010-12-18 01:00:40 +0000570void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000571 while (!BlockValueStack.empty()) {
572 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000573 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
574
Nuno Lopese6e04902012-06-28 01:16:18 +0000575 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000576 // The work item was completely processed.
577 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000578 assert(hasCachedValueInfo(e.second, e.first) &&
579 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000580
Philip Reames44456b82016-02-02 03:15:40 +0000581 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000582 << " = " << getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000583
Owen Anderson6f060af2011-01-05 23:26:22 +0000584 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000585 BlockValueSet.erase(e);
586 } else {
587 // More work needs to be done before revisiting.
588 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000589 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000590 }
591}
592
593bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
594 // If already a constant, there is nothing to compute.
595 if (isa<Constant>(Val))
596 return true;
597
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000598 return hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000599}
600
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000601LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000602 // If already a constant, there is nothing to compute.
603 if (Constant *VC = dyn_cast<Constant>(Val))
604 return LVILatticeVal::get(VC);
605
Benjamin Kramer36647082011-12-03 15:16:45 +0000606 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000607 return getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000608}
609
Philip Reameseb3e9da2015-10-29 03:57:17 +0000610static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
611 switch (BBI->getOpcode()) {
612 default: break;
613 case Instruction::Load:
614 case Instruction::Call:
615 case Instruction::Invoke:
616 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000617 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000618 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000619 }
620 break;
621 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000622 // Nothing known - will be intersected with other facts
623 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000624}
625
Nick Lewycky55a700b2010-12-18 01:00:40 +0000626bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
627 if (isa<Constant>(Val))
628 return true;
629
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000630 if (hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000631 // If we have a cached value, use that.
632 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000633 << "' val=" << getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000634
Hans Wennborg45172ac2014-11-25 17:23:05 +0000635 // Since we're reusing a cached value, we don't need to update the
636 // OverDefinedCache. The cache will have been properly updated whenever the
637 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000638 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000639 }
640
Hans Wennborg45172ac2014-11-25 17:23:05 +0000641 // Hold off inserting this value into the Cache in case we have to return
642 // false and come back later.
643 LVILatticeVal Res;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000644
Chris Lattneraf025d32009-11-15 19:59:49 +0000645 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000646 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000647 if (!solveBlockValueNonLocal(Res, Val, BB))
648 return false;
649 insertResult(Val, BB, Res);
650 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000651 }
Chris Lattner2c708562009-11-15 20:00:52 +0000652
Nick Lewycky55a700b2010-12-18 01:00:40 +0000653 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000654 if (!solveBlockValuePHINode(Res, PN, BB))
655 return false;
656 insertResult(Val, BB, Res);
657 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000658 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000659
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000660 if (auto *SI = dyn_cast<SelectInst>(BBI)) {
661 if (!solveBlockValueSelect(Res, SI, BB))
662 return false;
663 insertResult(Val, BB, Res);
664 return true;
665 }
666
Philip Reames2ab964e2016-04-27 01:02:25 +0000667 // If this value is a nonnull pointer, record it's range and bailout. Note
668 // that for all other pointer typed values, we terminate the search at the
669 // definition. We could easily extend this to look through geps, bitcasts,
670 // and the like to prove non-nullness, but it's not clear that's worth it
671 // compile time wise. The context-insensative value walk done inside
672 // isKnownNonNull gets most of the profitable cases at much less expense.
673 // This does mean that we have a sensativity to where the defining
674 // instruction is placed, even if it could legally be hoisted much higher.
675 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000676 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
677 if (PT && isKnownNonNull(BBI)) {
678 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000679 insertResult(Val, BB, Res);
680 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000681 }
Davide Italianobd543d02016-05-25 22:29:34 +0000682 if (BBI->getType()->isIntegerTy()) {
Philip Reames2ab964e2016-04-27 01:02:25 +0000683 if (isa<CastInst>(BBI)) {
684 if (!solveBlockValueCast(Res, BBI, BB))
685 return false;
686 insertResult(Val, BB, Res);
687 return true;
688 }
689 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
690 if (BO && isa<ConstantInt>(BO->getOperand(1))) {
691 if (!solveBlockValueBinaryOp(Res, BBI, BB))
692 return false;
693 insertResult(Val, BB, Res);
694 return true;
695 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000696 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000697
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000698 DEBUG(dbgs() << " compute BB '" << BB->getName()
699 << "' - unknown inst def found.\n");
700 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000701 insertResult(Val, BB, Res);
702 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000703}
704
705static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
706 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
707 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000708 GetUnderlyingObject(L->getPointerOperand(),
709 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000710 }
711 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
712 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000713 GetUnderlyingObject(S->getPointerOperand(),
714 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000715 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000716 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
717 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000718
719 // FIXME: check whether it has a valuerange that excludes zero?
720 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
721 if (!Len || Len->isZero()) return false;
722
Eli Friedman7a5fc692011-05-31 20:40:16 +0000723 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000724 if (GetUnderlyingObject(MI->getRawDest(),
725 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000726 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000727 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000728 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000729 if (GetUnderlyingObject(MTI->getRawSource(),
730 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000731 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000732 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000733 return false;
734}
735
Philip Reames3f83dbe2016-04-27 00:30:55 +0000736/// Return true if the allocation associated with Val is ever dereferenced
737/// within the given basic block. This establishes the fact Val is not null,
738/// but does not imply that the memory at Val is dereferenceable. (Val may
739/// point off the end of the dereferenceable part of the object.)
740static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
741 assert(Val->getType()->isPointerTy());
742
743 const DataLayout &DL = BB->getModule()->getDataLayout();
744 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
745 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
746 // inside InstructionDereferencesPointer either.
747 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
748 for (Instruction &I : *BB)
749 if (InstructionDereferencesPointer(&I, UnderlyingVal))
750 return true;
751 return false;
752}
753
Owen Anderson64c2c572010-12-20 18:18:16 +0000754bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
755 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000756 LVILatticeVal Result; // Start Undefined.
757
Nick Lewycky55a700b2010-12-18 01:00:40 +0000758 // If this is the entry block, we must be asking about an argument. The
759 // value is overdefined.
760 if (BB == &BB->getParent()->getEntryBlock()) {
761 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000762 // Bofore giving up, see if we can prove the pointer non-null local to
763 // this particular block.
764 if (Val->getType()->isPointerTy() &&
765 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000766 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000767 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
768 } else {
769 Result.markOverdefined();
770 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000771 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000772 return true;
773 }
774
775 // Loop over all of our predecessors, merging what we know from them into
776 // result.
777 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000778 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000779 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000780 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000781 if (EdgesMissing)
782 continue;
783
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000784 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000785
786 // If we hit overdefined, exit early. The BlockVals entry is already set
787 // to overdefined.
788 if (Result.isOverdefined()) {
789 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000790 << "' - overdefined because of pred (non local).\n");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000791 // Bofore giving up, see if we can prove the pointer non-null local to
792 // this particular block.
793 if (Val->getType()->isPointerTy() &&
794 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000795 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000796 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
797 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000798
Owen Anderson64c2c572010-12-20 18:18:16 +0000799 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000800 return true;
801 }
802 }
803 if (EdgesMissing)
804 return false;
805
806 // Return the merged value, which is more precise than 'overdefined'.
807 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000808 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000809 return true;
810}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000811
Owen Anderson64c2c572010-12-20 18:18:16 +0000812bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
813 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000814 LVILatticeVal Result; // Start Undefined.
815
816 // Loop over all of our predecessors, merging what we know from them into
817 // result.
818 bool EdgesMissing = false;
819 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
820 BasicBlock *PhiBB = PN->getIncomingBlock(i);
821 Value *PhiVal = PN->getIncomingValue(i);
822 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000823 // Note that we can provide PN as the context value to getEdgeValue, even
824 // though the results will be cached, because PN is the value being used as
825 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000826 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000827 if (EdgesMissing)
828 continue;
829
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000830 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000831
832 // If we hit overdefined, exit early. The BlockVals entry is already set
833 // to overdefined.
834 if (Result.isOverdefined()) {
835 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000836 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000837
Owen Anderson64c2c572010-12-20 18:18:16 +0000838 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000839 return true;
840 }
841 }
842 if (EdgesMissing)
843 return false;
844
845 // Return the merged value, which is more precise than 'overdefined'.
846 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000847 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000848 return true;
849}
850
Hal Finkel7e184492014-09-07 20:29:59 +0000851static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
852 LVILatticeVal &Result,
853 bool isTrueDest = true);
854
Philip Reamesd1f829d2016-02-02 21:57:37 +0000855// If we can determine a constraint on the value given conditions assumed by
856// the program, intersect those constraints with BBLV
857void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000858 LVILatticeVal &BBLV,
859 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000860 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
861 if (!BBI)
862 return;
863
Chandler Carruth66b31302015-01-04 12:03:27 +0000864 for (auto &AssumeVH : AC->assumptions()) {
865 if (!AssumeVH)
866 continue;
867 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000868 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000869 continue;
870
871 Value *C = I->getArgOperand(0);
872 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
873 LVILatticeVal Result;
Philip Reamesd1f829d2016-02-02 21:57:37 +0000874 if (getValueFromFromCondition(Val, ICI, Result))
875 BBLV = intersect(BBLV, Result);
Hal Finkel7e184492014-09-07 20:29:59 +0000876 }
877 }
878}
879
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000880bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
881 SelectInst *SI, BasicBlock *BB) {
882
883 // Recurse on our inputs if needed
884 if (!hasBlockValue(SI->getTrueValue(), BB)) {
885 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
886 return false;
887 BBLV.markOverdefined();
888 return true;
889 }
890 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
891 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
892 // extra slots in the table if we can.
893 if (TrueVal.isOverdefined()) {
894 BBLV.markOverdefined();
895 return true;
896 }
897
898 if (!hasBlockValue(SI->getFalseValue(), BB)) {
899 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
900 return false;
901 BBLV.markOverdefined();
902 return true;
903 }
904 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
905 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
906 // extra slots in the table if we can.
907 if (FalseVal.isOverdefined()) {
908 BBLV.markOverdefined();
909 return true;
910 }
911
Philip Reamesadf0e352016-02-26 22:53:59 +0000912 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
913 ConstantRange TrueCR = TrueVal.getConstantRange();
914 ConstantRange FalseCR = FalseVal.getConstantRange();
915 Value *LHS = nullptr;
916 Value *RHS = nullptr;
917 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
918 // Is this a min specifically of our two inputs? (Avoid the risk of
919 // ValueTracking getting smarter looking back past our immediate inputs.)
920 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
921 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
922 switch (SPR.Flavor) {
923 default:
924 llvm_unreachable("unexpected minmax type!");
925 case SPF_SMIN: /// Signed minimum
926 BBLV.markConstantRange(TrueCR.smin(FalseCR));
927 return true;
928 case SPF_UMIN: /// Unsigned minimum
929 BBLV.markConstantRange(TrueCR.umin(FalseCR));
930 return true;
931 case SPF_SMAX: /// Signed maximum
932 BBLV.markConstantRange(TrueCR.smax(FalseCR));
933 return true;
934 case SPF_UMAX: /// Unsigned maximum
935 BBLV.markConstantRange(TrueCR.umax(FalseCR));
936 return true;
937 };
938 }
939
940 // TODO: ABS, NABS from the SelectPatternResult
941 }
942
Philip Reames854a84c2016-02-12 00:09:18 +0000943 // Can we constrain the facts about the true and false values by using the
944 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
945 // TODO: We could potentially refine an overdefined true value above.
946 if (auto *ICI = dyn_cast<ICmpInst>(SI->getCondition())) {
947 LVILatticeVal TrueValTaken, FalseValTaken;
948 if (!getValueFromFromCondition(SI->getTrueValue(), ICI,
949 TrueValTaken, true))
950 TrueValTaken.markOverdefined();
951 if (!getValueFromFromCondition(SI->getFalseValue(), ICI,
952 FalseValTaken, false))
953 FalseValTaken.markOverdefined();
954
955 TrueVal = intersect(TrueVal, TrueValTaken);
956 FalseVal = intersect(FalseVal, FalseValTaken);
Philip Reames854a84c2016-02-12 00:09:18 +0000957
Philip Reamesadf0e352016-02-26 22:53:59 +0000958
959 // Handle clamp idioms such as:
960 // %24 = constantrange<0, 17>
961 // %39 = icmp eq i32 %24, 0
962 // %40 = add i32 %24, -1
963 // %siv.next = select i1 %39, i32 16, i32 %40
964 // %siv.next = constantrange<0, 17> not <-1, 17>
965 // In general, this can handle any clamp idiom which tests the edge
966 // condition via an equality or inequality.
967 ICmpInst::Predicate Pred = ICI->getPredicate();
968 Value *A = ICI->getOperand(0);
969 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
970 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
971 assert(A->getType() == B->getType());
972 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
973 };
974 // See if either input is A + C2, subject to the constraint from the
975 // condition that A != C when that input is used. We can assume that
976 // that input doesn't include C + C2.
977 ConstantInt *CIAdded;
978 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +0000979 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +0000980 case ICmpInst::ICMP_EQ:
981 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
982 m_ConstantInt(CIAdded)))) {
983 auto ResNot = addConstants(CIBase, CIAdded);
984 FalseVal = intersect(FalseVal,
985 LVILatticeVal::getNot(ResNot));
986 }
987 break;
988 case ICmpInst::ICMP_NE:
989 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
990 m_ConstantInt(CIAdded)))) {
991 auto ResNot = addConstants(CIBase, CIAdded);
992 TrueVal = intersect(TrueVal,
993 LVILatticeVal::getNot(ResNot));
994 }
995 break;
996 };
997 }
998 }
Philip Reames854a84c2016-02-12 00:09:18 +0000999
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001000 LVILatticeVal Result; // Start Undefined.
1001 Result.mergeIn(TrueVal, DL);
1002 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001003 BBLV = Result;
1004 return true;
1005}
1006
Philip Reames66715772016-04-25 18:30:31 +00001007bool LazyValueInfoCache::solveBlockValueCast(LVILatticeVal &BBLV,
1008 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001009 BasicBlock *BB) {
1010 if (!BBI->getOperand(0)->getType()->isSized()) {
1011 // Without knowing how wide the input is, we can't analyze it in any useful
1012 // way.
1013 BBLV.markOverdefined();
1014 return true;
1015 }
Philip Reamesf105db42016-04-26 23:27:33 +00001016
1017 // Filter out casts we don't know how to reason about before attempting to
1018 // recurse on our operand. This can cut a long search short if we know we're
1019 // not going to be able to get any useful information anways.
1020 switch (BBI->getOpcode()) {
1021 case Instruction::Trunc:
1022 case Instruction::SExt:
1023 case Instruction::ZExt:
1024 case Instruction::BitCast:
1025 break;
1026 default:
1027 // Unhandled instructions are overdefined.
1028 DEBUG(dbgs() << " compute BB '" << BB->getName()
1029 << "' - overdefined (unknown cast).\n");
1030 BBLV.markOverdefined();
1031 return true;
1032 }
1033
Philip Reamese5030e82016-04-26 22:52:30 +00001034
Philip Reames38c87c22016-04-26 21:48:16 +00001035 // Figure out the range of the LHS. If that fails, we still apply the
1036 // transfer rule on the full set since we may be able to locally infer
1037 // interesting facts.
1038 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001039 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001040 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001041 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001042
1043 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001044 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001045 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1046 if (hasBlockValue(BBI->getOperand(0), BB)) {
1047 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1048 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1049 if (LHSVal.isConstantRange())
1050 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001051 }
1052
Philip Reames38c87c22016-04-26 21:48:16 +00001053 const unsigned ResultBitWidth =
1054 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001055
1056 // NOTE: We're currently limited by the set of operations that ConstantRange
1057 // can evaluate symbolically. Enhancing that set will allows us to analyze
1058 // more definitions.
1059 LVILatticeVal Result;
1060 switch (BBI->getOpcode()) {
1061 case Instruction::Trunc:
Philip Reames38c87c22016-04-26 21:48:16 +00001062 Result.markConstantRange(LHSRange.truncate(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001063 break;
1064 case Instruction::SExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001065 Result.markConstantRange(LHSRange.signExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001066 break;
1067 case Instruction::ZExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001068 Result.markConstantRange(LHSRange.zeroExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001069 break;
1070 case Instruction::BitCast:
1071 Result.markConstantRange(LHSRange);
1072 break;
Philip Reames66715772016-04-25 18:30:31 +00001073 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001074 // Should be dead if the code above is correct
1075 llvm_unreachable("inconsistent with above");
Philip Reames66715772016-04-25 18:30:31 +00001076 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001077 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001078
Philip Reames66715772016-04-25 18:30:31 +00001079 BBLV = Result;
1080 return true;
1081}
1082
1083bool LazyValueInfoCache::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
1084 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001085 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001086
Philip Reames053c2a62016-04-26 23:10:35 +00001087 assert(BBI->getOperand(0)->getType()->isSized() &&
1088 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001089
1090 // Filter out operators we don't know how to reason about before attempting to
1091 // recurse on our operand(s). This can cut a long search short if we know
1092 // we're not going to be able to get any useful information anways.
1093 switch (BBI->getOpcode()) {
1094 case Instruction::Add:
1095 case Instruction::Sub:
1096 case Instruction::Mul:
1097 case Instruction::UDiv:
1098 case Instruction::Shl:
1099 case Instruction::LShr:
1100 case Instruction::And:
1101 case Instruction::Or:
1102 // continue into the code below
1103 break;
1104 default:
1105 // Unhandled instructions are overdefined.
1106 DEBUG(dbgs() << " compute BB '" << BB->getName()
1107 << "' - overdefined (unknown binary operator).\n");
1108 BBLV.markOverdefined();
1109 return true;
1110 };
Philip Reames053c2a62016-04-26 23:10:35 +00001111
1112 // Figure out the range of the LHS. If that fails, use a conservative range,
1113 // but apply the transfer rule anyways. This lets us pick up facts from
1114 // expressions like "and i32 (call i32 @foo()), 32"
1115 if (!hasBlockValue(BBI->getOperand(0), BB))
1116 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1117 // More work to do before applying this transfer rule.
1118 return false;
1119
1120 const unsigned OperandBitWidth =
1121 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1122 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1123 if (hasBlockValue(BBI->getOperand(0), BB)) {
1124 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1125 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1126 if (LHSVal.isConstantRange())
1127 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001128 }
Philip Reames66715772016-04-25 18:30:31 +00001129
1130 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1131 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1132
Owen Anderson80d19f02010-08-18 21:11:37 +00001133 // NOTE: We're currently limited by the set of operations that ConstantRange
1134 // can evaluate symbolically. Enhancing that set will allows us to analyze
1135 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +00001136 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +00001137 switch (BBI->getOpcode()) {
1138 case Instruction::Add:
1139 Result.markConstantRange(LHSRange.add(RHSRange));
1140 break;
1141 case Instruction::Sub:
1142 Result.markConstantRange(LHSRange.sub(RHSRange));
1143 break;
1144 case Instruction::Mul:
1145 Result.markConstantRange(LHSRange.multiply(RHSRange));
1146 break;
1147 case Instruction::UDiv:
1148 Result.markConstantRange(LHSRange.udiv(RHSRange));
1149 break;
1150 case Instruction::Shl:
1151 Result.markConstantRange(LHSRange.shl(RHSRange));
1152 break;
1153 case Instruction::LShr:
1154 Result.markConstantRange(LHSRange.lshr(RHSRange));
1155 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +00001156 case Instruction::And:
1157 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
1158 break;
1159 case Instruction::Or:
1160 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
1161 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001162 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001163 // Should be dead if the code above is correct
1164 llvm_unreachable("inconsistent with above");
Owen Anderson80d19f02010-08-18 21:11:37 +00001165 break;
1166 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001167
Owen Anderson64c2c572010-12-20 18:18:16 +00001168 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +00001169 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001170}
1171
Hal Finkel7e184492014-09-07 20:29:59 +00001172bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
1173 LVILatticeVal &Result, bool isTrueDest) {
Philip Reames19183842016-04-25 22:21:24 +00001174 assert(ICI && "precondition");
1175 if (isa<Constant>(ICI->getOperand(1))) {
Hal Finkel7e184492014-09-07 20:29:59 +00001176 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
1177 // We know that V has the RHS constant if this is a true SETEQ or
1178 // false SETNE.
1179 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
1180 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
1181 else
1182 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
1183 return true;
1184 }
1185
1186 // Recognize the range checking idiom that InstCombine produces.
1187 // (X-C1) u< C2 --> [C1, C1+C2)
1188 ConstantInt *NegOffset = nullptr;
1189 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
1190 match(ICI->getOperand(0), m_Add(m_Specific(Val),
1191 m_ConstantInt(NegOffset)));
1192
1193 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
1194 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Sanjoy Das7182d362015-03-18 00:41:24 +00001195 // Calculate the range of values that are allowed by the comparison
Hal Finkel7e184492014-09-07 20:29:59 +00001196 ConstantRange CmpRange(CI->getValue());
1197 ConstantRange TrueValues =
Sanjoy Das7182d362015-03-18 00:41:24 +00001198 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
Hal Finkel7e184492014-09-07 20:29:59 +00001199
1200 if (NegOffset) // Apply the offset from above.
1201 TrueValues = TrueValues.subtract(NegOffset->getValue());
1202
1203 // If we're interested in the false dest, invert the condition.
1204 if (!isTrueDest) TrueValues = TrueValues.inverse();
1205
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001206 Result = LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001207 return true;
1208 }
1209 }
Philip Reames38c87c22016-04-26 21:48:16 +00001210
Hal Finkel7e184492014-09-07 20:29:59 +00001211 return false;
1212}
1213
Nuno Lopese6e04902012-06-28 01:16:18 +00001214/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001215/// Val is not constrained on the edge. Result is unspecified if return value
1216/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001217static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1218 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001219 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001220 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001221 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1222 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001223 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001224 if (BI->isConditional() &&
1225 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1226 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1227 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1228 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001229
Chris Lattner19019ea2009-11-11 22:48:44 +00001230 // If V is the condition of the branch itself, then we know exactly what
1231 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001232 if (BI->getCondition() == Val) {
1233 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001234 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001235 return true;
1236 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001237
Chris Lattner19019ea2009-11-11 22:48:44 +00001238 // If the condition of the branch is an equality comparison, we may be
1239 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +00001240 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
1241 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
1242 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001243 }
1244 }
Chris Lattner77358782009-11-15 20:02:12 +00001245
1246 // If the edge was formed by a switch on the value, then we may know exactly
1247 // what it is.
1248 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001249 if (SI->getCondition() != Val)
1250 return false;
1251
1252 bool DefaultCase = SI->getDefaultDest() == BBTo;
1253 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1254 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1255
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001256 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001257 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001258 if (DefaultCase) {
1259 // It is possible that the default destination is the destination of
1260 // some cases. There is no need to perform difference for those cases.
1261 if (i.getCaseSuccessor() != BBTo)
1262 EdgesVals = EdgesVals.difference(EdgeVal);
1263 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001264 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001265 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001266 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001267 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001268 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001269 return false;
1270}
1271
Sanjay Patel938e2792015-01-09 16:35:37 +00001272/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1273/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +00001274bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001275 BasicBlock *BBTo, LVILatticeVal &Result,
1276 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001277 // If already a constant, there is nothing to compute.
1278 if (Constant *VC = dyn_cast<Constant>(Val)) {
1279 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001280 return true;
1281 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001282
Philip Reames44456b82016-02-02 03:15:40 +00001283 LVILatticeVal LocalResult;
1284 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1285 // If we couldn't constrain the value on the edge, LocalResult doesn't
1286 // provide any information.
1287 LocalResult.markOverdefined();
1288
1289 if (hasSingleValue(LocalResult)) {
1290 // Can't get any more precise here
1291 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001292 return true;
1293 }
1294
1295 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001296 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1297 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001298 // No new information.
1299 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001300 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001301 }
1302
Philip Reames44456b82016-02-02 03:15:40 +00001303 // Try to intersect ranges of the BB and the constraint on the edge.
1304 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001305 intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001306 // We can use the context instruction (generically the ultimate instruction
1307 // the calling pass is trying to simplify) here, even though the result of
1308 // this function is generally cached when called from the solve* functions
1309 // (and that cached result might be used with queries using a different
1310 // context instruction), because when this function is called from the solve*
1311 // functions, the context instruction is not provided. When called from
1312 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1313 // but then the result is not cached.
Philip Reamesd1f829d2016-02-02 21:57:37 +00001314 intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001315
1316 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001317 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001318}
1319
Hal Finkel7e184492014-09-07 20:29:59 +00001320LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1321 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001322 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001323 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001324
Hans Wennborg45172ac2014-11-25 17:23:05 +00001325 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001326 if (!hasBlockValue(V, BB)) {
1327 pushBlockValue(std::make_pair(BB, V));
1328 solve();
1329 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001330 LVILatticeVal Result = getBlockValue(V, BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001331 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001332
1333 DEBUG(dbgs() << " Result = " << Result << "\n");
1334 return Result;
1335}
1336
1337LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1338 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1339 << CxtI->getName() << "'\n");
1340
Philip Reamesbb781b42016-02-10 21:46:32 +00001341 if (auto *C = dyn_cast<Constant>(V))
1342 return LVILatticeVal::get(C);
1343
Philip Reamesd1f829d2016-02-02 21:57:37 +00001344 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001345 if (auto *I = dyn_cast<Instruction>(V))
1346 Result = getFromRangeMetadata(I);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001347 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001348
David Greene37e98092009-12-23 20:43:58 +00001349 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001350 return Result;
1351}
Chris Lattner19019ea2009-11-11 22:48:44 +00001352
Chris Lattneraf025d32009-11-15 19:59:49 +00001353LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001354getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1355 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001356 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001357 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001358
Nick Lewycky55a700b2010-12-18 01:00:40 +00001359 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001360 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001361 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001362 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001363 (void)WasFastQuery;
1364 assert(WasFastQuery && "More work to do after problem solved?");
1365 }
1366
David Greene37e98092009-12-23 20:43:58 +00001367 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001368 return Result;
1369}
1370
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001371void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1372 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001373 // When an edge in the graph has been threaded, values that we could not
1374 // determine a value for before (i.e. were marked overdefined) may be
1375 // possible to solve now. We do NOT try to proactively update these values.
1376 // Instead, we clear their entries from the cache, and allow lazy updating to
1377 // recompute them when needed.
1378
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001379 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001380 // for all values that were marked overdefined in OldSucc, and for those same
1381 // values in any successor of OldSucc (except NewSucc) in which they were
1382 // also marked overdefined.
1383 std::vector<BasicBlock*> worklist;
1384 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001385
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001386 auto I = OverDefinedCache.find(OldSucc);
1387 if (I == OverDefinedCache.end())
1388 return; // Nothing to process here.
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001389 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001390
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001391 // Use a worklist to perform a depth-first search of OldSucc's successors.
1392 // NOTE: We do not need a visited list since any blocks we have already
1393 // visited will have had their overdefined markers cleared already, and we
1394 // thus won't loop to their successors.
1395 while (!worklist.empty()) {
1396 BasicBlock *ToUpdate = worklist.back();
1397 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001398
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001399 // Skip blocks only accessible through NewSucc.
1400 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001401
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001402 bool changed = false;
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001403 for (Value *V : ValsToClear) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001404 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001405 auto OI = OverDefinedCache.find(ToUpdate);
1406 if (OI == OverDefinedCache.end())
1407 continue;
1408 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1409 if (!ValueSet.count(V))
1410 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001411
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001412 ValueSet.erase(V);
1413 if (ValueSet.empty())
1414 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001415
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001416 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001417 // blocks successors too.
1418 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001419 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001420
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001421 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001422
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001423 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1424 }
1425}
1426
Chris Lattneraf025d32009-11-15 19:59:49 +00001427//===----------------------------------------------------------------------===//
1428// LazyValueInfo Impl
1429//===----------------------------------------------------------------------===//
1430
Sanjay Patel2a385e22015-01-09 16:47:20 +00001431/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001432static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001433 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001434 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001435 if (!PImpl) {
1436 assert(DL && "getCache() called with a null DataLayout");
1437 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1438 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001439 return *static_cast<LazyValueInfoCache*>(PImpl);
1440}
1441
Sean Silva687019f2016-06-13 22:01:25 +00001442bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1443 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001444 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001445
1446 DominatorTreeWrapperPass *DTWP =
1447 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001448 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1449 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001450
Sean Silva687019f2016-06-13 22:01:25 +00001451 if (Info.PImpl)
1452 getCache(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001453
Owen Anderson208636f2010-08-18 18:39:01 +00001454 // Fully lazy.
1455 return false;
1456}
1457
Sean Silva687019f2016-06-13 22:01:25 +00001458void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001459 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001460 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001461 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001462}
1463
Sean Silva687019f2016-06-13 22:01:25 +00001464LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1465
1466LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1467
Chris Lattneraf025d32009-11-15 19:59:49 +00001468void LazyValueInfo::releaseMemory() {
1469 // If the cache was allocated, free it.
1470 if (PImpl) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001471 delete &getCache(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001472 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001473 }
1474}
1475
Sean Silva687019f2016-06-13 22:01:25 +00001476void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1477
1478LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1479 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1480 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1481 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1482
1483 return LazyValueInfo(&AC, &TLI, DT);
1484}
1485
Hal Finkel7e184492014-09-07 20:29:59 +00001486Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1487 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001488 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001489 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001490 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001491
Chris Lattner19019ea2009-11-11 22:48:44 +00001492 if (Result.isConstant())
1493 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001494 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001495 ConstantRange CR = Result.getConstantRange();
1496 if (const APInt *SingleVal = CR.getSingleElement())
1497 return ConstantInt::get(V->getContext(), *SingleVal);
1498 }
Craig Topper9f008862014-04-15 04:59:12 +00001499 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001500}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001501
John Regehre1c481d2016-05-02 19:58:00 +00001502ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
1503 Instruction *CxtI) {
1504 assert(V->getType()->isIntegerTy());
1505 unsigned Width = V->getType()->getIntegerBitWidth();
1506 const DataLayout &DL = BB->getModule()->getDataLayout();
1507 LVILatticeVal Result =
1508 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1509 assert(!Result.isConstant());
1510 if (Result.isUndefined())
1511 return ConstantRange(Width, /*isFullSet=*/false);
1512 if (Result.isConstantRange())
1513 return Result.getConstantRange();
Davide Italianobd543d02016-05-25 22:29:34 +00001514 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001515}
1516
Sanjay Patel2a385e22015-01-09 16:47:20 +00001517/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001518/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001519Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001520 BasicBlock *ToBB,
1521 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001522 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001523 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001524 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001525
Chris Lattnerd5e25432009-11-12 01:29:10 +00001526 if (Result.isConstant())
1527 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001528 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001529 ConstantRange CR = Result.getConstantRange();
1530 if (const APInt *SingleVal = CR.getSingleElement())
1531 return ConstantInt::get(V->getContext(), *SingleVal);
1532 }
Craig Topper9f008862014-04-15 04:59:12 +00001533 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001534}
1535
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001536static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1537 LVILatticeVal &Result,
1538 const DataLayout &DL,
1539 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001540
Chris Lattner565ee2f2009-11-12 04:36:58 +00001541 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001542 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001543 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001544 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001545 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001546 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001547 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1548 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001549 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001550
Owen Anderson185fe002010-08-10 20:03:09 +00001551 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001552 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001553 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001554
Owen Anderson185fe002010-08-10 20:03:09 +00001555 ConstantRange CR = Result.getConstantRange();
1556 if (Pred == ICmpInst::ICMP_EQ) {
1557 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001558 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001559
Owen Anderson185fe002010-08-10 20:03:09 +00001560 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001561 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001562 } else if (Pred == ICmpInst::ICMP_NE) {
1563 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001564 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001565
Owen Anderson185fe002010-08-10 20:03:09 +00001566 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001567 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001568 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001569
Owen Anderson185fe002010-08-10 20:03:09 +00001570 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001571 ConstantRange TrueValues =
1572 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1573 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001574 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001575 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001576 return LazyValueInfo::False;
1577 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001578 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001579
Chris Lattneraf025d32009-11-15 19:59:49 +00001580 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001581 // If this is an equality comparison, we can try to fold it knowing that
1582 // "V != C1".
1583 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001584 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001585 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001586 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001587 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001588 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001589 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001590 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001591 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001592 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001593 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001594 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001595 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001596 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001597 }
Hal Finkel7e184492014-09-07 20:29:59 +00001598 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001599 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001600
Hal Finkel7e184492014-09-07 20:29:59 +00001601 return LazyValueInfo::Unknown;
1602}
1603
Sanjay Patel2a385e22015-01-09 16:47:20 +00001604/// Determine whether the specified value comparison with a constant is known to
1605/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001606LazyValueInfo::Tristate
1607LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1608 BasicBlock *FromBB, BasicBlock *ToBB,
1609 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001610 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001611 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001612 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001613
1614 return getPredicateResult(Pred, C, Result, DL, TLI);
1615}
1616
1617LazyValueInfo::Tristate
1618LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1619 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001620 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1621 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001622 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1623 if (Ret != Unknown)
1624 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001625
Philip Reamesaeefae02015-11-04 01:47:04 +00001626 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1627 // LVI as a whole tries to compute a lattice value which is conservatively
1628 // correct at a given location. In this case, we have a predicate which we
1629 // weren't able to prove about the merged result, and we're pushing that
1630 // predicate back along each incoming edge to see if we can prove it
1631 // separately for each input. As a motivating example, consider:
1632 // bb1:
1633 // %v1 = ... ; constantrange<1, 5>
1634 // br label %merge
1635 // bb2:
1636 // %v2 = ... ; constantrange<10, 20>
1637 // br label %merge
1638 // merge:
1639 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1640 // %pred = icmp eq i32 %phi, 8
1641 // We can't tell from the lattice value for '%phi' that '%pred' is false
1642 // along each path, but by checking the predicate over each input separately,
1643 // we can.
1644 // We limit the search to one step backwards from the current BB and value.
1645 // We could consider extending this to search further backwards through the
1646 // CFG and/or value graph, but there are non-obvious compile time vs quality
1647 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001648 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001649 BasicBlock *BB = CxtI->getParent();
1650
1651 // Function entry or an unreachable block. Bail to avoid confusing
1652 // analysis below.
1653 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1654 if (PI == PE)
1655 return Unknown;
1656
1657 // If V is a PHI node in the same block as the context, we need to ask
1658 // questions about the predicate as applied to the incoming value along
1659 // each edge. This is useful for eliminating cases where the predicate is
1660 // known along all incoming edges.
1661 if (auto *PHI = dyn_cast<PHINode>(V))
1662 if (PHI->getParent() == BB) {
1663 Tristate Baseline = Unknown;
1664 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1665 Value *Incoming = PHI->getIncomingValue(i);
1666 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1667 // Note that PredBB may be BB itself.
1668 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1669 CxtI);
1670
1671 // Keep going as long as we've seen a consistent known result for
1672 // all inputs.
1673 Baseline = (i == 0) ? Result /* First iteration */
1674 : (Baseline == Result ? Baseline : Unknown); /* All others */
1675 if (Baseline == Unknown)
1676 break;
1677 }
1678 if (Baseline != Unknown)
1679 return Baseline;
1680 }
1681
Philip Reames66ab0f02015-06-16 00:49:59 +00001682 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001683 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001684 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001685 if (!isa<Instruction>(V) ||
1686 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001687 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001688 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001689 // the value of the comparison in this block.
1690 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1691 if (Baseline != Unknown) {
1692 // Check that all remaining incoming values match the first one.
1693 while (++PI != PE) {
1694 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1695 if (Ret != Baseline) break;
1696 }
1697 // If we terminated early, then one of the values didn't match.
1698 if (PI == PE) {
1699 return Baseline;
1700 }
1701 }
1702 }
1703 }
1704 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001705}
1706
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001707void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001708 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001709 if (PImpl) {
1710 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1711 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1712 }
Owen Anderson208636f2010-08-18 18:39:01 +00001713}
1714
1715void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001716 if (PImpl) {
1717 const DataLayout &DL = BB->getModule()->getDataLayout();
1718 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1719 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001720}