blob: 31f1d44653dffeb12d4d81088167df14c0bf66eb [file] [log] [blame]
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
Chris Lattner741c94c2009-11-11 00:22:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000022#include "llvm/Analysis/ValueTracking.h"
Anna Thomase27b39a2017-03-22 19:27:12 +000023#include "llvm/IR/AssemblyAnnotationWriter.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000024#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000025#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +000031#include "llvm/IR/Intrinsics.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000032#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000033#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000034#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000035#include "llvm/Support/Debug.h"
Anna Thomase27b39a2017-03-22 19:27:12 +000036#include "llvm/Support/FormattedStream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000038#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000039#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000040using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000041using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000042
Chandler Carruthf1221bd2014-04-22 02:48:03 +000043#define DEBUG_TYPE "lazy-value-info"
44
Daniel Berlin9c92a462017-02-08 15:22:52 +000045// This is the number of worklist items we will process to try to discover an
46// answer for a given value.
47static const unsigned MaxProcessedPerValue = 500;
48
Sean Silva687019f2016-06-13 22:01:25 +000049char LazyValueInfoWrapperPass::ID = 0;
50INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000051 "Lazy Value Information Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000052INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000053INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Sean Silva687019f2016-06-13 22:01:25 +000054INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000055 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000056
57namespace llvm {
Sean Silva687019f2016-06-13 22:01:25 +000058 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000059}
60
Chandler Carruthdab4eae2016-11-23 17:53:26 +000061AnalysisKey LazyValueAnalysis::Key;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000062
63//===----------------------------------------------------------------------===//
64// LVILatticeVal
65//===----------------------------------------------------------------------===//
66
Sanjay Patel2a385e22015-01-09 16:47:20 +000067/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000068///
69/// FIXME: This is basically just for bringup, this can be made a lot more rich
70/// in the future.
71///
72namespace {
73class LVILatticeVal {
74 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000075 /// This Value has no known value yet. As a result, this implies the
76 /// producing instruction is dead. Caution: We use this as the starting
77 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000078 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000079 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000080
Philip Reames02bb6a62016-12-07 04:48:50 +000081 /// This Value has a specific constant value. (For constant integers,
82 /// constantrange is used instead. Integer typed constantexprs can appear
83 /// as constant.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000084 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000085
Philip Reames02bb6a62016-12-07 04:48:50 +000086 /// This Value is known to not have the specified value. (For constant
87 /// integers, constantrange is used instead. As above, integer typed
88 /// constantexprs can appear here.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000089 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000090
Philip Reames3bb28322016-04-25 18:48:43 +000091 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000092 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000093
Philip Reames3bb28322016-04-25 18:48:43 +000094 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000095 overdefined
96 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000097
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000098 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000099 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +0000100 LatticeValueTy Tag;
101 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +0000102 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000103
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000104public:
Craig Topper9f008862014-04-15 04:59:12 +0000105 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000106
Chris Lattner19019ea2009-11-11 22:48:44 +0000107 static LVILatticeVal get(Constant *C) {
108 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000109 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000110 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000111 return Res;
112 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000113 static LVILatticeVal getNot(Constant *C) {
114 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000115 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000116 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000117 return Res;
118 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000119 static LVILatticeVal getRange(ConstantRange CR) {
120 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000121 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000122 return Res;
123 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000124 static LVILatticeVal getOverdefined() {
125 LVILatticeVal Res;
126 Res.markOverdefined();
127 return Res;
128 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000129
Owen Anderson0f306a42010-08-05 22:59:19 +0000130 bool isUndefined() const { return Tag == undefined; }
131 bool isConstant() const { return Tag == constant; }
132 bool isNotConstant() const { return Tag == notconstant; }
133 bool isConstantRange() const { return Tag == constantrange; }
134 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000135
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000136 Constant *getConstant() const {
137 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000138 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000139 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000140
Chris Lattner565ee2f2009-11-12 04:36:58 +0000141 Constant *getNotConstant() const {
142 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000143 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000144 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000145
Craig Topper2b195fd2017-05-06 03:35:15 +0000146 const ConstantRange &getConstantRange() const {
Owen Anderson0f306a42010-08-05 22:59:19 +0000147 assert(isConstantRange() &&
148 "Cannot get the constant-range of a non-constant-range!");
149 return Range;
150 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000151
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +0000152 Optional<APInt> asConstantInteger() const {
153 if (isConstant() && isa<ConstantInt>(Val)) {
Craig Topper4e22ee62017-08-04 16:59:29 +0000154 return cast<ConstantInt>(Val)->getValue();
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +0000155 } else if (isConstantRange() && Range.isSingleElement()) {
156 return *Range.getSingleElement();
157 }
158 return None;
159 }
160
Philip Reames1baaef12016-12-06 03:01:08 +0000161private:
Philip Reames71a49672016-12-07 01:03:56 +0000162 void markOverdefined() {
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000163 if (isOverdefined())
Philip Reames71a49672016-12-07 01:03:56 +0000164 return;
Owen Andersonc3a14132010-08-05 22:10:46 +0000165 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000166 }
167
Philip Reames71a49672016-12-07 01:03:56 +0000168 void markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000169 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000170 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
171 markConstantRange(ConstantRange(CI->getValue()));
172 return;
173 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000174 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000175 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000176
177 assert((!isConstant() || getConstant() == V) &&
178 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000179 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000180 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000181 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000182 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000183
Philip Reames71a49672016-12-07 01:03:56 +0000184 void markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000185 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000186 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
187 markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
188 return;
189 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000190 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000191 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000192
193 assert((!isConstant() || getConstant() != V) &&
194 "Marking constant !constant with same value");
195 assert((!isNotConstant() || getNotConstant() == V) &&
196 "Marking !constant with different value");
197 assert(isUndefined() || isConstant());
198 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000199 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000200 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000201
Philip Reames71a49672016-12-07 01:03:56 +0000202 void markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000203 if (isConstantRange()) {
204 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000205 markOverdefined();
206 else {
Philip Reames71a49672016-12-07 01:03:56 +0000207 Range = std::move(NewR);
208 }
209 return;
Owen Anderson0f306a42010-08-05 22:59:19 +0000210 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000211
Owen Anderson0f306a42010-08-05 22:59:19 +0000212 assert(isUndefined());
213 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000214 markOverdefined();
215 else {
216 Tag = constantrange;
217 Range = std::move(NewR);
218 }
Owen Anderson0f306a42010-08-05 22:59:19 +0000219 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000220
Philip Reamesb2949622016-12-06 02:54:16 +0000221public:
222
Sanjay Patel2a385e22015-01-09 16:47:20 +0000223 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000224 /// one and returning true if anything changed.
Philip Reamesb47a7192016-12-07 00:54:21 +0000225 void mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
226 if (RHS.isUndefined() || isOverdefined())
227 return;
228 if (RHS.isOverdefined()) {
229 markOverdefined();
230 return;
231 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000232
Nick Lewycky11678bd2010-12-15 18:57:18 +0000233 if (isUndefined()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000234 *this = RHS;
235 return;
Chris Lattner22db4b52009-11-12 04:57:13 +0000236 }
237
Nick Lewycky11678bd2010-12-15 18:57:18 +0000238 if (isConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000239 if (RHS.isConstant() && Val == RHS.Val)
240 return;
241 markOverdefined();
242 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000243 }
244
245 if (isNotConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000246 if (RHS.isNotConstant() && Val == RHS.Val)
247 return;
248 markOverdefined();
249 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000250 }
251
252 assert(isConstantRange() && "New LVILattice type?");
Philip Reames02bb6a62016-12-07 04:48:50 +0000253 if (!RHS.isConstantRange()) {
254 // We can get here if we've encountered a constantexpr of integer type
255 // and merge it with a constantrange.
256 markOverdefined();
257 return;
258 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000259 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
260 if (NewR.isFullSet())
Philip Reamesb47a7192016-12-07 00:54:21 +0000261 markOverdefined();
262 else
Craig Topper2b195fd2017-05-06 03:35:15 +0000263 markConstantRange(std::move(NewR));
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000264 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000265};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000266
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000267} // end anonymous namespace.
268
Chris Lattner19019ea2009-11-11 22:48:44 +0000269namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000270raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
271 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000272raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
273 if (Val.isUndefined())
274 return OS << "undefined";
275 if (Val.isOverdefined())
276 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000277
278 if (Val.isNotConstant())
279 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000280 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000281 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
282 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000283 return OS << "constant<" << *Val.getConstant() << '>';
284}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000285}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000286
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000287/// Returns true if this lattice value represents at most one possible value.
288/// This is as precise as any lattice value can get while still representing
289/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000290static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000291 if (Val.isConstantRange() &&
292 Val.getConstantRange().isSingleElement())
293 // Integer constants are single element ranges
294 return true;
295 if (Val.isConstant())
296 // Non integer constants
297 return true;
298 return false;
299}
300
301/// Combine two sets of facts about the same value into a single set of
302/// facts. Note that this method is not suitable for merging facts along
303/// different paths in a CFG; that's what the mergeIn function is for. This
304/// is for merging facts gathered about the same value at the same location
305/// through two independent means.
306/// Notes:
307/// * This method does not promise to return the most precise possible lattice
308/// value implied by A and B. It is allowed to return any lattice element
309/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000310/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000311/// * Due to unreachable code, the intersection of two lattice values could be
312/// contradictory. If this happens, we return some valid lattice value so as
313/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
314/// we do not make this guarantee. TODO: This would be a useful enhancement.
Craig Topperdb528092017-06-08 17:08:58 +0000315static LVILatticeVal intersect(const LVILatticeVal &A, const LVILatticeVal &B) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000316 // Undefined is the strongest state. It means the value is known to be along
317 // an unreachable path.
318 if (A.isUndefined())
319 return A;
320 if (B.isUndefined())
321 return B;
322
323 // If we gave up for one, but got a useable fact from the other, use it.
324 if (A.isOverdefined())
325 return B;
326 if (B.isOverdefined())
327 return A;
328
329 // Can't get any more precise than constants.
330 if (hasSingleValue(A))
331 return A;
332 if (hasSingleValue(B))
333 return B;
334
335 // Could be either constant range or not constant here.
336 if (!A.isConstantRange() || !B.isConstantRange()) {
337 // TODO: Arbitrary choice, could be improved
338 return A;
339 }
340
341 // Intersect two constant ranges
342 ConstantRange Range =
343 A.getConstantRange().intersectWith(B.getConstantRange());
344 // Note: An empty range is implicitly converted to overdefined internally.
345 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000346 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000347 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000348}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000349
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000350//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000351// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000352//===----------------------------------------------------------------------===//
353
Chris Lattneraf025d32009-11-15 19:59:49 +0000354namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000355 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000356 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000357 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000358 // Needs to access getValPtr(), which is protected.
359 friend struct DenseMapInfo<LVIValueHandle>;
360
Owen Anderson118ac802011-01-05 21:15:29 +0000361 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000362
Owen Anderson118ac802011-01-05 21:15:29 +0000363 LVIValueHandle(Value *V, LazyValueInfoCache *P)
364 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000365
366 void deleted() override;
367 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000368 deleted();
369 }
370 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000371} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000372
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000373namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000374 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000375 /// maintains information about queries across the clients' queries.
376 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000377 /// This is all of the cached block information for exactly one Value*.
378 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000379 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000380 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
381 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000382 struct ValueCacheEntryTy {
383 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
384 LVIValueHandle Handle;
Chandler Carruth6acdca72017-01-24 12:55:57 +0000385 SmallDenseMap<PoisoningVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
Justin Lebar58b377e2016-07-27 22:33:36 +0000386 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000387
Sanjay Patel2a385e22015-01-09 16:47:20 +0000388 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000389 /// over-defined at the end of that block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000390 typedef DenseMap<PoisoningVH<BasicBlock>, SmallPtrSet<Value *, 4>>
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000391 OverDefinedCacheTy;
Sanjay Patel2a385e22015-01-09 16:47:20 +0000392 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000393 /// don't spend time removing unused blocks from our caches.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000394 DenseSet<PoisoningVH<BasicBlock> > SeenBlocks;
Benjamin Kramer36647082011-12-03 15:16:45 +0000395
Anna Thomase27b39a2017-03-22 19:27:12 +0000396 /// This is all of the cached information for all values,
397 /// mapped from Value* to key information.
398 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
399 OverDefinedCacheTy OverDefinedCache;
400
401
Philip Reames9db79482016-09-12 22:38:44 +0000402 public:
Hans Wennborg45172ac2014-11-25 17:23:05 +0000403 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
404 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000405
406 // Insert over-defined values into their own cache to reduce memory
407 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000408 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000409 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000410 else {
411 auto It = ValueCache.find_as(Val);
412 if (It == ValueCache.end()) {
413 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
414 It = ValueCache.find_as(Val);
415 assert(It != ValueCache.end() && "Val was just added to the map!");
416 }
417 It->second->BlockVals[BB] = Result;
418 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000419 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000420
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000421 bool isOverdefined(Value *V, BasicBlock *BB) const {
422 auto ODI = OverDefinedCache.find(BB);
423
424 if (ODI == OverDefinedCache.end())
425 return false;
426
427 return ODI->second.count(V);
428 }
429
Philip Reames9db79482016-09-12 22:38:44 +0000430 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000431 if (isOverdefined(V, BB))
432 return true;
433
Justin Lebar58b377e2016-07-27 22:33:36 +0000434 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000435 if (I == ValueCache.end())
436 return false;
437
Justin Lebar58b377e2016-07-27 22:33:36 +0000438 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000439 }
440
Philip Reames9db79482016-09-12 22:38:44 +0000441 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000442 if (isOverdefined(V, BB))
443 return LVILatticeVal::getOverdefined();
444
Justin Lebar58b377e2016-07-27 22:33:36 +0000445 auto I = ValueCache.find_as(V);
446 if (I == ValueCache.end())
447 return LVILatticeVal();
448 auto BBI = I->second->BlockVals.find(BB);
449 if (BBI == I->second->BlockVals.end())
450 return LVILatticeVal();
451 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000452 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000453
Philip Reames92e5e1b2016-09-12 21:46:58 +0000454 /// clear - Empty the cache.
455 void clear() {
456 SeenBlocks.clear();
457 ValueCache.clear();
458 OverDefinedCache.clear();
459 }
460
Philip Reamesb627aec2016-09-12 22:03:36 +0000461 /// Inform the cache that a given value has been deleted.
462 void eraseValue(Value *V);
463
464 /// This is part of the update interface to inform the cache
465 /// that a block has been deleted.
466 void eraseBlock(BasicBlock *BB);
467
Philip Reames9db79482016-09-12 22:38:44 +0000468 /// Updates the cache to remove any influence an overdefined value in
469 /// OldSucc might have (unless also overdefined in NewSucc). This just
470 /// flushes elements from the cache and does not add any.
471 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
472
Philip Reames92e5e1b2016-09-12 21:46:58 +0000473 friend struct LVIValueHandle;
474 };
Philip Reamesb627aec2016-09-12 22:03:36 +0000475}
Philip Reames92e5e1b2016-09-12 21:46:58 +0000476
Philip Reamesb627aec2016-09-12 22:03:36 +0000477void LazyValueInfoCache::eraseValue(Value *V) {
Chandler Carruth41421df2017-01-26 08:31:54 +0000478 for (auto I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E;) {
479 // Copy and increment the iterator immediately so we can erase behind
480 // ourselves.
481 auto Iter = I++;
482 SmallPtrSetImpl<Value *> &ValueSet = Iter->second;
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000483 ValueSet.erase(V);
Philip Reamesb627aec2016-09-12 22:03:36 +0000484 if (ValueSet.empty())
Chandler Carruth41421df2017-01-26 08:31:54 +0000485 OverDefinedCache.erase(Iter);
Philip Reamesb627aec2016-09-12 22:03:36 +0000486 }
Philip Reamesb627aec2016-09-12 22:03:36 +0000487
488 ValueCache.erase(V);
489}
490
491void LVIValueHandle::deleted() {
492 // This erasure deallocates *this, so it MUST happen after we're done
493 // using any and all members of *this.
494 Parent->eraseValue(*this);
495}
496
497void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
498 // Shortcut if we have never seen this block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000499 DenseSet<PoisoningVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
Philip Reamesb627aec2016-09-12 22:03:36 +0000500 if (I == SeenBlocks.end())
501 return;
502 SeenBlocks.erase(I);
503
504 auto ODI = OverDefinedCache.find(BB);
505 if (ODI != OverDefinedCache.end())
506 OverDefinedCache.erase(ODI);
507
508 for (auto &I : ValueCache)
509 I.second->BlockVals.erase(BB);
510}
511
Philip Reames9db79482016-09-12 22:38:44 +0000512void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
513 BasicBlock *NewSucc) {
514 // When an edge in the graph has been threaded, values that we could not
515 // determine a value for before (i.e. were marked overdefined) may be
516 // possible to solve now. We do NOT try to proactively update these values.
517 // Instead, we clear their entries from the cache, and allow lazy updating to
518 // recompute them when needed.
519
520 // The updating process is fairly simple: we need to drop cached info
521 // for all values that were marked overdefined in OldSucc, and for those same
522 // values in any successor of OldSucc (except NewSucc) in which they were
523 // also marked overdefined.
524 std::vector<BasicBlock*> worklist;
525 worklist.push_back(OldSucc);
526
527 auto I = OverDefinedCache.find(OldSucc);
528 if (I == OverDefinedCache.end())
529 return; // Nothing to process here.
530 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
531
532 // Use a worklist to perform a depth-first search of OldSucc's successors.
533 // NOTE: We do not need a visited list since any blocks we have already
534 // visited will have had their overdefined markers cleared already, and we
535 // thus won't loop to their successors.
536 while (!worklist.empty()) {
537 BasicBlock *ToUpdate = worklist.back();
538 worklist.pop_back();
539
540 // Skip blocks only accessible through NewSucc.
541 if (ToUpdate == NewSucc) continue;
542
Philip Reames1e48efc2016-12-30 17:56:47 +0000543 // If a value was marked overdefined in OldSucc, and is here too...
544 auto OI = OverDefinedCache.find(ToUpdate);
545 if (OI == OverDefinedCache.end())
546 continue;
547 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
548
Philip Reames9db79482016-09-12 22:38:44 +0000549 bool changed = false;
550 for (Value *V : ValsToClear) {
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000551 if (!ValueSet.erase(V))
Philip Reames9db79482016-09-12 22:38:44 +0000552 continue;
553
Philip Reames9db79482016-09-12 22:38:44 +0000554 // If we removed anything, then we potentially need to update
555 // blocks successors too.
556 changed = true;
Philip Reames1e48efc2016-12-30 17:56:47 +0000557
558 if (ValueSet.empty()) {
559 OverDefinedCache.erase(OI);
560 break;
561 }
Philip Reames9db79482016-09-12 22:38:44 +0000562 }
563
564 if (!changed) continue;
565
566 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
567 }
568}
569
Anna Thomas4acfc7e2017-06-06 19:25:31 +0000570
571namespace {
572/// An assembly annotator class to print LazyValueCache information in
573/// comments.
574class LazyValueInfoImpl;
575class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
576 LazyValueInfoImpl *LVIImpl;
577 // While analyzing which blocks we can solve values for, we need the dominator
578 // information. Since this is an optional parameter in LVI, we require this
579 // DomTreeAnalysis pass in the printer pass, and pass the dominator
580 // tree to the LazyValueInfoAnnotatedWriter.
581 DominatorTree &DT;
582
583public:
584 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
585 : LVIImpl(L), DT(DTree) {}
586
587 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
588 formatted_raw_ostream &OS);
589
590 virtual void emitInstructionAnnot(const Instruction *I,
591 formatted_raw_ostream &OS);
592};
593}
Philip Reamesb627aec2016-09-12 22:03:36 +0000594namespace {
Philip Reames92e5e1b2016-09-12 21:46:58 +0000595 // The actual implementation of the lazy analysis and update. Note that the
596 // inheritance from LazyValueInfoCache is intended to be temporary while
597 // splitting the code and then transitioning to a has-a relationship.
Philip Reames9db79482016-09-12 22:38:44 +0000598 class LazyValueInfoImpl {
599
600 /// Cached results from previous queries
601 LazyValueInfoCache TheCache;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000602
603 /// This stack holds the state of the value solver during a query.
604 /// It basically emulates the callstack of the naive
605 /// recursive value lookup process.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000606 SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000607
608 /// Keeps track of which block-value pairs are in BlockValueStack.
609 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
610
611 /// Push BV onto BlockValueStack unless it's already in there.
612 /// Returns true on success.
613 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
614 if (!BlockValueSet.insert(BV).second)
615 return false; // It's already in the stack.
616
617 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
618 << "\n");
Daniel Berlin9c92a462017-02-08 15:22:52 +0000619 BlockValueStack.push_back(BV);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000620 return true;
621 }
622
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000623 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
Philip Reames92e5e1b2016-09-12 21:46:58 +0000624 const DataLayout &DL; ///< A mandatory DataLayout
625 DominatorTree *DT; ///< An optional DT pointer.
626
627 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
628 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
629 LVILatticeVal &Result, Instruction *CxtI = nullptr);
630 bool hasBlockValue(Value *Val, BasicBlock *BB);
631
632 // These methods process one work item and may add more. A false value
633 // returned means that the work item was not completely processed and must
634 // be revisited after going through the new items.
635 bool solveBlockValue(Value *Val, BasicBlock *BB);
Philip Reames05c435e2016-12-06 03:22:03 +0000636 bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000637 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
638 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
639 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
640 BasicBlock *BB);
Craig Topper3778c892017-06-02 16:33:13 +0000641 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, BinaryOperator *BBI,
Philip Reames92e5e1b2016-09-12 21:46:58 +0000642 BasicBlock *BB);
Craig Topper0e5f1092017-06-03 07:47:08 +0000643 bool solveBlockValueCast(LVILatticeVal &BBLV, CastInst *CI,
Philip Reames92e5e1b2016-09-12 21:46:58 +0000644 BasicBlock *BB);
645 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
646 LVILatticeVal &BBLV,
Craig Topper9277a862017-06-02 17:28:12 +0000647 Instruction *BBI);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000648
649 void solve();
650
651 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000652 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000653 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000654 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
655 Instruction *CxtI = nullptr);
656
Sanjay Patel2a385e22015-01-09 16:47:20 +0000657 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000658 /// value for the specified Value* at the specified instruction (generally
659 /// from an assume intrinsic).
660 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000661
Sanjay Patel2a385e22015-01-09 16:47:20 +0000662 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000663 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000664 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
665 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000666
Philip Reames9db79482016-09-12 22:38:44 +0000667 /// Complete flush all previously computed values
668 void clear() {
669 TheCache.clear();
670 }
671
Anna Thomas4acfc7e2017-06-06 19:25:31 +0000672 /// Printing the LazyValueInfo Analysis.
673 void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
674 LazyValueInfoAnnotatedWriter Writer(this, DTree);
675 F.print(OS, &Writer);
Anna Thomase27b39a2017-03-22 19:27:12 +0000676 }
677
Philip Reames9db79482016-09-12 22:38:44 +0000678 /// This is part of the update interface to inform the cache
679 /// that a block has been deleted.
680 void eraseBlock(BasicBlock *BB) {
681 TheCache.eraseBlock(BB);
682 }
683
Sanjay Patel2a385e22015-01-09 16:47:20 +0000684 /// This is the update interface to inform the cache that an edge from
685 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000686 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000687
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000688 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
689 DominatorTree *DT = nullptr)
690 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000691 };
692} // end anonymous namespace
693
Anna Thomas4acfc7e2017-06-06 19:25:31 +0000694
Philip Reames92e5e1b2016-09-12 21:46:58 +0000695void LazyValueInfoImpl::solve() {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000696 SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
697 BlockValueStack.begin(), BlockValueStack.end());
698
699 unsigned processedCount = 0;
Owen Anderson6f060af2011-01-05 23:26:22 +0000700 while (!BlockValueStack.empty()) {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000701 processedCount++;
702 // Abort if we have to process too many values to get a result for this one.
703 // Because of the design of the overdefined cache currently being per-block
704 // to avoid naming-related issues (IE it wants to try to give different
705 // results for the same name in different blocks), overdefined results don't
706 // get cached globally, which in turn means we will often try to rediscover
707 // the same overdefined result again and again. Once something like
708 // PredicateInfo is used in LVI or CVP, we should be able to make the
709 // overdefined cache global, and remove this throttle.
710 if (processedCount > MaxProcessedPerValue) {
711 DEBUG(dbgs() << "Giving up on stack because we are getting too deep\n");
712 // Fill in the original values
713 while (!StartingStack.empty()) {
714 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
715 TheCache.insertResult(e.second, e.first,
716 LVILatticeVal::getOverdefined());
717 StartingStack.pop_back();
718 }
719 BlockValueSet.clear();
720 BlockValueStack.clear();
721 return;
722 }
Vitaly Buka9987d982017-02-09 09:28:05 +0000723 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000724 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
725
Nuno Lopese6e04902012-06-28 01:16:18 +0000726 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000727 // The work item was completely processed.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000728 assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
Philip Reames9db79482016-09-12 22:38:44 +0000729 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000730 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000731
Philip Reames44456b82016-02-02 03:15:40 +0000732 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000733 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000734
Daniel Berlin9c92a462017-02-08 15:22:52 +0000735 BlockValueStack.pop_back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000736 BlockValueSet.erase(e);
737 } else {
738 // More work needs to be done before revisiting.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000739 assert(BlockValueStack.back() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000740 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000741 }
742}
743
Philip Reames92e5e1b2016-09-12 21:46:58 +0000744bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000745 // If already a constant, there is nothing to compute.
746 if (isa<Constant>(Val))
747 return true;
748
Philip Reames9db79482016-09-12 22:38:44 +0000749 return TheCache.hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000750}
751
Philip Reames92e5e1b2016-09-12 21:46:58 +0000752LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000753 // If already a constant, there is nothing to compute.
754 if (Constant *VC = dyn_cast<Constant>(Val))
755 return LVILatticeVal::get(VC);
756
Philip Reames9db79482016-09-12 22:38:44 +0000757 return TheCache.getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000758}
759
Philip Reameseb3e9da2015-10-29 03:57:17 +0000760static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
761 switch (BBI->getOpcode()) {
762 default: break;
763 case Instruction::Load:
764 case Instruction::Call:
765 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000766 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000767 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000768 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000769 }
770 break;
771 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000772 // Nothing known - will be intersected with other facts
773 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000774}
775
Philip Reames92e5e1b2016-09-12 21:46:58 +0000776bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000777 if (isa<Constant>(Val))
778 return true;
779
Philip Reames9db79482016-09-12 22:38:44 +0000780 if (TheCache.hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000781 // If we have a cached value, use that.
782 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000783 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000784
Hans Wennborg45172ac2014-11-25 17:23:05 +0000785 // Since we're reusing a cached value, we don't need to update the
786 // OverDefinedCache. The cache will have been properly updated whenever the
787 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000788 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000789 }
790
Hans Wennborg45172ac2014-11-25 17:23:05 +0000791 // Hold off inserting this value into the Cache in case we have to return
792 // false and come back later.
793 LVILatticeVal Res;
Philip Reames05c435e2016-12-06 03:22:03 +0000794 if (!solveBlockValueImpl(Res, Val, BB))
795 // Work pushed, will revisit
796 return false;
797
798 TheCache.insertResult(Val, BB, Res);
799 return true;
800}
801
802bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
803 Value *Val, BasicBlock *BB) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000804
Chris Lattneraf025d32009-11-15 19:59:49 +0000805 Instruction *BBI = dyn_cast<Instruction>(Val);
Philip Reames05c435e2016-12-06 03:22:03 +0000806 if (!BBI || BBI->getParent() != BB)
807 return solveBlockValueNonLocal(Res, Val, BB);
Chris Lattner2c708562009-11-15 20:00:52 +0000808
Philip Reames05c435e2016-12-06 03:22:03 +0000809 if (PHINode *PN = dyn_cast<PHINode>(BBI))
810 return solveBlockValuePHINode(Res, PN, BB);
Owen Anderson80d19f02010-08-18 21:11:37 +0000811
Philip Reames05c435e2016-12-06 03:22:03 +0000812 if (auto *SI = dyn_cast<SelectInst>(BBI))
813 return solveBlockValueSelect(Res, SI, BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000814
Philip Reames2ab964e2016-04-27 01:02:25 +0000815 // If this value is a nonnull pointer, record it's range and bailout. Note
816 // that for all other pointer typed values, we terminate the search at the
817 // definition. We could easily extend this to look through geps, bitcasts,
818 // and the like to prove non-nullness, but it's not clear that's worth it
Craig Topper7ad13f22017-06-09 21:21:17 +0000819 // compile time wise. The context-insensitive value walk done inside
Nuno Lopes404f1062017-09-09 18:23:11 +0000820 // isKnownNonZero gets most of the profitable cases at much less expense.
Philip Reames2ab964e2016-04-27 01:02:25 +0000821 // This does mean that we have a sensativity to where the defining
822 // instruction is placed, even if it could legally be hoisted much higher.
823 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000824 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
Nuno Lopes404f1062017-09-09 18:23:11 +0000825 if (PT && isKnownNonZero(BBI, DL)) {
Igor Laevsky0fa48192015-09-18 13:01:48 +0000826 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000827 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000828 }
Davide Italianobd543d02016-05-25 22:29:34 +0000829 if (BBI->getType()->isIntegerTy()) {
Craig Topper0e5f1092017-06-03 07:47:08 +0000830 if (auto *CI = dyn_cast<CastInst>(BBI))
831 return solveBlockValueCast(Res, CI, BB);
832
Philip Reames2ab964e2016-04-27 01:02:25 +0000833 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
Philip Reames05c435e2016-12-06 03:22:03 +0000834 if (BO && isa<ConstantInt>(BO->getOperand(1)))
Craig Topper3778c892017-06-02 16:33:13 +0000835 return solveBlockValueBinaryOp(Res, BO, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000836 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000837
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000838 DEBUG(dbgs() << " compute BB '" << BB->getName()
839 << "' - unknown inst def found.\n");
840 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000841 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000842}
843
844static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
845 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
846 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000847 GetUnderlyingObject(L->getPointerOperand(),
848 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000849 }
850 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
851 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000852 GetUnderlyingObject(S->getPointerOperand(),
853 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000854 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000855 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
856 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000857
858 // FIXME: check whether it has a valuerange that excludes zero?
859 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
860 if (!Len || Len->isZero()) return false;
861
Eli Friedman7a5fc692011-05-31 20:40:16 +0000862 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000863 if (GetUnderlyingObject(MI->getRawDest(),
864 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000865 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000866 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000867 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000868 if (GetUnderlyingObject(MTI->getRawSource(),
869 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000870 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000871 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000872 return false;
873}
874
Philip Reames3f83dbe2016-04-27 00:30:55 +0000875/// Return true if the allocation associated with Val is ever dereferenced
876/// within the given basic block. This establishes the fact Val is not null,
877/// but does not imply that the memory at Val is dereferenceable. (Val may
878/// point off the end of the dereferenceable part of the object.)
879static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
880 assert(Val->getType()->isPointerTy());
881
882 const DataLayout &DL = BB->getModule()->getDataLayout();
883 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
884 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
885 // inside InstructionDereferencesPointer either.
886 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
887 for (Instruction &I : *BB)
888 if (InstructionDereferencesPointer(&I, UnderlyingVal))
889 return true;
890 return false;
891}
892
Philip Reames92e5e1b2016-09-12 21:46:58 +0000893bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000894 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000895 LVILatticeVal Result; // Start Undefined.
896
Nick Lewycky55a700b2010-12-18 01:00:40 +0000897 // If this is the entry block, we must be asking about an argument. The
898 // value is overdefined.
899 if (BB == &BB->getParent()->getEntryBlock()) {
900 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Craig Topper96d6ee852017-04-28 16:57:59 +0000901 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000902 // this particular block.
903 if (Val->getType()->isPointerTy() &&
Nuno Lopes404f1062017-09-09 18:23:11 +0000904 (isKnownNonZero(Val, DL) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000905 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000906 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
907 } else {
Philip Reames1baaef12016-12-06 03:01:08 +0000908 Result = LVILatticeVal::getOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000909 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000910 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000911 return true;
912 }
913
914 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000915 // result. If we encounter an unexplored predecessor, we eagerly explore it
916 // in a depth first manner. In practice, this has the effect of discovering
917 // paths we can't analyze eagerly without spending compile times analyzing
918 // other paths. This heuristic benefits from the fact that predecessors are
919 // frequently arranged such that dominating ones come first and we quickly
920 // find a path to function entry. TODO: We should consider explicitly
921 // canonicalizing to make this true rather than relying on this happy
922 // accident.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000923 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000924 LVILatticeVal EdgeResult;
Philip Reamesc80bd042017-02-07 00:25:24 +0000925 if (!getEdgeValue(Val, *PI, BB, EdgeResult))
926 // Explore that input, then return here
927 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000928
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000929 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000930
931 // If we hit overdefined, exit early. The BlockVals entry is already set
932 // to overdefined.
933 if (Result.isOverdefined()) {
934 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000935 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000936 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000937 // this particular block.
938 if (Val->getType()->isPointerTy() &&
939 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000940 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000941 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
942 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000943
Owen Anderson64c2c572010-12-20 18:18:16 +0000944 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000945 return true;
946 }
947 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000948
949 // Return the merged value, which is more precise than 'overdefined'.
950 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000951 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000952 return true;
953}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000954
Philip Reames92e5e1b2016-09-12 21:46:58 +0000955bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000956 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000957 LVILatticeVal Result; // Start Undefined.
958
959 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000960 // result. See the comment about the chosen traversal order in
961 // solveBlockValueNonLocal; the same reasoning applies here.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000962 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
963 BasicBlock *PhiBB = PN->getIncomingBlock(i);
964 Value *PhiVal = PN->getIncomingValue(i);
965 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000966 // Note that we can provide PN as the context value to getEdgeValue, even
967 // though the results will be cached, because PN is the value being used as
968 // the cache key in the caller.
Philip Reamesc80bd042017-02-07 00:25:24 +0000969 if (!getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN))
970 // Explore that input, then return here
971 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000972
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000973 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000974
975 // If we hit overdefined, exit early. The BlockVals entry is already set
976 // to overdefined.
977 if (Result.isOverdefined()) {
978 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000979 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000980
Owen Anderson64c2c572010-12-20 18:18:16 +0000981 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000982 return true;
983 }
984 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000985
986 // Return the merged value, which is more precise than 'overdefined'.
987 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000988 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000989 return true;
990}
991
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000992static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
993 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +0000994
Philip Reamesd1f829d2016-02-02 21:57:37 +0000995// If we can determine a constraint on the value given conditions assumed by
996// the program, intersect those constraints with BBLV
Philip Reames92e5e1b2016-09-12 21:46:58 +0000997void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000998 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000999 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
1000 if (!BBI)
1001 return;
1002
Hal Finkel8a9a7832017-01-11 13:24:24 +00001003 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001004 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +00001005 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001006 auto *I = cast<CallInst>(AssumeVH);
1007 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +00001008 continue;
1009
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001010 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +00001011 }
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001012
1013 // If guards are not used in the module, don't spend time looking for them
1014 auto *GuardDecl = BBI->getModule()->getFunction(
1015 Intrinsic::getName(Intrinsic::experimental_guard));
1016 if (!GuardDecl || GuardDecl->use_empty())
1017 return;
1018
Artur Pilipenko47dc0982016-10-21 15:02:21 +00001019 for (Instruction &I : make_range(BBI->getIterator().getReverse(),
1020 BBI->getParent()->rend())) {
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001021 Value *Cond = nullptr;
Artur Pilipenko47dc0982016-10-21 15:02:21 +00001022 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
1023 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001024 }
Hal Finkel7e184492014-09-07 20:29:59 +00001025}
1026
Philip Reames92e5e1b2016-09-12 21:46:58 +00001027bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001028 SelectInst *SI, BasicBlock *BB) {
1029
1030 // Recurse on our inputs if needed
1031 if (!hasBlockValue(SI->getTrueValue(), BB)) {
1032 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
1033 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001034 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001035 return true;
1036 }
1037 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
1038 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1039 // extra slots in the table if we can.
1040 if (TrueVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001041 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001042 return true;
1043 }
1044
1045 if (!hasBlockValue(SI->getFalseValue(), BB)) {
1046 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
1047 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001048 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001049 return true;
1050 }
1051 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
1052 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1053 // extra slots in the table if we can.
1054 if (FalseVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001055 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001056 return true;
1057 }
1058
Philip Reamesadf0e352016-02-26 22:53:59 +00001059 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
Craig Topper2b195fd2017-05-06 03:35:15 +00001060 const ConstantRange &TrueCR = TrueVal.getConstantRange();
1061 const ConstantRange &FalseCR = FalseVal.getConstantRange();
Philip Reamesadf0e352016-02-26 22:53:59 +00001062 Value *LHS = nullptr;
1063 Value *RHS = nullptr;
1064 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
1065 // Is this a min specifically of our two inputs? (Avoid the risk of
1066 // ValueTracking getting smarter looking back past our immediate inputs.)
1067 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
1068 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
Philip Reamesb2949622016-12-06 02:54:16 +00001069 ConstantRange ResultCR = [&]() {
1070 switch (SPR.Flavor) {
1071 default:
1072 llvm_unreachable("unexpected minmax type!");
1073 case SPF_SMIN: /// Signed minimum
1074 return TrueCR.smin(FalseCR);
1075 case SPF_UMIN: /// Unsigned minimum
1076 return TrueCR.umin(FalseCR);
1077 case SPF_SMAX: /// Signed maximum
1078 return TrueCR.smax(FalseCR);
1079 case SPF_UMAX: /// Unsigned maximum
1080 return TrueCR.umax(FalseCR);
1081 };
1082 }();
1083 BBLV = LVILatticeVal::getRange(ResultCR);
1084 return true;
Philip Reamesadf0e352016-02-26 22:53:59 +00001085 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001086
Philip Reamesadf0e352016-02-26 22:53:59 +00001087 // TODO: ABS, NABS from the SelectPatternResult
1088 }
1089
Philip Reames854a84c2016-02-12 00:09:18 +00001090 // Can we constrain the facts about the true and false values by using the
1091 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
1092 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001093 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001094 TrueVal = intersect(TrueVal,
1095 getValueFromCondition(SI->getTrueValue(), Cond, true));
1096 FalseVal = intersect(FalseVal,
1097 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +00001098
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001099 // Handle clamp idioms such as:
1100 // %24 = constantrange<0, 17>
1101 // %39 = icmp eq i32 %24, 0
1102 // %40 = add i32 %24, -1
1103 // %siv.next = select i1 %39, i32 16, i32 %40
1104 // %siv.next = constantrange<0, 17> not <-1, 17>
1105 // In general, this can handle any clamp idiom which tests the edge
1106 // condition via an equality or inequality.
1107 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +00001108 ICmpInst::Predicate Pred = ICI->getPredicate();
1109 Value *A = ICI->getOperand(0);
1110 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1111 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1112 assert(A->getType() == B->getType());
1113 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1114 };
1115 // See if either input is A + C2, subject to the constraint from the
1116 // condition that A != C when that input is used. We can assume that
1117 // that input doesn't include C + C2.
1118 ConstantInt *CIAdded;
1119 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +00001120 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +00001121 case ICmpInst::ICMP_EQ:
1122 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1123 m_ConstantInt(CIAdded)))) {
1124 auto ResNot = addConstants(CIBase, CIAdded);
1125 FalseVal = intersect(FalseVal,
1126 LVILatticeVal::getNot(ResNot));
1127 }
1128 break;
1129 case ICmpInst::ICMP_NE:
1130 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1131 m_ConstantInt(CIAdded)))) {
1132 auto ResNot = addConstants(CIBase, CIAdded);
1133 TrueVal = intersect(TrueVal,
1134 LVILatticeVal::getNot(ResNot));
1135 }
1136 break;
1137 };
1138 }
1139 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001140
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001141 LVILatticeVal Result; // Start Undefined.
1142 Result.mergeIn(TrueVal, DL);
1143 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001144 BBLV = Result;
1145 return true;
1146}
1147
Philip Reames92e5e1b2016-09-12 21:46:58 +00001148bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
Craig Topper0e5f1092017-06-03 07:47:08 +00001149 CastInst *CI,
1150 BasicBlock *BB) {
1151 if (!CI->getOperand(0)->getType()->isSized()) {
Philip Reamese5030e82016-04-26 22:52:30 +00001152 // Without knowing how wide the input is, we can't analyze it in any useful
1153 // way.
Philip Reames1baaef12016-12-06 03:01:08 +00001154 BBLV = LVILatticeVal::getOverdefined();
Philip Reamese5030e82016-04-26 22:52:30 +00001155 return true;
1156 }
Philip Reamesf105db42016-04-26 23:27:33 +00001157
1158 // Filter out casts we don't know how to reason about before attempting to
1159 // recurse on our operand. This can cut a long search short if we know we're
1160 // not going to be able to get any useful information anways.
Craig Topper0e5f1092017-06-03 07:47:08 +00001161 switch (CI->getOpcode()) {
Philip Reamesf105db42016-04-26 23:27:33 +00001162 case Instruction::Trunc:
1163 case Instruction::SExt:
1164 case Instruction::ZExt:
1165 case Instruction::BitCast:
1166 break;
1167 default:
1168 // Unhandled instructions are overdefined.
1169 DEBUG(dbgs() << " compute BB '" << BB->getName()
1170 << "' - overdefined (unknown cast).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001171 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001172 return true;
1173 }
1174
Philip Reames38c87c22016-04-26 21:48:16 +00001175 // Figure out the range of the LHS. If that fails, we still apply the
1176 // transfer rule on the full set since we may be able to locally infer
1177 // interesting facts.
Craig Topper0e5f1092017-06-03 07:47:08 +00001178 if (!hasBlockValue(CI->getOperand(0), BB))
1179 if (pushBlockValue(std::make_pair(BB, CI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001180 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001181 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001182
1183 const unsigned OperandBitWidth =
Craig Topper0e5f1092017-06-03 07:47:08 +00001184 DL.getTypeSizeInBits(CI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001185 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
Craig Topper0e5f1092017-06-03 07:47:08 +00001186 if (hasBlockValue(CI->getOperand(0), BB)) {
1187 LVILatticeVal LHSVal = getBlockValue(CI->getOperand(0), BB);
1188 intersectAssumeOrGuardBlockValueConstantRange(CI->getOperand(0), LHSVal,
1189 CI);
Philip Reames38c87c22016-04-26 21:48:16 +00001190 if (LHSVal.isConstantRange())
1191 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001192 }
1193
Craig Toppera803d5b2017-06-03 07:47:14 +00001194 const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001195
1196 // NOTE: We're currently limited by the set of operations that ConstantRange
1197 // can evaluate symbolically. Enhancing that set will allows us to analyze
1198 // more definitions.
Craig Topper0e5f1092017-06-03 07:47:08 +00001199 BBLV = LVILatticeVal::getRange(LHSRange.castOp(CI->getOpcode(),
1200 ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001201 return true;
1202}
1203
Philip Reames92e5e1b2016-09-12 21:46:58 +00001204bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
Craig Topper3778c892017-06-02 16:33:13 +00001205 BinaryOperator *BO,
Philip Reamese5030e82016-04-26 22:52:30 +00001206 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001207
Craig Topper3778c892017-06-02 16:33:13 +00001208 assert(BO->getOperand(0)->getType()->isSized() &&
Philip Reames053c2a62016-04-26 23:10:35 +00001209 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001210
1211 // Filter out operators we don't know how to reason about before attempting to
1212 // recurse on our operand(s). This can cut a long search short if we know
Craig Topper84a9f162017-06-02 16:21:13 +00001213 // we're not going to be able to get any useful information anyways.
Craig Topper3778c892017-06-02 16:33:13 +00001214 switch (BO->getOpcode()) {
Philip Reamesf105db42016-04-26 23:27:33 +00001215 case Instruction::Add:
1216 case Instruction::Sub:
1217 case Instruction::Mul:
1218 case Instruction::UDiv:
1219 case Instruction::Shl:
1220 case Instruction::LShr:
1221 case Instruction::And:
1222 case Instruction::Or:
1223 // continue into the code below
1224 break;
1225 default:
1226 // Unhandled instructions are overdefined.
1227 DEBUG(dbgs() << " compute BB '" << BB->getName()
1228 << "' - overdefined (unknown binary operator).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001229 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001230 return true;
1231 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001232
Philip Reames053c2a62016-04-26 23:10:35 +00001233 // Figure out the range of the LHS. If that fails, use a conservative range,
1234 // but apply the transfer rule anyways. This lets us pick up facts from
1235 // expressions like "and i32 (call i32 @foo()), 32"
Craig Topper3778c892017-06-02 16:33:13 +00001236 if (!hasBlockValue(BO->getOperand(0), BB))
1237 if (pushBlockValue(std::make_pair(BB, BO->getOperand(0))))
Philip Reames053c2a62016-04-26 23:10:35 +00001238 // More work to do before applying this transfer rule.
1239 return false;
1240
1241 const unsigned OperandBitWidth =
Craig Topper3778c892017-06-02 16:33:13 +00001242 DL.getTypeSizeInBits(BO->getOperand(0)->getType());
Philip Reames053c2a62016-04-26 23:10:35 +00001243 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
Craig Topper3778c892017-06-02 16:33:13 +00001244 if (hasBlockValue(BO->getOperand(0), BB)) {
1245 LVILatticeVal LHSVal = getBlockValue(BO->getOperand(0), BB);
1246 intersectAssumeOrGuardBlockValueConstantRange(BO->getOperand(0), LHSVal,
1247 BO);
Philip Reames053c2a62016-04-26 23:10:35 +00001248 if (LHSVal.isConstantRange())
1249 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001250 }
Philip Reames66715772016-04-25 18:30:31 +00001251
Craig Topper3778c892017-06-02 16:33:13 +00001252 ConstantInt *RHS = cast<ConstantInt>(BO->getOperand(1));
Philip Reames66715772016-04-25 18:30:31 +00001253 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1254
Owen Anderson80d19f02010-08-18 21:11:37 +00001255 // NOTE: We're currently limited by the set of operations that ConstantRange
1256 // can evaluate symbolically. Enhancing that set will allows us to analyze
1257 // more definitions.
Craig Topper3778c892017-06-02 16:33:13 +00001258 Instruction::BinaryOps BinOp = BO->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001259 BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001260 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001261}
1262
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001263static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1264 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001265 Value *LHS = ICI->getOperand(0);
1266 Value *RHS = ICI->getOperand(1);
1267 CmpInst::Predicate Predicate = ICI->getPredicate();
1268
1269 if (isa<Constant>(RHS)) {
1270 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001271 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001272 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001273 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001274 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001275 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001276 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001277 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001278 }
Hal Finkel7e184492014-09-07 20:29:59 +00001279
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001280 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001281 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001282
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001283 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1284 // range of Val guaranteed by the condition. Recognize comparisons in the from
1285 // of:
1286 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001287 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001288 // The latter is the range checking idiom that InstCombine produces. Subtract
1289 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001290
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001291 // Val or (add Val, Offset) can be on either hand of the comparison
1292 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1293 std::swap(LHS, RHS);
1294 Predicate = CmpInst::getSwappedPredicate(Predicate);
1295 }
Hal Finkel7e184492014-09-07 20:29:59 +00001296
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001297 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001298 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001299 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001300
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001301 if (LHS == Val || Offset) {
1302 // Calculate the range of values that are allowed by the comparison
1303 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1304 /*isFullSet=*/true);
1305 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1306 RHSRange = ConstantRange(CI->getValue());
Artur Pilipenko6669f252016-08-12 10:14:11 +00001307 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1308 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1309 RHSRange = getConstantRangeFromMetadata(*Ranges);
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001310
1311 // If we're interested in the false dest, invert the condition
1312 CmpInst::Predicate Pred =
1313 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1314 ConstantRange TrueValues =
1315 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1316
1317 if (Offset) // Apply the offset from above.
1318 TrueValues = TrueValues.subtract(Offset->getValue());
1319
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001320 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001321 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001322
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001323 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001324}
1325
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001326static LVILatticeVal
1327getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1328 DenseMap<Value*, LVILatticeVal> &Visited);
1329
1330static LVILatticeVal
1331getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1332 DenseMap<Value*, LVILatticeVal> &Visited) {
1333 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1334 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1335
1336 // Handle conditions in the form of (cond1 && cond2), we know that on the
Craig Topperb60f8662017-06-23 01:08:16 +00001337 // true dest path both of the conditions hold. Similarly for conditions of
1338 // the form (cond1 || cond2), we know that on the false dest path neither
1339 // condition holds.
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001340 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
Craig Topperb60f8662017-06-23 01:08:16 +00001341 if (!BO || (isTrueDest && BO->getOpcode() != BinaryOperator::And) ||
1342 (!isTrueDest && BO->getOpcode() != BinaryOperator::Or))
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001343 return LVILatticeVal::getOverdefined();
1344
1345 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1346 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1347 return intersect(RHS, LHS);
1348}
1349
1350static LVILatticeVal
1351getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1352 DenseMap<Value*, LVILatticeVal> &Visited) {
1353 auto I = Visited.find(Cond);
1354 if (I != Visited.end())
1355 return I->second;
Artur Pilipenkob6230882016-08-12 15:08:15 +00001356
1357 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1358 Visited[Cond] = Result;
1359 return Result;
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001360}
1361
1362LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1363 assert(Cond && "precondition");
1364 DenseMap<Value*, LVILatticeVal> Visited;
1365 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1366}
1367
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001368// Return true if Usr has Op as an operand, otherwise false.
1369static bool usesOperand(User *Usr, Value *Op) {
1370 return find(Usr->operands(), Op) != Usr->op_end();
1371}
1372
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001373// Return true if the instruction type of Val is supported by
1374// constantFoldUser(). Currently CastInst and BinaryOperator only. Call this
1375// before calling constantFoldUser() to find out if it's even worth attempting
1376// to call it.
1377static bool isOperationFoldable(User *Usr) {
1378 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr);
1379}
1380
1381// Check if Usr can be simplified to an integer constant when the value of one
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001382// of its operands Op is an integer constant OpConstVal. If so, return it as an
1383// lattice value range with a single element or otherwise return an overdefined
1384// lattice value.
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001385static LVILatticeVal constantFoldUser(User *Usr, Value *Op,
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001386 const APInt &OpConstVal,
1387 const DataLayout &DL) {
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001388 assert(isOperationFoldable(Usr) && "Precondition");
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001389 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001390 // Check if Usr can be simplified to a constant.
1391 if (auto *CI = dyn_cast<CastInst>(Usr)) {
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001392 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1393 if (auto *C = dyn_cast_or_null<ConstantInt>(
1394 SimplifyCastInst(CI->getOpcode(), OpConst,
1395 CI->getDestTy(), DL))) {
Craig Topper4e22ee62017-08-04 16:59:29 +00001396 return LVILatticeVal::getRange(ConstantRange(C->getValue()));
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001397 }
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001398 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001399 bool Op0Match = BO->getOperand(0) == Op;
1400 bool Op1Match = BO->getOperand(1) == Op;
1401 assert((Op0Match || Op1Match) &&
1402 "Operand 0 nor Operand 1 isn't a match");
1403 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1404 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1405 if (auto *C = dyn_cast_or_null<ConstantInt>(
1406 SimplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
Craig Topper4e22ee62017-08-04 16:59:29 +00001407 return LVILatticeVal::getRange(ConstantRange(C->getValue()));
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001408 }
1409 }
1410 return LVILatticeVal::getOverdefined();
1411}
1412
Nuno Lopese6e04902012-06-28 01:16:18 +00001413/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001414/// Val is not constrained on the edge. Result is unspecified if return value
1415/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001416static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1417 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001418 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001419 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001420 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1421 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001422 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001423 if (BI->isConditional() &&
1424 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1425 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1426 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1427 "BBTo isn't a successor of BBFrom");
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001428 Value *Condition = BI->getCondition();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001429
Chris Lattner19019ea2009-11-11 22:48:44 +00001430 // If V is the condition of the branch itself, then we know exactly what
1431 // it is.
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001432 if (Condition == Val) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001433 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001434 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001435 return true;
1436 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001437
Chris Lattner19019ea2009-11-11 22:48:44 +00001438 // If the condition of the branch is an equality comparison, we may be
1439 // able to infer the value.
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001440 Result = getValueFromCondition(Val, Condition, isTrueDest);
1441 if (!Result.isOverdefined())
1442 return true;
1443
1444 if (User *Usr = dyn_cast<User>(Val)) {
1445 assert(Result.isOverdefined() && "Result isn't overdefined");
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001446 // Check with isOperationFoldable() first to avoid linearly iterating
1447 // over the operands unnecessarily which can be expensive for
1448 // instructions with many operands.
1449 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001450 const DataLayout &DL = BBTo->getModule()->getDataLayout();
1451 if (usesOperand(Usr, Condition)) {
1452 // If Val has Condition as an operand and Val can be folded into a
1453 // constant with either Condition == true or Condition == false,
1454 // propagate the constant.
1455 // eg.
1456 // ; %Val is true on the edge to %then.
1457 // %Val = and i1 %Condition, true.
1458 // br %Condition, label %then, label %else
1459 APInt ConditionVal(1, isTrueDest ? 1 : 0);
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001460 Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001461 } else {
1462 // If one of Val's operand has an inferred value, we may be able to
1463 // infer the value of Val.
1464 // eg.
1465 // ; %Val is 94 on the edge to %then.
1466 // %Val = add i8 %Op, 1
1467 // %Condition = icmp eq i8 %Op, 93
1468 // br i1 %Condition, label %then, label %else
1469 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1470 Value *Op = Usr->getOperand(i);
1471 LVILatticeVal OpLatticeVal =
1472 getValueFromCondition(Op, Condition, isTrueDest);
1473 if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001474 Result = constantFoldUser(Usr, Op, OpConst.getValue(), DL);
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001475 break;
1476 }
1477 }
1478 }
1479 }
1480 }
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001481 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001482 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001483 }
1484 }
Chris Lattner77358782009-11-15 20:02:12 +00001485
1486 // If the edge was formed by a switch on the value, then we may know exactly
1487 // what it is.
1488 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001489 Value *Condition = SI->getCondition();
1490 if (!isa<IntegerType>(Val->getType()))
Nuno Lopes8650fb82012-06-28 16:13:37 +00001491 return false;
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001492 bool ValUsesConditionAndMayBeFoldable = false;
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001493 if (Condition != Val) {
1494 // Check if Val has Condition as an operand.
1495 if (User *Usr = dyn_cast<User>(Val))
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001496 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1497 usesOperand(Usr, Condition);
1498 if (!ValUsesConditionAndMayBeFoldable)
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001499 return false;
1500 }
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001501 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001502 "Condition != Val nor Val doesn't use Condition");
Nuno Lopes8650fb82012-06-28 16:13:37 +00001503
1504 bool DefaultCase = SI->getDefaultDest() == BBTo;
1505 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1506 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1507
Chandler Carruth927d8e62017-04-12 07:27:28 +00001508 for (auto Case : SI->cases()) {
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001509 APInt CaseValue = Case.getCaseValue()->getValue();
1510 ConstantRange EdgeVal(CaseValue);
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001511 if (ValUsesConditionAndMayBeFoldable) {
1512 User *Usr = cast<User>(Val);
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001513 const DataLayout &DL = BBTo->getModule()->getDataLayout();
1514 LVILatticeVal EdgeLatticeVal =
Hiroshi Yamauchiccd412f2017-08-10 02:23:14 +00001515 constantFoldUser(Usr, Condition, CaseValue, DL);
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001516 if (EdgeLatticeVal.isOverdefined())
1517 return false;
1518 EdgeVal = EdgeLatticeVal.getConstantRange();
1519 }
Manman Renf3fedb62012-09-05 23:45:58 +00001520 if (DefaultCase) {
1521 // It is possible that the default destination is the destination of
Hiroshi Yamauchi144ee2b2017-08-03 21:11:30 +00001522 // some cases. We cannot perform difference for those cases.
1523 // We know Condition != CaseValue in BBTo. In some cases we can use
1524 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1525 // only do this when f is identity (i.e. Val == Condition), but we
1526 // should be able to do this for any injective f.
1527 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
Manman Renf3fedb62012-09-05 23:45:58 +00001528 EdgesVals = EdgesVals.difference(EdgeVal);
Chandler Carruth927d8e62017-04-12 07:27:28 +00001529 } else if (Case.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001530 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001531 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001532 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001533 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001534 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001535 return false;
1536}
1537
Sanjay Patel938e2792015-01-09 16:35:37 +00001538/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1539/// the basic block if the edge does not constrain Val.
Philip Reames92e5e1b2016-09-12 21:46:58 +00001540bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Xin Tong68ea9aa2017-02-24 20:59:26 +00001541 BasicBlock *BBTo, LVILatticeVal &Result,
1542 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001543 // If already a constant, there is nothing to compute.
1544 if (Constant *VC = dyn_cast<Constant>(Val)) {
1545 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001546 return true;
1547 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001548
Philip Reames44456b82016-02-02 03:15:40 +00001549 LVILatticeVal LocalResult;
1550 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1551 // If we couldn't constrain the value on the edge, LocalResult doesn't
1552 // provide any information.
Philip Reames1baaef12016-12-06 03:01:08 +00001553 LocalResult = LVILatticeVal::getOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001554
Philip Reames44456b82016-02-02 03:15:40 +00001555 if (hasSingleValue(LocalResult)) {
1556 // Can't get any more precise here
1557 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001558 return true;
1559 }
1560
1561 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001562 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1563 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001564 // No new information.
1565 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001566 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001567 }
1568
Philip Reames44456b82016-02-02 03:15:40 +00001569 // Try to intersect ranges of the BB and the constraint on the edge.
1570 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001571 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1572 BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001573 // We can use the context instruction (generically the ultimate instruction
1574 // the calling pass is trying to simplify) here, even though the result of
1575 // this function is generally cached when called from the solve* functions
1576 // (and that cached result might be used with queries using a different
1577 // context instruction), because when this function is called from the solve*
1578 // functions, the context instruction is not provided. When called from
Philip Reames92e5e1b2016-09-12 21:46:58 +00001579 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
Hal Finkel2400c962014-10-16 00:40:05 +00001580 // but then the result is not cached.
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001581 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001582
1583 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001584 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001585}
1586
Philip Reames92e5e1b2016-09-12 21:46:58 +00001587LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Hal Finkel7e184492014-09-07 20:29:59 +00001588 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001589 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001590 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001591
Hans Wennborg45172ac2014-11-25 17:23:05 +00001592 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001593 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001594 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001595 solve();
1596 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001597 LVILatticeVal Result = getBlockValue(V, BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001598 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001599
1600 DEBUG(dbgs() << " Result = " << Result << "\n");
1601 return Result;
1602}
1603
Philip Reames92e5e1b2016-09-12 21:46:58 +00001604LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001605 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1606 << CxtI->getName() << "'\n");
1607
Philip Reamesbb781b42016-02-10 21:46:32 +00001608 if (auto *C = dyn_cast<Constant>(V))
1609 return LVILatticeVal::get(C);
1610
Philip Reamesd1f829d2016-02-02 21:57:37 +00001611 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001612 if (auto *I = dyn_cast<Instruction>(V))
1613 Result = getFromRangeMetadata(I);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001614 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001615
David Greene37e98092009-12-23 20:43:58 +00001616 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001617 return Result;
1618}
Chris Lattner19019ea2009-11-11 22:48:44 +00001619
Philip Reames92e5e1b2016-09-12 21:46:58 +00001620LVILatticeVal LazyValueInfoImpl::
Hal Finkel7e184492014-09-07 20:29:59 +00001621getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1622 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001623 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001624 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001625
Nick Lewycky55a700b2010-12-18 01:00:40 +00001626 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001627 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001628 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001629 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001630 (void)WasFastQuery;
1631 assert(WasFastQuery && "More work to do after problem solved?");
1632 }
1633
David Greene37e98092009-12-23 20:43:58 +00001634 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001635 return Result;
1636}
1637
Philip Reames92e5e1b2016-09-12 21:46:58 +00001638void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Philip Reames9db79482016-09-12 22:38:44 +00001639 BasicBlock *NewSucc) {
1640 TheCache.threadEdgeImpl(OldSucc, NewSucc);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001641}
1642
Chris Lattneraf025d32009-11-15 19:59:49 +00001643//===----------------------------------------------------------------------===//
1644// LazyValueInfo Impl
1645//===----------------------------------------------------------------------===//
1646
Philip Reames92e5e1b2016-09-12 21:46:58 +00001647/// This lazily constructs the LazyValueInfoImpl.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001648static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1649 const DataLayout *DL,
Philip Reames92e5e1b2016-09-12 21:46:58 +00001650 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001651 if (!PImpl) {
1652 assert(DL && "getCache() called with a null DataLayout");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001653 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001654 }
Philip Reames92e5e1b2016-09-12 21:46:58 +00001655 return *static_cast<LazyValueInfoImpl*>(PImpl);
Chris Lattneraf025d32009-11-15 19:59:49 +00001656}
1657
Sean Silva687019f2016-06-13 22:01:25 +00001658bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001659 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001660 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001661
1662 DominatorTreeWrapperPass *DTWP =
1663 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001664 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1665 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001666
Sean Silva687019f2016-06-13 22:01:25 +00001667 if (Info.PImpl)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001668 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001669
Owen Anderson208636f2010-08-18 18:39:01 +00001670 // Fully lazy.
1671 return false;
1672}
1673
Sean Silva687019f2016-06-13 22:01:25 +00001674void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001675 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001676 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001677 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001678}
1679
Sean Silva687019f2016-06-13 22:01:25 +00001680LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1681
1682LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1683
Chris Lattneraf025d32009-11-15 19:59:49 +00001684void LazyValueInfo::releaseMemory() {
1685 // If the cache was allocated, free it.
1686 if (PImpl) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001687 delete &getImpl(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001688 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001689 }
1690}
1691
Chandler Carrutha504f2b2017-01-23 06:35:12 +00001692bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1693 FunctionAnalysisManager::Invalidator &Inv) {
1694 // We need to invalidate if we have either failed to preserve this analyses
1695 // result directly or if any of its dependencies have been invalidated.
1696 auto PAC = PA.getChecker<LazyValueAnalysis>();
1697 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
1698 (DT && Inv.invalidate<DominatorTreeAnalysis>(F, PA)))
1699 return true;
1700
1701 return false;
1702}
1703
Sean Silva687019f2016-06-13 22:01:25 +00001704void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1705
1706LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001707 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
Sean Silva687019f2016-06-13 22:01:25 +00001708 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1709 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1710
Anna Thomasa10e3e42017-03-12 14:06:41 +00001711 return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI, DT);
Sean Silva687019f2016-06-13 22:01:25 +00001712}
1713
Wei Mif160e342016-09-15 06:28:34 +00001714/// Returns true if we can statically tell that this value will never be a
1715/// "useful" constant. In practice, this means we've got something like an
1716/// alloca or a malloc call for which a comparison against a constant can
1717/// only be guarding dead code. Note that we are potentially giving up some
1718/// precision in dead code (a constant result) in favour of avoiding a
1719/// expensive search for a easily answered common query.
1720static bool isKnownNonConstant(Value *V) {
1721 V = V->stripPointerCasts();
1722 // The return val of alloc cannot be a Constant.
1723 if (isa<AllocaInst>(V))
1724 return true;
1725 return false;
1726}
1727
Hal Finkel7e184492014-09-07 20:29:59 +00001728Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1729 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001730 // Bail out early if V is known not to be a Constant.
1731 if (isKnownNonConstant(V))
1732 return nullptr;
1733
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001734 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001735 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001736 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001737
Chris Lattner19019ea2009-11-11 22:48:44 +00001738 if (Result.isConstant())
1739 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001740 if (Result.isConstantRange()) {
Craig Topper2b195fd2017-05-06 03:35:15 +00001741 const ConstantRange &CR = Result.getConstantRange();
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001742 if (const APInt *SingleVal = CR.getSingleElement())
1743 return ConstantInt::get(V->getContext(), *SingleVal);
1744 }
Craig Topper9f008862014-04-15 04:59:12 +00001745 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001746}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001747
John Regehre1c481d2016-05-02 19:58:00 +00001748ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001749 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001750 assert(V->getType()->isIntegerTy());
1751 unsigned Width = V->getType()->getIntegerBitWidth();
1752 const DataLayout &DL = BB->getModule()->getDataLayout();
1753 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001754 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001755 if (Result.isUndefined())
1756 return ConstantRange(Width, /*isFullSet=*/false);
1757 if (Result.isConstantRange())
1758 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001759 // We represent ConstantInt constants as constant ranges but other kinds
1760 // of integer constants, i.e. ConstantExpr will be tagged as constants
1761 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1762 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001763 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001764}
1765
Sanjay Patel2a385e22015-01-09 16:47:20 +00001766/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001767/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001768Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001769 BasicBlock *ToBB,
1770 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001771 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001772 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001773 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001774
Chris Lattnerd5e25432009-11-12 01:29:10 +00001775 if (Result.isConstant())
1776 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001777 if (Result.isConstantRange()) {
Craig Topper2b195fd2017-05-06 03:35:15 +00001778 const ConstantRange &CR = Result.getConstantRange();
Owen Anderson185fe002010-08-10 20:03:09 +00001779 if (const APInt *SingleVal = CR.getSingleElement())
1780 return ConstantInt::get(V->getContext(), *SingleVal);
1781 }
Craig Topper9f008862014-04-15 04:59:12 +00001782 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001783}
1784
Craig Topper2c20c422017-06-23 05:41:35 +00001785ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1786 BasicBlock *FromBB,
1787 BasicBlock *ToBB,
1788 Instruction *CxtI) {
1789 unsigned Width = V->getType()->getIntegerBitWidth();
1790 const DataLayout &DL = FromBB->getModule()->getDataLayout();
1791 LVILatticeVal Result =
1792 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1793
1794 if (Result.isUndefined())
1795 return ConstantRange(Width, /*isFullSet=*/false);
1796 if (Result.isConstantRange())
1797 return Result.getConstantRange();
1798 // We represent ConstantInt constants as constant ranges but other kinds
1799 // of integer constants, i.e. ConstantExpr will be tagged as constants
1800 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1801 "ConstantInt value must be represented as constantrange");
1802 return ConstantRange(Width, /*isFullSet=*/true);
1803}
1804
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001805static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
Craig Topper6dd9dcf2017-06-09 21:18:16 +00001806 const LVILatticeVal &Val,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001807 const DataLayout &DL,
1808 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001809
Chris Lattner565ee2f2009-11-12 04:36:58 +00001810 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001811 Constant *Res = nullptr;
Craig Topper6dd9dcf2017-06-09 21:18:16 +00001812 if (Val.isConstant()) {
1813 Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001814 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001815 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1816 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001817 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001818
Craig Topper6dd9dcf2017-06-09 21:18:16 +00001819 if (Val.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001820 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001821 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001822
Craig Topper6dd9dcf2017-06-09 21:18:16 +00001823 const ConstantRange &CR = Val.getConstantRange();
Owen Anderson185fe002010-08-10 20:03:09 +00001824 if (Pred == ICmpInst::ICMP_EQ) {
1825 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001826 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001827
Craig Topper79452482017-06-07 00:58:09 +00001828 if (CR.isSingleElement())
Hal Finkel7e184492014-09-07 20:29:59 +00001829 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001830 } else if (Pred == ICmpInst::ICMP_NE) {
1831 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001832 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001833
Craig Topper79452482017-06-07 00:58:09 +00001834 if (CR.isSingleElement())
Hal Finkel7e184492014-09-07 20:29:59 +00001835 return LazyValueInfo::False;
Craig Topper31ce4ec2017-06-09 16:16:20 +00001836 } else {
1837 // Handle more complex predicates.
1838 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1839 (ICmpInst::Predicate)Pred, CI->getValue());
1840 if (TrueValues.contains(CR))
1841 return LazyValueInfo::True;
1842 if (TrueValues.inverse().contains(CR))
1843 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001844 }
Hal Finkel7e184492014-09-07 20:29:59 +00001845 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001846 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001847
Craig Topper6dd9dcf2017-06-09 21:18:16 +00001848 if (Val.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001849 // If this is an equality comparison, we can try to fold it knowing that
1850 // "V != C1".
1851 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001852 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001853 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Craig Topper6dd9dcf2017-06-09 21:18:16 +00001854 Val.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001855 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001856 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001857 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001858 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001859 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001860 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Craig Topper6dd9dcf2017-06-09 21:18:16 +00001861 Val.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001862 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001863 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001864 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001865 }
Hal Finkel7e184492014-09-07 20:29:59 +00001866 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001867 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001868
Hal Finkel7e184492014-09-07 20:29:59 +00001869 return LazyValueInfo::Unknown;
1870}
1871
Sanjay Patel2a385e22015-01-09 16:47:20 +00001872/// Determine whether the specified value comparison with a constant is known to
1873/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001874LazyValueInfo::Tristate
1875LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1876 BasicBlock *FromBB, BasicBlock *ToBB,
1877 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001878 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001879 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001880 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001881
1882 return getPredicateResult(Pred, C, Result, DL, TLI);
1883}
1884
1885LazyValueInfo::Tristate
1886LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1887 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001888 // Is or is not NonNull are common predicates being queried. If
Nuno Lopes404f1062017-09-09 18:23:11 +00001889 // isKnownNonZero can tell us the result of the predicate, we can
Wei Mif160e342016-09-15 06:28:34 +00001890 // return it quickly. But this is only a fastpath, and falling
1891 // through would still be correct.
Nuno Lopes404f1062017-09-09 18:23:11 +00001892 const DataLayout &DL = CxtI->getModule()->getDataLayout();
Wei Mif160e342016-09-15 06:28:34 +00001893 if (V->getType()->isPointerTy() && C->isNullValue() &&
Nuno Lopes404f1062017-09-09 18:23:11 +00001894 isKnownNonZero(V->stripPointerCasts(), DL)) {
Wei Mif160e342016-09-15 06:28:34 +00001895 if (Pred == ICmpInst::ICMP_EQ)
1896 return LazyValueInfo::False;
1897 else if (Pred == ICmpInst::ICMP_NE)
1898 return LazyValueInfo::True;
1899 }
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001900 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001901 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1902 if (Ret != Unknown)
1903 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001904
Philip Reamesaeefae02015-11-04 01:47:04 +00001905 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1906 // LVI as a whole tries to compute a lattice value which is conservatively
1907 // correct at a given location. In this case, we have a predicate which we
1908 // weren't able to prove about the merged result, and we're pushing that
1909 // predicate back along each incoming edge to see if we can prove it
1910 // separately for each input. As a motivating example, consider:
1911 // bb1:
1912 // %v1 = ... ; constantrange<1, 5>
1913 // br label %merge
1914 // bb2:
1915 // %v2 = ... ; constantrange<10, 20>
1916 // br label %merge
1917 // merge:
1918 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1919 // %pred = icmp eq i32 %phi, 8
1920 // We can't tell from the lattice value for '%phi' that '%pred' is false
1921 // along each path, but by checking the predicate over each input separately,
1922 // we can.
1923 // We limit the search to one step backwards from the current BB and value.
1924 // We could consider extending this to search further backwards through the
1925 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001926 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001927 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001928 BasicBlock *BB = CxtI->getParent();
1929
1930 // Function entry or an unreachable block. Bail to avoid confusing
1931 // analysis below.
1932 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1933 if (PI == PE)
1934 return Unknown;
1935
1936 // If V is a PHI node in the same block as the context, we need to ask
1937 // questions about the predicate as applied to the incoming value along
1938 // each edge. This is useful for eliminating cases where the predicate is
1939 // known along all incoming edges.
1940 if (auto *PHI = dyn_cast<PHINode>(V))
1941 if (PHI->getParent() == BB) {
1942 Tristate Baseline = Unknown;
1943 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1944 Value *Incoming = PHI->getIncomingValue(i);
1945 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001946 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001947 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1948 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001949
Philip Reamesbb11d622015-08-31 18:31:48 +00001950 // Keep going as long as we've seen a consistent known result for
1951 // all inputs.
1952 Baseline = (i == 0) ? Result /* First iteration */
1953 : (Baseline == Result ? Baseline : Unknown); /* All others */
1954 if (Baseline == Unknown)
1955 break;
1956 }
1957 if (Baseline != Unknown)
1958 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001959 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001960
Philip Reames66ab0f02015-06-16 00:49:59 +00001961 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001962 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001963 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001964 if (!isa<Instruction>(V) ||
1965 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001966 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001967 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001968 // the value of the comparison in this block.
1969 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1970 if (Baseline != Unknown) {
1971 // Check that all remaining incoming values match the first one.
1972 while (++PI != PE) {
1973 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1974 if (Ret != Baseline) break;
1975 }
1976 // If we terminated early, then one of the values didn't match.
1977 if (PI == PE) {
1978 return Baseline;
1979 }
1980 }
1981 }
1982 }
1983 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001984}
1985
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001986void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001987 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001988 if (PImpl) {
1989 const DataLayout &DL = PredBB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001990 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001991 }
Owen Anderson208636f2010-08-18 18:39:01 +00001992}
1993
1994void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001995 if (PImpl) {
1996 const DataLayout &DL = BB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001997 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001998 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001999}
Anna Thomase27b39a2017-03-22 19:27:12 +00002000
2001
Anna Thomas4acfc7e2017-06-06 19:25:31 +00002002void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
Anna Thomase27b39a2017-03-22 19:27:12 +00002003 if (PImpl) {
Anna Thomas4acfc7e2017-06-06 19:25:31 +00002004 getImpl(PImpl, AC, DL, DT).printLVI(F, DTree, OS);
Anna Thomase27b39a2017-03-22 19:27:12 +00002005 }
2006}
2007
Anna Thomas4acfc7e2017-06-06 19:25:31 +00002008// Print the LVI for the function arguments at the start of each basic block.
2009void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2010 const BasicBlock *BB, formatted_raw_ostream &OS) {
2011 // Find if there are latticevalues defined for arguments of the function.
2012 auto *F = BB->getParent();
2013 for (auto &Arg : F->args()) {
2014 LVILatticeVal Result = LVIImpl->getValueInBlock(
2015 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2016 if (Result.isUndefined())
2017 continue;
2018 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
2019 }
2020}
2021
2022// This function prints the LVI analysis for the instruction I at the beginning
2023// of various basic blocks. It relies on calculated values that are stored in
2024// the LazyValueInfoCache, and in the absence of cached values, recalculte the
2025// LazyValueInfo for `I`, and print that info.
2026void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2027 const Instruction *I, formatted_raw_ostream &OS) {
2028
2029 auto *ParentBB = I->getParent();
2030 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2031 // We can generate (solve) LVI values only for blocks that are dominated by
2032 // the I's parent. However, to avoid generating LVI for all dominating blocks,
2033 // that contain redundant/uninteresting information, we print LVI for
2034 // blocks that may use this LVI information (such as immediate successor
2035 // blocks, and blocks that contain uses of `I`).
2036 auto printResult = [&](const BasicBlock *BB) {
2037 if (!BlocksContainingLVI.insert(BB).second)
2038 return;
2039 LVILatticeVal Result = LVIImpl->getValueInBlock(
2040 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2041 OS << "; LatticeVal for: '" << *I << "' in BB: '";
2042 BB->printAsOperand(OS, false);
2043 OS << "' is: " << Result << "\n";
2044 };
2045
2046 printResult(ParentBB);
2047 // Print the LVI analysis results for the the immediate successor blocks, that
2048 // are dominated by `ParentBB`.
2049 for (auto *BBSucc : successors(ParentBB))
2050 if (DT.dominates(ParentBB, BBSucc))
2051 printResult(BBSucc);
2052
2053 // Print LVI in blocks where `I` is used.
2054 for (auto *U : I->users())
2055 if (auto *UseI = dyn_cast<Instruction>(U))
2056 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2057 printResult(UseI->getParent());
2058
2059}
2060
Anna Thomase27b39a2017-03-22 19:27:12 +00002061namespace {
2062// Printer class for LazyValueInfo results.
2063class LazyValueInfoPrinter : public FunctionPass {
2064public:
2065 static char ID; // Pass identification, replacement for typeid
2066 LazyValueInfoPrinter() : FunctionPass(ID) {
2067 initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
2068 }
2069
2070 void getAnalysisUsage(AnalysisUsage &AU) const override {
2071 AU.setPreservesAll();
2072 AU.addRequired<LazyValueInfoWrapperPass>();
Anna Thomas4acfc7e2017-06-06 19:25:31 +00002073 AU.addRequired<DominatorTreeWrapperPass>();
Anna Thomase27b39a2017-03-22 19:27:12 +00002074 }
2075
Anna Thomas4acfc7e2017-06-06 19:25:31 +00002076 // Get the mandatory dominator tree analysis and pass this in to the
2077 // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
Anna Thomase27b39a2017-03-22 19:27:12 +00002078 bool runOnFunction(Function &F) override {
2079 dbgs() << "LVI for function '" << F.getName() << "':\n";
2080 auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
Anna Thomas4acfc7e2017-06-06 19:25:31 +00002081 auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2082 LVI.printLVI(F, DTree, dbgs());
Anna Thomase27b39a2017-03-22 19:27:12 +00002083 return false;
2084 }
2085};
2086}
2087
2088char LazyValueInfoPrinter::ID = 0;
2089INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
2090 "Lazy Value Info Printer Pass", false, false)
2091INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
2092INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
2093 "Lazy Value Info Printer Pass", false, false)