blob: 041481411a4c6f56e8bb22166f8b17c735dec52a [file] [log] [blame]
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
Chris Lattner741c94c2009-11-11 00:22:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000029#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000030#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000031#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000032#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000034#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000035#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000036using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000037using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000038
Chandler Carruthf1221bd2014-04-22 02:48:03 +000039#define DEBUG_TYPE "lazy-value-info"
40
Chris Lattner741c94c2009-11-11 00:22:30 +000041char LazyValueInfo::ID = 0;
Chad Rosier43a33062011-12-02 01:26:24 +000042INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
43 "Lazy Value Information Analysis", false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +000044INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000045INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chad Rosier43a33062011-12-02 01:26:24 +000046INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000047 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000048
49namespace llvm {
50 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
51}
52
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000053
54//===----------------------------------------------------------------------===//
55// LVILatticeVal
56//===----------------------------------------------------------------------===//
57
Sanjay Patel2a385e22015-01-09 16:47:20 +000058/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000059///
60/// FIXME: This is basically just for bringup, this can be made a lot more rich
61/// in the future.
62///
63namespace {
64class LVILatticeVal {
65 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000066 /// This Value has no known value yet. As a result, this implies the
67 /// producing instruction is dead. Caution: We use this as the starting
68 /// state in our local meet rules. In this usage, it's taken to mean
69 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000070 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000071
Philip Reames3bb28322016-04-25 18:48:43 +000072 /// This Value has a specific constant value. (For integers, constantrange
73 /// is used instead.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000074 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000075
Philip Reames3bb28322016-04-25 18:48:43 +000076 /// This Value is known to not have the specified value. (For integers,
77 /// constantrange is used instead.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000078 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000079
Philip Reames3bb28322016-04-25 18:48:43 +000080 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000081 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000082
Philip Reames3bb28322016-04-25 18:48:43 +000083 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000084 overdefined
85 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000086
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000087 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000088 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000089 LatticeValueTy Tag;
90 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000091 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000092
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000093public:
Craig Topper9f008862014-04-15 04:59:12 +000094 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000095
Chris Lattner19019ea2009-11-11 22:48:44 +000096 static LVILatticeVal get(Constant *C) {
97 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000098 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000099 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000100 return Res;
101 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000102 static LVILatticeVal getNot(Constant *C) {
103 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000104 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000105 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000106 return Res;
107 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000108 static LVILatticeVal getRange(ConstantRange CR) {
109 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000110 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000111 return Res;
112 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000113 static LVILatticeVal getOverdefined() {
114 LVILatticeVal Res;
115 Res.markOverdefined();
116 return Res;
117 }
118
Owen Anderson0f306a42010-08-05 22:59:19 +0000119 bool isUndefined() const { return Tag == undefined; }
120 bool isConstant() const { return Tag == constant; }
121 bool isNotConstant() const { return Tag == notconstant; }
122 bool isConstantRange() const { return Tag == constantrange; }
123 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000124
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000125 Constant *getConstant() const {
126 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000127 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000128 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000129
Chris Lattner565ee2f2009-11-12 04:36:58 +0000130 Constant *getNotConstant() const {
131 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000132 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000133 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000134
Owen Anderson0f306a42010-08-05 22:59:19 +0000135 ConstantRange getConstantRange() const {
136 assert(isConstantRange() &&
137 "Cannot get the constant-range of a non-constant-range!");
138 return Range;
139 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000140
Sanjay Patel2a385e22015-01-09 16:47:20 +0000141 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000142 bool markOverdefined() {
143 if (isOverdefined())
144 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000145 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000146 return true;
147 }
148
Sanjay Patel2a385e22015-01-09 16:47:20 +0000149 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000150 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000151 assert(V && "Marking constant with NULL");
152 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
153 return markConstantRange(ConstantRange(CI->getValue()));
154 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000155 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000156
157 assert((!isConstant() || getConstant() == V) &&
158 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000159 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000160 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000161 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000162 return true;
163 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000164
Sanjay Patel2a385e22015-01-09 16:47:20 +0000165 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000166 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000167 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000168 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
169 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
170 if (isa<UndefValue>(V))
171 return false;
172
173 assert((!isConstant() || getConstant() != V) &&
174 "Marking constant !constant with same value");
175 assert((!isNotConstant() || getNotConstant() == V) &&
176 "Marking !constant with different value");
177 assert(isUndefined() || isConstant());
178 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000179 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000180 return true;
181 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000182
Sanjay Patel2a385e22015-01-09 16:47:20 +0000183 /// Return true if this is a change in status.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000184 bool markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000185 if (isConstantRange()) {
186 if (NewR.isEmptySet())
187 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000188
Nuno Lopese6e04902012-06-28 01:16:18 +0000189 bool changed = Range != NewR;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000190 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000191 return changed;
192 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000193
Owen Anderson0f306a42010-08-05 22:59:19 +0000194 assert(isUndefined());
195 if (NewR.isEmptySet())
196 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000197
Owen Anderson0f306a42010-08-05 22:59:19 +0000198 Tag = constantrange;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000199 Range = std::move(NewR);
Owen Anderson0f306a42010-08-05 22:59:19 +0000200 return true;
201 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000202
Sanjay Patel2a385e22015-01-09 16:47:20 +0000203 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000204 /// one and returning true if anything changed.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000205 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
Chris Lattner19019ea2009-11-11 22:48:44 +0000206 if (RHS.isUndefined() || isOverdefined()) return false;
207 if (RHS.isOverdefined()) return markOverdefined();
208
Nick Lewycky11678bd2010-12-15 18:57:18 +0000209 if (isUndefined()) {
210 Tag = RHS.Tag;
211 Val = RHS.Val;
212 Range = RHS.Range;
213 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000214 }
215
Nick Lewycky11678bd2010-12-15 18:57:18 +0000216 if (isConstant()) {
217 if (RHS.isConstant()) {
218 if (Val == RHS.Val)
219 return false;
220 return markOverdefined();
221 }
222
223 if (RHS.isNotConstant()) {
224 if (Val == RHS.Val)
225 return markOverdefined();
226
227 // Unless we can prove that the two Constants are different, we must
228 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000229 if (ConstantInt *Res =
230 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
231 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000232 if (Res->isOne())
233 return markNotConstant(RHS.getNotConstant());
234
235 return markOverdefined();
236 }
237
Chris Lattner19019ea2009-11-11 22:48:44 +0000238 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000239 }
240
241 if (isNotConstant()) {
242 if (RHS.isConstant()) {
243 if (Val == RHS.Val)
244 return markOverdefined();
245
246 // Unless we can prove that the two Constants are different, we must
247 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248 if (ConstantInt *Res =
249 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
250 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000251 if (Res->isOne())
252 return false;
253
254 return markOverdefined();
255 }
256
257 if (RHS.isNotConstant()) {
258 if (Val == RHS.Val)
259 return false;
260 return markOverdefined();
261 }
262
263 return markOverdefined();
264 }
265
266 assert(isConstantRange() && "New LVILattice type?");
267 if (!RHS.isConstantRange())
268 return markOverdefined();
269
270 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
271 if (NewR.isFullSet())
272 return markOverdefined();
273 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000274 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000275};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000276
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000277} // end anonymous namespace.
278
Chris Lattner19019ea2009-11-11 22:48:44 +0000279namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000280raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
281 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000282raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
283 if (Val.isUndefined())
284 return OS << "undefined";
285 if (Val.isOverdefined())
286 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000287
288 if (Val.isNotConstant())
289 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000290 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000291 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
292 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000293 return OS << "constant<" << *Val.getConstant() << '>';
294}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000295}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000296
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000297/// Returns true if this lattice value represents at most one possible value.
298/// This is as precise as any lattice value can get while still representing
299/// reachable code.
300static bool hasSingleValue(LVILatticeVal Val) {
301 if (Val.isConstantRange() &&
302 Val.getConstantRange().isSingleElement())
303 // Integer constants are single element ranges
304 return true;
305 if (Val.isConstant())
306 // Non integer constants
307 return true;
308 return false;
309}
310
311/// Combine two sets of facts about the same value into a single set of
312/// facts. Note that this method is not suitable for merging facts along
313/// different paths in a CFG; that's what the mergeIn function is for. This
314/// is for merging facts gathered about the same value at the same location
315/// through two independent means.
316/// Notes:
317/// * This method does not promise to return the most precise possible lattice
318/// value implied by A and B. It is allowed to return any lattice element
319/// which is at least as strong as *either* A or B (unless our facts
320/// conflict, see below).
321/// * Due to unreachable code, the intersection of two lattice values could be
322/// contradictory. If this happens, we return some valid lattice value so as
323/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
324/// we do not make this guarantee. TODO: This would be a useful enhancement.
325static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
326 // Undefined is the strongest state. It means the value is known to be along
327 // an unreachable path.
328 if (A.isUndefined())
329 return A;
330 if (B.isUndefined())
331 return B;
332
333 // If we gave up for one, but got a useable fact from the other, use it.
334 if (A.isOverdefined())
335 return B;
336 if (B.isOverdefined())
337 return A;
338
339 // Can't get any more precise than constants.
340 if (hasSingleValue(A))
341 return A;
342 if (hasSingleValue(B))
343 return B;
344
345 // Could be either constant range or not constant here.
346 if (!A.isConstantRange() || !B.isConstantRange()) {
347 // TODO: Arbitrary choice, could be improved
348 return A;
349 }
350
351 // Intersect two constant ranges
352 ConstantRange Range =
353 A.getConstantRange().intersectWith(B.getConstantRange());
354 // Note: An empty range is implicitly converted to overdefined internally.
355 // TODO: We could instead use Undefined here since we've proven a conflict
356 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000357 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000358}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000359
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000360//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000361// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000362//===----------------------------------------------------------------------===//
363
Chris Lattneraf025d32009-11-15 19:59:49 +0000364namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000365 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000366 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000367 struct LVIValueHandle final : public CallbackVH {
Owen Anderson118ac802011-01-05 21:15:29 +0000368 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000369
Owen Anderson118ac802011-01-05 21:15:29 +0000370 LVIValueHandle(Value *V, LazyValueInfoCache *P)
371 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000372
373 void deleted() override;
374 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000375 deleted();
376 }
377 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000378}
Owen Anderson118ac802011-01-05 21:15:29 +0000379
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000380namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000381 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000382 /// maintains information about queries across the clients' queries.
383 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000384 /// This is all of the cached block information for exactly one Value*.
385 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000386 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000387 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
388 /// memory overhead.
Bruno Cardoso Lopes1846ea32015-08-18 16:54:36 +0000389 typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
390 ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000391
Sanjay Patel2a385e22015-01-09 16:47:20 +0000392 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000393 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000394 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000395
Sanjay Patel2a385e22015-01-09 16:47:20 +0000396 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000397 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000398 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
399 OverDefinedCacheTy;
400 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000401
Sanjay Patel2a385e22015-01-09 16:47:20 +0000402 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000403 /// don't spend time removing unused blocks from our caches.
404 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
405
Sanjay Patel2a385e22015-01-09 16:47:20 +0000406 /// This stack holds the state of the value solver during a query.
407 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000408 /// recursive value lookup process.
409 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000410
Sanjay Patel2a385e22015-01-09 16:47:20 +0000411 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000412 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
413
Sanjay Patel2a385e22015-01-09 16:47:20 +0000414 /// Push BV onto BlockValueStack unless it's already in there.
415 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000416 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000417 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000418 return false; // It's already in the stack.
419
Philip Reames44456b82016-02-02 03:15:40 +0000420 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
421 << "\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000422 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000423 return true;
424 }
425
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000426 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
427 const DataLayout &DL; ///< A mandatory DataLayout
428 DominatorTree *DT; ///< An optional DT pointer.
429
Owen Anderson118ac802011-01-05 21:15:29 +0000430 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000431
Hans Wennborg45172ac2014-11-25 17:23:05 +0000432 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
433 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000434
435 // Insert over-defined values into their own cache to reduce memory
436 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000437 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000438 OverDefinedCache[BB].insert(Val);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000439 else
440 lookup(Val)[BB] = Result;
Hans Wennborg45172ac2014-11-25 17:23:05 +0000441 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000442
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000443 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000444 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000445 LVILatticeVal &Result,
446 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000447 bool hasBlockValue(Value *Val, BasicBlock *BB);
448
449 // These methods process one work item and may add more. A false value
450 // returned means that the work item was not completely processed and must
451 // be revisited after going through the new items.
452 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000453 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
454 Value *Val, BasicBlock *BB);
455 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
456 PHINode *PN, BasicBlock *BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000457 bool solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +0000458 SelectInst *S, BasicBlock *BB);
459 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV,
460 Instruction *BBI, BasicBlock *BB);
461 bool solveBlockValueCast(LVILatticeVal &BBLV,
462 Instruction *BBI, BasicBlock *BB);
463 void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
Hal Finkel7e184492014-09-07 20:29:59 +0000464 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000465
466 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000467
Nick Lewycky11678bd2010-12-15 18:57:18 +0000468 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000469 return ValueCache[LVIValueHandle(V, this)];
470 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000471
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000472 bool isOverdefined(Value *V, BasicBlock *BB) const {
473 auto ODI = OverDefinedCache.find(BB);
474
475 if (ODI == OverDefinedCache.end())
476 return false;
477
478 return ODI->second.count(V);
479 }
480
481 bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
482 if (isOverdefined(V, BB))
483 return true;
484
485 LVIValueHandle ValHandle(V, this);
486 auto I = ValueCache.find(ValHandle);
487 if (I == ValueCache.end())
488 return false;
489
490 return I->second.count(BB);
491 }
492
493 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
494 if (isOverdefined(V, BB))
495 return LVILatticeVal::getOverdefined();
496
497 return lookup(V)[BB];
498 }
499
Chris Lattneraf025d32009-11-15 19:59:49 +0000500 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000501 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000502 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000503 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
504 Instruction *CxtI = nullptr);
505
Sanjay Patel2a385e22015-01-09 16:47:20 +0000506 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000507 /// value for the specified Value* at the specified instruction (generally
508 /// from an assume intrinsic).
509 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000510
Sanjay Patel2a385e22015-01-09 16:47:20 +0000511 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000512 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000513 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
514 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000515
Sanjay Patel2a385e22015-01-09 16:47:20 +0000516 /// This is the update interface to inform the cache that an edge from
517 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000518 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000519
Sanjay Patel2a385e22015-01-09 16:47:20 +0000520 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000521 /// that a block has been deleted.
522 void eraseBlock(BasicBlock *BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000523
Owen Anderson208636f2010-08-18 18:39:01 +0000524 /// clear - Empty the cache.
525 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000526 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000527 ValueCache.clear();
528 OverDefinedCache.clear();
529 }
Hal Finkel7e184492014-09-07 20:29:59 +0000530
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000531 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000532 DominatorTree *DT = nullptr)
533 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000534 };
535} // end anonymous namespace
536
Owen Anderson118ac802011-01-05 21:15:29 +0000537void LVIValueHandle::deleted() {
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000538 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
539 for (auto &I : Parent->OverDefinedCache) {
540 SmallPtrSetImpl<Value *> &ValueSet = I.second;
541 if (ValueSet.count(getValPtr()))
542 ValueSet.erase(getValPtr());
543 if (ValueSet.empty())
544 ToErase.push_back(I.first);
545 }
546 for (auto &BB : ToErase)
547 Parent->OverDefinedCache.erase(BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000548
Owen Anderson7b974a42010-08-11 22:36:04 +0000549 // This erasure deallocates *this, so it MUST happen after we're done
550 // using any and all members of *this.
551 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000552}
553
Owen Anderson208636f2010-08-18 18:39:01 +0000554void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000555 // Shortcut if we have never seen this block.
556 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
557 if (I == SeenBlocks.end())
558 return;
559 SeenBlocks.erase(I);
560
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000561 auto ODI = OverDefinedCache.find(BB);
562 if (ODI != OverDefinedCache.end())
563 OverDefinedCache.erase(ODI);
Owen Anderson208636f2010-08-18 18:39:01 +0000564
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000565 for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
Owen Anderson208636f2010-08-18 18:39:01 +0000566 I->second.erase(BB);
567}
Owen Andersonc1561b82010-07-30 23:59:40 +0000568
Nick Lewycky55a700b2010-12-18 01:00:40 +0000569void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000570 while (!BlockValueStack.empty()) {
571 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000572 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
573
Nuno Lopese6e04902012-06-28 01:16:18 +0000574 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000575 // The work item was completely processed.
576 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000577 assert(hasCachedValueInfo(e.second, e.first) &&
578 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000579
Philip Reames44456b82016-02-02 03:15:40 +0000580 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000581 << " = " << getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000582
Owen Anderson6f060af2011-01-05 23:26:22 +0000583 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000584 BlockValueSet.erase(e);
585 } else {
586 // More work needs to be done before revisiting.
587 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000588 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000589 }
590}
591
592bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
593 // If already a constant, there is nothing to compute.
594 if (isa<Constant>(Val))
595 return true;
596
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000597 return hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000598}
599
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000600LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000601 // If already a constant, there is nothing to compute.
602 if (Constant *VC = dyn_cast<Constant>(Val))
603 return LVILatticeVal::get(VC);
604
Benjamin Kramer36647082011-12-03 15:16:45 +0000605 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000606 return getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000607}
608
Philip Reameseb3e9da2015-10-29 03:57:17 +0000609static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
610 switch (BBI->getOpcode()) {
611 default: break;
612 case Instruction::Load:
613 case Instruction::Call:
614 case Instruction::Invoke:
615 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000616 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000617 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000618 }
619 break;
620 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000621 // Nothing known - will be intersected with other facts
622 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000623}
624
Nick Lewycky55a700b2010-12-18 01:00:40 +0000625bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
626 if (isa<Constant>(Val))
627 return true;
628
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000629 if (hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000630 // If we have a cached value, use that.
631 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000632 << "' val=" << getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000633
Hans Wennborg45172ac2014-11-25 17:23:05 +0000634 // Since we're reusing a cached value, we don't need to update the
635 // OverDefinedCache. The cache will have been properly updated whenever the
636 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000637 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000638 }
639
Hans Wennborg45172ac2014-11-25 17:23:05 +0000640 // Hold off inserting this value into the Cache in case we have to return
641 // false and come back later.
642 LVILatticeVal Res;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000643
Chris Lattneraf025d32009-11-15 19:59:49 +0000644 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000645 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000646 if (!solveBlockValueNonLocal(Res, Val, BB))
647 return false;
648 insertResult(Val, BB, Res);
649 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000650 }
Chris Lattner2c708562009-11-15 20:00:52 +0000651
Nick Lewycky55a700b2010-12-18 01:00:40 +0000652 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000653 if (!solveBlockValuePHINode(Res, PN, BB))
654 return false;
655 insertResult(Val, BB, Res);
656 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000657 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000658
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000659 if (auto *SI = dyn_cast<SelectInst>(BBI)) {
660 if (!solveBlockValueSelect(Res, SI, BB))
661 return false;
662 insertResult(Val, BB, Res);
663 return true;
664 }
665
Philip Reames2ab964e2016-04-27 01:02:25 +0000666 // If this value is a nonnull pointer, record it's range and bailout. Note
667 // that for all other pointer typed values, we terminate the search at the
668 // definition. We could easily extend this to look through geps, bitcasts,
669 // and the like to prove non-nullness, but it's not clear that's worth it
670 // compile time wise. The context-insensative value walk done inside
671 // isKnownNonNull gets most of the profitable cases at much less expense.
672 // This does mean that we have a sensativity to where the defining
673 // instruction is placed, even if it could legally be hoisted much higher.
674 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000675 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
676 if (PT && isKnownNonNull(BBI)) {
677 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000678 insertResult(Val, BB, Res);
679 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000680 }
Davide Italianobd543d02016-05-25 22:29:34 +0000681 if (BBI->getType()->isIntegerTy()) {
Philip Reames2ab964e2016-04-27 01:02:25 +0000682 if (isa<CastInst>(BBI)) {
683 if (!solveBlockValueCast(Res, BBI, BB))
684 return false;
685 insertResult(Val, BB, Res);
686 return true;
687 }
688 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
689 if (BO && isa<ConstantInt>(BO->getOperand(1))) {
690 if (!solveBlockValueBinaryOp(Res, BBI, BB))
691 return false;
692 insertResult(Val, BB, Res);
693 return true;
694 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000695 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000696
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000697 DEBUG(dbgs() << " compute BB '" << BB->getName()
698 << "' - unknown inst def found.\n");
699 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000700 insertResult(Val, BB, Res);
701 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000702}
703
704static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
705 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
706 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000707 GetUnderlyingObject(L->getPointerOperand(),
708 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000709 }
710 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
711 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000712 GetUnderlyingObject(S->getPointerOperand(),
713 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000714 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000715 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
716 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000717
718 // FIXME: check whether it has a valuerange that excludes zero?
719 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
720 if (!Len || Len->isZero()) return false;
721
Eli Friedman7a5fc692011-05-31 20:40:16 +0000722 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000723 if (GetUnderlyingObject(MI->getRawDest(),
724 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000725 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000726 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000727 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000728 if (GetUnderlyingObject(MTI->getRawSource(),
729 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000730 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000731 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000732 return false;
733}
734
Philip Reames3f83dbe2016-04-27 00:30:55 +0000735/// Return true if the allocation associated with Val is ever dereferenced
736/// within the given basic block. This establishes the fact Val is not null,
737/// but does not imply that the memory at Val is dereferenceable. (Val may
738/// point off the end of the dereferenceable part of the object.)
739static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
740 assert(Val->getType()->isPointerTy());
741
742 const DataLayout &DL = BB->getModule()->getDataLayout();
743 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
744 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
745 // inside InstructionDereferencesPointer either.
746 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
747 for (Instruction &I : *BB)
748 if (InstructionDereferencesPointer(&I, UnderlyingVal))
749 return true;
750 return false;
751}
752
Owen Anderson64c2c572010-12-20 18:18:16 +0000753bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
754 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000755 LVILatticeVal Result; // Start Undefined.
756
Nick Lewycky55a700b2010-12-18 01:00:40 +0000757 // If this is the entry block, we must be asking about an argument. The
758 // value is overdefined.
759 if (BB == &BB->getParent()->getEntryBlock()) {
760 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000761 // Bofore giving up, see if we can prove the pointer non-null local to
762 // this particular block.
763 if (Val->getType()->isPointerTy() &&
764 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000765 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000766 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
767 } else {
768 Result.markOverdefined();
769 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000770 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000771 return true;
772 }
773
774 // Loop over all of our predecessors, merging what we know from them into
775 // result.
776 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000777 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000778 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000779 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000780 if (EdgesMissing)
781 continue;
782
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000783 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000784
785 // If we hit overdefined, exit early. The BlockVals entry is already set
786 // to overdefined.
787 if (Result.isOverdefined()) {
788 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000789 << "' - overdefined because of pred (non local).\n");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000790 // Bofore giving up, see if we can prove the pointer non-null local to
791 // this particular block.
792 if (Val->getType()->isPointerTy() &&
793 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000794 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000795 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
796 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000797
Owen Anderson64c2c572010-12-20 18:18:16 +0000798 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000799 return true;
800 }
801 }
802 if (EdgesMissing)
803 return false;
804
805 // Return the merged value, which is more precise than 'overdefined'.
806 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000807 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000808 return true;
809}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000810
Owen Anderson64c2c572010-12-20 18:18:16 +0000811bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
812 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000813 LVILatticeVal Result; // Start Undefined.
814
815 // Loop over all of our predecessors, merging what we know from them into
816 // result.
817 bool EdgesMissing = false;
818 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
819 BasicBlock *PhiBB = PN->getIncomingBlock(i);
820 Value *PhiVal = PN->getIncomingValue(i);
821 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000822 // Note that we can provide PN as the context value to getEdgeValue, even
823 // though the results will be cached, because PN is the value being used as
824 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000825 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000826 if (EdgesMissing)
827 continue;
828
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000829 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000830
831 // If we hit overdefined, exit early. The BlockVals entry is already set
832 // to overdefined.
833 if (Result.isOverdefined()) {
834 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000835 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000836
Owen Anderson64c2c572010-12-20 18:18:16 +0000837 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000838 return true;
839 }
840 }
841 if (EdgesMissing)
842 return false;
843
844 // Return the merged value, which is more precise than 'overdefined'.
845 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000846 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000847 return true;
848}
849
Hal Finkel7e184492014-09-07 20:29:59 +0000850static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
851 LVILatticeVal &Result,
852 bool isTrueDest = true);
853
Philip Reamesd1f829d2016-02-02 21:57:37 +0000854// If we can determine a constraint on the value given conditions assumed by
855// the program, intersect those constraints with BBLV
856void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000857 LVILatticeVal &BBLV,
858 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000859 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
860 if (!BBI)
861 return;
862
Chandler Carruth66b31302015-01-04 12:03:27 +0000863 for (auto &AssumeVH : AC->assumptions()) {
864 if (!AssumeVH)
865 continue;
866 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000867 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000868 continue;
869
870 Value *C = I->getArgOperand(0);
871 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
872 LVILatticeVal Result;
Philip Reamesd1f829d2016-02-02 21:57:37 +0000873 if (getValueFromFromCondition(Val, ICI, Result))
874 BBLV = intersect(BBLV, Result);
Hal Finkel7e184492014-09-07 20:29:59 +0000875 }
876 }
877}
878
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000879bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
880 SelectInst *SI, BasicBlock *BB) {
881
882 // Recurse on our inputs if needed
883 if (!hasBlockValue(SI->getTrueValue(), BB)) {
884 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
885 return false;
886 BBLV.markOverdefined();
887 return true;
888 }
889 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
890 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
891 // extra slots in the table if we can.
892 if (TrueVal.isOverdefined()) {
893 BBLV.markOverdefined();
894 return true;
895 }
896
897 if (!hasBlockValue(SI->getFalseValue(), BB)) {
898 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
899 return false;
900 BBLV.markOverdefined();
901 return true;
902 }
903 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
904 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
905 // extra slots in the table if we can.
906 if (FalseVal.isOverdefined()) {
907 BBLV.markOverdefined();
908 return true;
909 }
910
Philip Reamesadf0e352016-02-26 22:53:59 +0000911 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
912 ConstantRange TrueCR = TrueVal.getConstantRange();
913 ConstantRange FalseCR = FalseVal.getConstantRange();
914 Value *LHS = nullptr;
915 Value *RHS = nullptr;
916 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
917 // Is this a min specifically of our two inputs? (Avoid the risk of
918 // ValueTracking getting smarter looking back past our immediate inputs.)
919 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
920 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
921 switch (SPR.Flavor) {
922 default:
923 llvm_unreachable("unexpected minmax type!");
924 case SPF_SMIN: /// Signed minimum
925 BBLV.markConstantRange(TrueCR.smin(FalseCR));
926 return true;
927 case SPF_UMIN: /// Unsigned minimum
928 BBLV.markConstantRange(TrueCR.umin(FalseCR));
929 return true;
930 case SPF_SMAX: /// Signed maximum
931 BBLV.markConstantRange(TrueCR.smax(FalseCR));
932 return true;
933 case SPF_UMAX: /// Unsigned maximum
934 BBLV.markConstantRange(TrueCR.umax(FalseCR));
935 return true;
936 };
937 }
938
939 // TODO: ABS, NABS from the SelectPatternResult
940 }
941
Philip Reames854a84c2016-02-12 00:09:18 +0000942 // Can we constrain the facts about the true and false values by using the
943 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
944 // TODO: We could potentially refine an overdefined true value above.
945 if (auto *ICI = dyn_cast<ICmpInst>(SI->getCondition())) {
946 LVILatticeVal TrueValTaken, FalseValTaken;
947 if (!getValueFromFromCondition(SI->getTrueValue(), ICI,
948 TrueValTaken, true))
949 TrueValTaken.markOverdefined();
950 if (!getValueFromFromCondition(SI->getFalseValue(), ICI,
951 FalseValTaken, false))
952 FalseValTaken.markOverdefined();
953
954 TrueVal = intersect(TrueVal, TrueValTaken);
955 FalseVal = intersect(FalseVal, FalseValTaken);
Philip Reames854a84c2016-02-12 00:09:18 +0000956
Philip Reamesadf0e352016-02-26 22:53:59 +0000957
958 // Handle clamp idioms such as:
959 // %24 = constantrange<0, 17>
960 // %39 = icmp eq i32 %24, 0
961 // %40 = add i32 %24, -1
962 // %siv.next = select i1 %39, i32 16, i32 %40
963 // %siv.next = constantrange<0, 17> not <-1, 17>
964 // In general, this can handle any clamp idiom which tests the edge
965 // condition via an equality or inequality.
966 ICmpInst::Predicate Pred = ICI->getPredicate();
967 Value *A = ICI->getOperand(0);
968 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
969 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
970 assert(A->getType() == B->getType());
971 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
972 };
973 // See if either input is A + C2, subject to the constraint from the
974 // condition that A != C when that input is used. We can assume that
975 // that input doesn't include C + C2.
976 ConstantInt *CIAdded;
977 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +0000978 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +0000979 case ICmpInst::ICMP_EQ:
980 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
981 m_ConstantInt(CIAdded)))) {
982 auto ResNot = addConstants(CIBase, CIAdded);
983 FalseVal = intersect(FalseVal,
984 LVILatticeVal::getNot(ResNot));
985 }
986 break;
987 case ICmpInst::ICMP_NE:
988 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
989 m_ConstantInt(CIAdded)))) {
990 auto ResNot = addConstants(CIBase, CIAdded);
991 TrueVal = intersect(TrueVal,
992 LVILatticeVal::getNot(ResNot));
993 }
994 break;
995 };
996 }
997 }
Philip Reames854a84c2016-02-12 00:09:18 +0000998
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000999 LVILatticeVal Result; // Start Undefined.
1000 Result.mergeIn(TrueVal, DL);
1001 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001002 BBLV = Result;
1003 return true;
1004}
1005
Philip Reames66715772016-04-25 18:30:31 +00001006bool LazyValueInfoCache::solveBlockValueCast(LVILatticeVal &BBLV,
1007 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001008 BasicBlock *BB) {
1009 if (!BBI->getOperand(0)->getType()->isSized()) {
1010 // Without knowing how wide the input is, we can't analyze it in any useful
1011 // way.
1012 BBLV.markOverdefined();
1013 return true;
1014 }
Philip Reamesf105db42016-04-26 23:27:33 +00001015
1016 // Filter out casts we don't know how to reason about before attempting to
1017 // recurse on our operand. This can cut a long search short if we know we're
1018 // not going to be able to get any useful information anways.
1019 switch (BBI->getOpcode()) {
1020 case Instruction::Trunc:
1021 case Instruction::SExt:
1022 case Instruction::ZExt:
1023 case Instruction::BitCast:
1024 break;
1025 default:
1026 // Unhandled instructions are overdefined.
1027 DEBUG(dbgs() << " compute BB '" << BB->getName()
1028 << "' - overdefined (unknown cast).\n");
1029 BBLV.markOverdefined();
1030 return true;
1031 }
1032
Philip Reamese5030e82016-04-26 22:52:30 +00001033
Philip Reames38c87c22016-04-26 21:48:16 +00001034 // Figure out the range of the LHS. If that fails, we still apply the
1035 // transfer rule on the full set since we may be able to locally infer
1036 // interesting facts.
1037 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001038 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001039 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001040 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001041
1042 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001043 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001044 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1045 if (hasBlockValue(BBI->getOperand(0), BB)) {
1046 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1047 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1048 if (LHSVal.isConstantRange())
1049 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001050 }
1051
Philip Reames38c87c22016-04-26 21:48:16 +00001052 const unsigned ResultBitWidth =
1053 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001054
1055 // NOTE: We're currently limited by the set of operations that ConstantRange
1056 // can evaluate symbolically. Enhancing that set will allows us to analyze
1057 // more definitions.
1058 LVILatticeVal Result;
1059 switch (BBI->getOpcode()) {
1060 case Instruction::Trunc:
Philip Reames38c87c22016-04-26 21:48:16 +00001061 Result.markConstantRange(LHSRange.truncate(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001062 break;
1063 case Instruction::SExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001064 Result.markConstantRange(LHSRange.signExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001065 break;
1066 case Instruction::ZExt:
Philip Reames38c87c22016-04-26 21:48:16 +00001067 Result.markConstantRange(LHSRange.zeroExtend(ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001068 break;
1069 case Instruction::BitCast:
1070 Result.markConstantRange(LHSRange);
1071 break;
Philip Reames66715772016-04-25 18:30:31 +00001072 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001073 // Should be dead if the code above is correct
1074 llvm_unreachable("inconsistent with above");
Philip Reames66715772016-04-25 18:30:31 +00001075 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001076 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001077
Philip Reames66715772016-04-25 18:30:31 +00001078 BBLV = Result;
1079 return true;
1080}
1081
1082bool LazyValueInfoCache::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
1083 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001084 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001085
Philip Reames053c2a62016-04-26 23:10:35 +00001086 assert(BBI->getOperand(0)->getType()->isSized() &&
1087 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001088
1089 // Filter out operators we don't know how to reason about before attempting to
1090 // recurse on our operand(s). This can cut a long search short if we know
1091 // we're not going to be able to get any useful information anways.
1092 switch (BBI->getOpcode()) {
1093 case Instruction::Add:
1094 case Instruction::Sub:
1095 case Instruction::Mul:
1096 case Instruction::UDiv:
1097 case Instruction::Shl:
1098 case Instruction::LShr:
1099 case Instruction::And:
1100 case Instruction::Or:
1101 // continue into the code below
1102 break;
1103 default:
1104 // Unhandled instructions are overdefined.
1105 DEBUG(dbgs() << " compute BB '" << BB->getName()
1106 << "' - overdefined (unknown binary operator).\n");
1107 BBLV.markOverdefined();
1108 return true;
1109 };
Philip Reames053c2a62016-04-26 23:10:35 +00001110
1111 // Figure out the range of the LHS. If that fails, use a conservative range,
1112 // but apply the transfer rule anyways. This lets us pick up facts from
1113 // expressions like "and i32 (call i32 @foo()), 32"
1114 if (!hasBlockValue(BBI->getOperand(0), BB))
1115 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1116 // More work to do before applying this transfer rule.
1117 return false;
1118
1119 const unsigned OperandBitWidth =
1120 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1121 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1122 if (hasBlockValue(BBI->getOperand(0), BB)) {
1123 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1124 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1125 if (LHSVal.isConstantRange())
1126 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001127 }
Philip Reames66715772016-04-25 18:30:31 +00001128
1129 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1130 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1131
Owen Anderson80d19f02010-08-18 21:11:37 +00001132 // NOTE: We're currently limited by the set of operations that ConstantRange
1133 // can evaluate symbolically. Enhancing that set will allows us to analyze
1134 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +00001135 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +00001136 switch (BBI->getOpcode()) {
1137 case Instruction::Add:
1138 Result.markConstantRange(LHSRange.add(RHSRange));
1139 break;
1140 case Instruction::Sub:
1141 Result.markConstantRange(LHSRange.sub(RHSRange));
1142 break;
1143 case Instruction::Mul:
1144 Result.markConstantRange(LHSRange.multiply(RHSRange));
1145 break;
1146 case Instruction::UDiv:
1147 Result.markConstantRange(LHSRange.udiv(RHSRange));
1148 break;
1149 case Instruction::Shl:
1150 Result.markConstantRange(LHSRange.shl(RHSRange));
1151 break;
1152 case Instruction::LShr:
1153 Result.markConstantRange(LHSRange.lshr(RHSRange));
1154 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +00001155 case Instruction::And:
1156 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
1157 break;
1158 case Instruction::Or:
1159 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
1160 break;
Owen Anderson80d19f02010-08-18 21:11:37 +00001161 default:
Philip Reamesf105db42016-04-26 23:27:33 +00001162 // Should be dead if the code above is correct
1163 llvm_unreachable("inconsistent with above");
Owen Anderson80d19f02010-08-18 21:11:37 +00001164 break;
1165 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001166
Owen Anderson64c2c572010-12-20 18:18:16 +00001167 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +00001168 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001169}
1170
Hal Finkel7e184492014-09-07 20:29:59 +00001171bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
1172 LVILatticeVal &Result, bool isTrueDest) {
Philip Reames19183842016-04-25 22:21:24 +00001173 assert(ICI && "precondition");
1174 if (isa<Constant>(ICI->getOperand(1))) {
Hal Finkel7e184492014-09-07 20:29:59 +00001175 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
1176 // We know that V has the RHS constant if this is a true SETEQ or
1177 // false SETNE.
1178 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
1179 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
1180 else
1181 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
1182 return true;
1183 }
1184
1185 // Recognize the range checking idiom that InstCombine produces.
1186 // (X-C1) u< C2 --> [C1, C1+C2)
1187 ConstantInt *NegOffset = nullptr;
1188 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
1189 match(ICI->getOperand(0), m_Add(m_Specific(Val),
1190 m_ConstantInt(NegOffset)));
1191
1192 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
1193 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Sanjoy Das7182d362015-03-18 00:41:24 +00001194 // Calculate the range of values that are allowed by the comparison
Hal Finkel7e184492014-09-07 20:29:59 +00001195 ConstantRange CmpRange(CI->getValue());
1196 ConstantRange TrueValues =
Sanjoy Das7182d362015-03-18 00:41:24 +00001197 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
Hal Finkel7e184492014-09-07 20:29:59 +00001198
1199 if (NegOffset) // Apply the offset from above.
1200 TrueValues = TrueValues.subtract(NegOffset->getValue());
1201
1202 // If we're interested in the false dest, invert the condition.
1203 if (!isTrueDest) TrueValues = TrueValues.inverse();
1204
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001205 Result = LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001206 return true;
1207 }
1208 }
Philip Reames38c87c22016-04-26 21:48:16 +00001209
Hal Finkel7e184492014-09-07 20:29:59 +00001210 return false;
1211}
1212
Nuno Lopese6e04902012-06-28 01:16:18 +00001213/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001214/// Val is not constrained on the edge. Result is unspecified if return value
1215/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001216static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1217 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001218 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001219 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001220 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1221 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001222 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001223 if (BI->isConditional() &&
1224 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1225 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1226 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1227 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001228
Chris Lattner19019ea2009-11-11 22:48:44 +00001229 // If V is the condition of the branch itself, then we know exactly what
1230 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001231 if (BI->getCondition() == Val) {
1232 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001233 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001234 return true;
1235 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001236
Chris Lattner19019ea2009-11-11 22:48:44 +00001237 // If the condition of the branch is an equality comparison, we may be
1238 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +00001239 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
1240 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
1241 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001242 }
1243 }
Chris Lattner77358782009-11-15 20:02:12 +00001244
1245 // If the edge was formed by a switch on the value, then we may know exactly
1246 // what it is.
1247 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001248 if (SI->getCondition() != Val)
1249 return false;
1250
1251 bool DefaultCase = SI->getDefaultDest() == BBTo;
1252 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1253 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1254
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001255 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001256 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001257 if (DefaultCase) {
1258 // It is possible that the default destination is the destination of
1259 // some cases. There is no need to perform difference for those cases.
1260 if (i.getCaseSuccessor() != BBTo)
1261 EdgesVals = EdgesVals.difference(EdgeVal);
1262 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001263 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001264 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001265 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001266 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001267 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001268 return false;
1269}
1270
Sanjay Patel938e2792015-01-09 16:35:37 +00001271/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1272/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +00001273bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001274 BasicBlock *BBTo, LVILatticeVal &Result,
1275 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001276 // If already a constant, there is nothing to compute.
1277 if (Constant *VC = dyn_cast<Constant>(Val)) {
1278 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001279 return true;
1280 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001281
Philip Reames44456b82016-02-02 03:15:40 +00001282 LVILatticeVal LocalResult;
1283 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1284 // If we couldn't constrain the value on the edge, LocalResult doesn't
1285 // provide any information.
1286 LocalResult.markOverdefined();
1287
1288 if (hasSingleValue(LocalResult)) {
1289 // Can't get any more precise here
1290 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001291 return true;
1292 }
1293
1294 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001295 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1296 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001297 // No new information.
1298 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001299 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001300 }
1301
Philip Reames44456b82016-02-02 03:15:40 +00001302 // Try to intersect ranges of the BB and the constraint on the edge.
1303 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001304 intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001305 // We can use the context instruction (generically the ultimate instruction
1306 // the calling pass is trying to simplify) here, even though the result of
1307 // this function is generally cached when called from the solve* functions
1308 // (and that cached result might be used with queries using a different
1309 // context instruction), because when this function is called from the solve*
1310 // functions, the context instruction is not provided. When called from
1311 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1312 // but then the result is not cached.
Philip Reamesd1f829d2016-02-02 21:57:37 +00001313 intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001314
1315 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001316 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001317}
1318
Hal Finkel7e184492014-09-07 20:29:59 +00001319LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1320 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001321 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001322 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001323
Hans Wennborg45172ac2014-11-25 17:23:05 +00001324 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001325 if (!hasBlockValue(V, BB)) {
1326 pushBlockValue(std::make_pair(BB, V));
1327 solve();
1328 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001329 LVILatticeVal Result = getBlockValue(V, BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001330 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001331
1332 DEBUG(dbgs() << " Result = " << Result << "\n");
1333 return Result;
1334}
1335
1336LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1337 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1338 << CxtI->getName() << "'\n");
1339
Philip Reamesbb781b42016-02-10 21:46:32 +00001340 if (auto *C = dyn_cast<Constant>(V))
1341 return LVILatticeVal::get(C);
1342
Philip Reamesd1f829d2016-02-02 21:57:37 +00001343 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001344 if (auto *I = dyn_cast<Instruction>(V))
1345 Result = getFromRangeMetadata(I);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001346 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001347
David Greene37e98092009-12-23 20:43:58 +00001348 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001349 return Result;
1350}
Chris Lattner19019ea2009-11-11 22:48:44 +00001351
Chris Lattneraf025d32009-11-15 19:59:49 +00001352LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001353getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1354 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001355 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001356 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001357
Nick Lewycky55a700b2010-12-18 01:00:40 +00001358 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001359 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001360 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001361 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001362 (void)WasFastQuery;
1363 assert(WasFastQuery && "More work to do after problem solved?");
1364 }
1365
David Greene37e98092009-12-23 20:43:58 +00001366 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001367 return Result;
1368}
1369
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001370void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1371 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001372 // When an edge in the graph has been threaded, values that we could not
1373 // determine a value for before (i.e. were marked overdefined) may be
1374 // possible to solve now. We do NOT try to proactively update these values.
1375 // Instead, we clear their entries from the cache, and allow lazy updating to
1376 // recompute them when needed.
1377
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001378 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001379 // for all values that were marked overdefined in OldSucc, and for those same
1380 // values in any successor of OldSucc (except NewSucc) in which they were
1381 // also marked overdefined.
1382 std::vector<BasicBlock*> worklist;
1383 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001384
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001385 auto I = OverDefinedCache.find(OldSucc);
1386 if (I == OverDefinedCache.end())
1387 return; // Nothing to process here.
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001388 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001389
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001390 // Use a worklist to perform a depth-first search of OldSucc's successors.
1391 // NOTE: We do not need a visited list since any blocks we have already
1392 // visited will have had their overdefined markers cleared already, and we
1393 // thus won't loop to their successors.
1394 while (!worklist.empty()) {
1395 BasicBlock *ToUpdate = worklist.back();
1396 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001397
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001398 // Skip blocks only accessible through NewSucc.
1399 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001400
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001401 bool changed = false;
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001402 for (Value *V : ValsToClear) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001403 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001404 auto OI = OverDefinedCache.find(ToUpdate);
1405 if (OI == OverDefinedCache.end())
1406 continue;
1407 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1408 if (!ValueSet.count(V))
1409 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001410
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001411 ValueSet.erase(V);
1412 if (ValueSet.empty())
1413 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001414
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001415 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001416 // blocks successors too.
1417 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001418 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001419
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001420 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001421
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001422 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1423 }
1424}
1425
Chris Lattneraf025d32009-11-15 19:59:49 +00001426//===----------------------------------------------------------------------===//
1427// LazyValueInfo Impl
1428//===----------------------------------------------------------------------===//
1429
Sanjay Patel2a385e22015-01-09 16:47:20 +00001430/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001431static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001432 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001433 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001434 if (!PImpl) {
1435 assert(DL && "getCache() called with a null DataLayout");
1436 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1437 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001438 return *static_cast<LazyValueInfoCache*>(PImpl);
1439}
1440
Owen Anderson208636f2010-08-18 18:39:01 +00001441bool LazyValueInfo::runOnFunction(Function &F) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001442 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001443 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001444
1445 DominatorTreeWrapperPass *DTWP =
1446 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1447 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001448
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001449 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001450
Hal Finkel7e184492014-09-07 20:29:59 +00001451 if (PImpl)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001452 getCache(PImpl, AC, &DL, 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
Chad Rosier43a33062011-12-02 01:26:24 +00001458void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1459 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
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
Hal Finkel7e184492014-09-07 20:29:59 +00001472Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1473 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001474 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001475 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001476 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001477
Chris Lattner19019ea2009-11-11 22:48:44 +00001478 if (Result.isConstant())
1479 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001480 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001481 ConstantRange CR = Result.getConstantRange();
1482 if (const APInt *SingleVal = CR.getSingleElement())
1483 return ConstantInt::get(V->getContext(), *SingleVal);
1484 }
Craig Topper9f008862014-04-15 04:59:12 +00001485 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001486}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001487
John Regehre1c481d2016-05-02 19:58:00 +00001488ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
1489 Instruction *CxtI) {
1490 assert(V->getType()->isIntegerTy());
1491 unsigned Width = V->getType()->getIntegerBitWidth();
1492 const DataLayout &DL = BB->getModule()->getDataLayout();
1493 LVILatticeVal Result =
1494 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1495 assert(!Result.isConstant());
1496 if (Result.isUndefined())
1497 return ConstantRange(Width, /*isFullSet=*/false);
1498 if (Result.isConstantRange())
1499 return Result.getConstantRange();
Davide Italianobd543d02016-05-25 22:29:34 +00001500 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001501}
1502
Sanjay Patel2a385e22015-01-09 16:47:20 +00001503/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001504/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001505Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001506 BasicBlock *ToBB,
1507 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001508 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001509 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001510 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001511
Chris Lattnerd5e25432009-11-12 01:29:10 +00001512 if (Result.isConstant())
1513 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001514 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001515 ConstantRange CR = Result.getConstantRange();
1516 if (const APInt *SingleVal = CR.getSingleElement())
1517 return ConstantInt::get(V->getContext(), *SingleVal);
1518 }
Craig Topper9f008862014-04-15 04:59:12 +00001519 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001520}
1521
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001522static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1523 LVILatticeVal &Result,
1524 const DataLayout &DL,
1525 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001526
Chris Lattner565ee2f2009-11-12 04:36:58 +00001527 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001528 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001529 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001530 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001531 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001532 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001533 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1534 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001535 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001536
Owen Anderson185fe002010-08-10 20:03:09 +00001537 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001538 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001539 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001540
Owen Anderson185fe002010-08-10 20:03:09 +00001541 ConstantRange CR = Result.getConstantRange();
1542 if (Pred == ICmpInst::ICMP_EQ) {
1543 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001544 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001545
Owen Anderson185fe002010-08-10 20:03:09 +00001546 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001547 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001548 } else if (Pred == ICmpInst::ICMP_NE) {
1549 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001550 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001551
Owen Anderson185fe002010-08-10 20:03:09 +00001552 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001553 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001554 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001555
Owen Anderson185fe002010-08-10 20:03:09 +00001556 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001557 ConstantRange TrueValues =
1558 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1559 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001560 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001561 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001562 return LazyValueInfo::False;
1563 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001564 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001565
Chris Lattneraf025d32009-11-15 19:59:49 +00001566 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001567 // If this is an equality comparison, we can try to fold it knowing that
1568 // "V != C1".
1569 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001570 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001571 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001572 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001573 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001574 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001575 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001576 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001577 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001578 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001579 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001580 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001581 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001582 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001583 }
Hal Finkel7e184492014-09-07 20:29:59 +00001584 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001585 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001586
Hal Finkel7e184492014-09-07 20:29:59 +00001587 return LazyValueInfo::Unknown;
1588}
1589
Sanjay Patel2a385e22015-01-09 16:47:20 +00001590/// Determine whether the specified value comparison with a constant is known to
1591/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001592LazyValueInfo::Tristate
1593LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1594 BasicBlock *FromBB, BasicBlock *ToBB,
1595 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001596 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001597 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001598 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001599
1600 return getPredicateResult(Pred, C, Result, DL, TLI);
1601}
1602
1603LazyValueInfo::Tristate
1604LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1605 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001606 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1607 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001608 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1609 if (Ret != Unknown)
1610 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001611
Philip Reamesaeefae02015-11-04 01:47:04 +00001612 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1613 // LVI as a whole tries to compute a lattice value which is conservatively
1614 // correct at a given location. In this case, we have a predicate which we
1615 // weren't able to prove about the merged result, and we're pushing that
1616 // predicate back along each incoming edge to see if we can prove it
1617 // separately for each input. As a motivating example, consider:
1618 // bb1:
1619 // %v1 = ... ; constantrange<1, 5>
1620 // br label %merge
1621 // bb2:
1622 // %v2 = ... ; constantrange<10, 20>
1623 // br label %merge
1624 // merge:
1625 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1626 // %pred = icmp eq i32 %phi, 8
1627 // We can't tell from the lattice value for '%phi' that '%pred' is false
1628 // along each path, but by checking the predicate over each input separately,
1629 // we can.
1630 // We limit the search to one step backwards from the current BB and value.
1631 // We could consider extending this to search further backwards through the
1632 // CFG and/or value graph, but there are non-obvious compile time vs quality
1633 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001634 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001635 BasicBlock *BB = CxtI->getParent();
1636
1637 // Function entry or an unreachable block. Bail to avoid confusing
1638 // analysis below.
1639 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1640 if (PI == PE)
1641 return Unknown;
1642
1643 // If V is a PHI node in the same block as the context, we need to ask
1644 // questions about the predicate as applied to the incoming value along
1645 // each edge. This is useful for eliminating cases where the predicate is
1646 // known along all incoming edges.
1647 if (auto *PHI = dyn_cast<PHINode>(V))
1648 if (PHI->getParent() == BB) {
1649 Tristate Baseline = Unknown;
1650 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1651 Value *Incoming = PHI->getIncomingValue(i);
1652 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1653 // Note that PredBB may be BB itself.
1654 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1655 CxtI);
1656
1657 // Keep going as long as we've seen a consistent known result for
1658 // all inputs.
1659 Baseline = (i == 0) ? Result /* First iteration */
1660 : (Baseline == Result ? Baseline : Unknown); /* All others */
1661 if (Baseline == Unknown)
1662 break;
1663 }
1664 if (Baseline != Unknown)
1665 return Baseline;
1666 }
1667
Philip Reames66ab0f02015-06-16 00:49:59 +00001668 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001669 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001670 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001671 if (!isa<Instruction>(V) ||
1672 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001673 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001674 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001675 // the value of the comparison in this block.
1676 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1677 if (Baseline != Unknown) {
1678 // Check that all remaining incoming values match the first one.
1679 while (++PI != PE) {
1680 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1681 if (Ret != Baseline) break;
1682 }
1683 // If we terminated early, then one of the values didn't match.
1684 if (PI == PE) {
1685 return Baseline;
1686 }
1687 }
1688 }
1689 }
1690 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001691}
1692
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001693void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001694 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001695 if (PImpl) {
1696 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1697 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1698 }
Owen Anderson208636f2010-08-18 18:39:01 +00001699}
1700
1701void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001702 if (PImpl) {
1703 const DataLayout &DL = BB->getModule()->getDataLayout();
1704 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1705 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001706}