blob: 5904257492be66e621c3a7335b2219e76e119d99 [file] [log] [blame]
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
Chris Lattner741c94c2009-11-11 00:22:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000029#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000030#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000031#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000033#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000034#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000035using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000036using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000037
Chandler Carruthf1221bd2014-04-22 02:48:03 +000038#define DEBUG_TYPE "lazy-value-info"
39
Chris Lattner741c94c2009-11-11 00:22:30 +000040char LazyValueInfo::ID = 0;
Chad Rosier43a33062011-12-02 01:26:24 +000041INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
42 "Lazy Value Information Analysis", false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +000043INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000044INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chad Rosier43a33062011-12-02 01:26:24 +000045INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000046 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000047
48namespace llvm {
49 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
50}
51
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000052
53//===----------------------------------------------------------------------===//
54// LVILatticeVal
55//===----------------------------------------------------------------------===//
56
Sanjay Patel2a385e22015-01-09 16:47:20 +000057/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000058///
59/// FIXME: This is basically just for bringup, this can be made a lot more rich
60/// in the future.
61///
62namespace {
63class LVILatticeVal {
64 enum LatticeValueTy {
Sanjay Patel2a385e22015-01-09 16:47:20 +000065 /// This Value has no known value yet.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000066 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000067
Sanjay Patel2a385e22015-01-09 16:47:20 +000068 /// This Value has a specific constant value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000069 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000070
Sanjay Patel2a385e22015-01-09 16:47:20 +000071 /// This Value is known to not have the specified value.
Chris Lattner565ee2f2009-11-12 04:36:58 +000072 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000073
Sanjay Patel2a385e22015-01-09 16:47:20 +000074 /// The Value falls within this range.
Owen Anderson0f306a42010-08-05 22:59:19 +000075 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000076
Sanjay Patel2a385e22015-01-09 16:47:20 +000077 /// This value is not known to be constant, and we know that it has a value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000078 overdefined
79 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000080
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000081 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000082 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000083 LatticeValueTy Tag;
84 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000085 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000086
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000087public:
Craig Topper9f008862014-04-15 04:59:12 +000088 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000089
Chris Lattner19019ea2009-11-11 22:48:44 +000090 static LVILatticeVal get(Constant *C) {
91 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000092 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000093 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +000094 return Res;
95 }
Chris Lattner565ee2f2009-11-12 04:36:58 +000096 static LVILatticeVal getNot(Constant *C) {
97 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000098 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000099 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000100 return Res;
101 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000102 static LVILatticeVal getRange(ConstantRange CR) {
103 LVILatticeVal Res;
104 Res.markConstantRange(CR);
105 return Res;
106 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000107
Owen Anderson0f306a42010-08-05 22:59:19 +0000108 bool isUndefined() const { return Tag == undefined; }
109 bool isConstant() const { return Tag == constant; }
110 bool isNotConstant() const { return Tag == notconstant; }
111 bool isConstantRange() const { return Tag == constantrange; }
112 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000113
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000114 Constant *getConstant() const {
115 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000116 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000117 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000118
Chris Lattner565ee2f2009-11-12 04:36:58 +0000119 Constant *getNotConstant() const {
120 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000121 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000122 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000123
Owen Anderson0f306a42010-08-05 22:59:19 +0000124 ConstantRange getConstantRange() const {
125 assert(isConstantRange() &&
126 "Cannot get the constant-range of a non-constant-range!");
127 return Range;
128 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000129
Sanjay Patel2a385e22015-01-09 16:47:20 +0000130 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000131 bool markOverdefined() {
132 if (isOverdefined())
133 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000134 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000135 return true;
136 }
137
Sanjay Patel2a385e22015-01-09 16:47:20 +0000138 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000139 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000140 assert(V && "Marking constant with NULL");
141 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
142 return markConstantRange(ConstantRange(CI->getValue()));
143 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000144 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000145
146 assert((!isConstant() || getConstant() == V) &&
147 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000148 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000149 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000150 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000151 return true;
152 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000153
Sanjay Patel2a385e22015-01-09 16:47:20 +0000154 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000155 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000156 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000157 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
158 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
159 if (isa<UndefValue>(V))
160 return false;
161
162 assert((!isConstant() || getConstant() != V) &&
163 "Marking constant !constant with same value");
164 assert((!isNotConstant() || getNotConstant() == V) &&
165 "Marking !constant with different value");
166 assert(isUndefined() || isConstant());
167 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000168 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000169 return true;
170 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000171
Sanjay Patel2a385e22015-01-09 16:47:20 +0000172 /// Return true if this is a change in status.
Owen Anderson0f306a42010-08-05 22:59:19 +0000173 bool markConstantRange(const ConstantRange NewR) {
174 if (isConstantRange()) {
175 if (NewR.isEmptySet())
176 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000177
Nuno Lopese6e04902012-06-28 01:16:18 +0000178 bool changed = Range != NewR;
Owen Anderson0f306a42010-08-05 22:59:19 +0000179 Range = NewR;
180 return changed;
181 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000182
Owen Anderson0f306a42010-08-05 22:59:19 +0000183 assert(isUndefined());
184 if (NewR.isEmptySet())
185 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000186
Owen Anderson0f306a42010-08-05 22:59:19 +0000187 Tag = constantrange;
188 Range = NewR;
189 return true;
190 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000191
Sanjay Patel2a385e22015-01-09 16:47:20 +0000192 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000193 /// one and returning true if anything changed.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000194 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
Chris Lattner19019ea2009-11-11 22:48:44 +0000195 if (RHS.isUndefined() || isOverdefined()) return false;
196 if (RHS.isOverdefined()) return markOverdefined();
197
Nick Lewycky11678bd2010-12-15 18:57:18 +0000198 if (isUndefined()) {
199 Tag = RHS.Tag;
200 Val = RHS.Val;
201 Range = RHS.Range;
202 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000203 }
204
Nick Lewycky11678bd2010-12-15 18:57:18 +0000205 if (isConstant()) {
206 if (RHS.isConstant()) {
207 if (Val == RHS.Val)
208 return false;
209 return markOverdefined();
210 }
211
212 if (RHS.isNotConstant()) {
213 if (Val == RHS.Val)
214 return markOverdefined();
215
216 // Unless we can prove that the two Constants are different, we must
217 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000218 if (ConstantInt *Res =
219 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
220 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000221 if (Res->isOne())
222 return markNotConstant(RHS.getNotConstant());
223
224 return markOverdefined();
225 }
226
227 // RHS is a ConstantRange, LHS is a non-integer Constant.
228
229 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
230 // a function. The correct result is to pick up RHS.
231
Chris Lattner19019ea2009-11-11 22:48:44 +0000232 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000233 }
234
235 if (isNotConstant()) {
236 if (RHS.isConstant()) {
237 if (Val == RHS.Val)
238 return markOverdefined();
239
240 // Unless we can prove that the two Constants are different, we must
241 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000242 if (ConstantInt *Res =
243 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
244 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000245 if (Res->isOne())
246 return false;
247
248 return markOverdefined();
249 }
250
251 if (RHS.isNotConstant()) {
252 if (Val == RHS.Val)
253 return false;
254 return markOverdefined();
255 }
256
257 return markOverdefined();
258 }
259
260 assert(isConstantRange() && "New LVILattice type?");
261 if (!RHS.isConstantRange())
262 return markOverdefined();
263
264 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
265 if (NewR.isFullSet())
266 return markOverdefined();
267 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000268 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000269};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000270
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000271} // end anonymous namespace.
272
Chris Lattner19019ea2009-11-11 22:48:44 +0000273namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000274raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
275 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000276raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
277 if (Val.isUndefined())
278 return OS << "undefined";
279 if (Val.isOverdefined())
280 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000281
282 if (Val.isNotConstant())
283 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson8afac042010-08-09 20:50:46 +0000284 else if (Val.isConstantRange())
285 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
286 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000287 return OS << "constant<" << *Val.getConstant() << '>';
288}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000289}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000290
291//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000292// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000293//===----------------------------------------------------------------------===//
294
Chris Lattneraf025d32009-11-15 19:59:49 +0000295namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000296 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000297 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000298 struct LVIValueHandle final : public CallbackVH {
Owen Anderson118ac802011-01-05 21:15:29 +0000299 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000300
Owen Anderson118ac802011-01-05 21:15:29 +0000301 LVIValueHandle(Value *V, LazyValueInfoCache *P)
302 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000303
304 void deleted() override;
305 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000306 deleted();
307 }
308 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000309}
Owen Anderson118ac802011-01-05 21:15:29 +0000310
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000311namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000312 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000313 /// maintains information about queries across the clients' queries.
314 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000315 /// This is all of the cached block information for exactly one Value*.
316 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000317 /// entries, allowing us to do a lookup with a binary search.
Bill Wendling4ec081a2012-01-11 23:43:34 +0000318 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000319
Sanjay Patel2a385e22015-01-09 16:47:20 +0000320 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000321 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000322 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000323
Sanjay Patel2a385e22015-01-09 16:47:20 +0000324 /// This tracks, on a per-block basis, the set of values that are
325 /// over-defined at the end of that block. This is required
Owen Anderson6f060af2011-01-05 23:26:22 +0000326 /// for cache updating.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000327 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
328 OverDefinedCacheTy;
329 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000330
Sanjay Patel2a385e22015-01-09 16:47:20 +0000331 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000332 /// don't spend time removing unused blocks from our caches.
333 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
334
Sanjay Patel2a385e22015-01-09 16:47:20 +0000335 /// This stack holds the state of the value solver during a query.
336 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000337 /// recursive value lookup process.
338 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000339
Sanjay Patel2a385e22015-01-09 16:47:20 +0000340 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000341 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
342
Sanjay Patel2a385e22015-01-09 16:47:20 +0000343 /// Push BV onto BlockValueStack unless it's already in there.
344 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000345 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000346 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000347 return false; // It's already in the stack.
348
349 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000350 return true;
351 }
352
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
354 const DataLayout &DL; ///< A mandatory DataLayout
355 DominatorTree *DT; ///< An optional DT pointer.
356
Owen Anderson118ac802011-01-05 21:15:29 +0000357 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000358
Hans Wennborg45172ac2014-11-25 17:23:05 +0000359 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
360 SeenBlocks.insert(BB);
361 lookup(Val)[BB] = Result;
362 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000363 OverDefinedCache[BB].insert(Val);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000364 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000365
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000366 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000367 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000368 LVILatticeVal &Result,
369 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000370 bool hasBlockValue(Value *Val, BasicBlock *BB);
371
372 // These methods process one work item and may add more. A false value
373 // returned means that the work item was not completely processed and must
374 // be revisited after going through the new items.
375 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000376 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
377 Value *Val, BasicBlock *BB);
378 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
379 PHINode *PN, BasicBlock *BB);
380 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
381 Instruction *BBI, BasicBlock *BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000382 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
383 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000384
385 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000386
Nick Lewycky11678bd2010-12-15 18:57:18 +0000387 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000388 return ValueCache[LVIValueHandle(V, this)];
389 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000390
Chris Lattneraf025d32009-11-15 19:59:49 +0000391 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000392 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000393 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000394 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
395 Instruction *CxtI = nullptr);
396
Sanjay Patel2a385e22015-01-09 16:47:20 +0000397 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000398 /// value for the specified Value* at the specified instruction (generally
399 /// from an assume intrinsic).
400 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000401
Sanjay Patel2a385e22015-01-09 16:47:20 +0000402 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000403 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000404 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
405 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000406
Sanjay Patel2a385e22015-01-09 16:47:20 +0000407 /// This is the update interface to inform the cache that an edge from
408 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000409 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000410
Sanjay Patel2a385e22015-01-09 16:47:20 +0000411 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000412 /// that a block has been deleted.
413 void eraseBlock(BasicBlock *BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000414
Owen Anderson208636f2010-08-18 18:39:01 +0000415 /// clear - Empty the cache.
416 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000417 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000418 ValueCache.clear();
419 OverDefinedCache.clear();
420 }
Hal Finkel7e184492014-09-07 20:29:59 +0000421
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000423 DominatorTree *DT = nullptr)
424 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000425 };
426} // end anonymous namespace
427
Owen Anderson118ac802011-01-05 21:15:29 +0000428void LVIValueHandle::deleted() {
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000429 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
430 for (auto &I : Parent->OverDefinedCache) {
431 SmallPtrSetImpl<Value *> &ValueSet = I.second;
432 if (ValueSet.count(getValPtr()))
433 ValueSet.erase(getValPtr());
434 if (ValueSet.empty())
435 ToErase.push_back(I.first);
436 }
437 for (auto &BB : ToErase)
438 Parent->OverDefinedCache.erase(BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000439
Owen Anderson7b974a42010-08-11 22:36:04 +0000440 // This erasure deallocates *this, so it MUST happen after we're done
441 // using any and all members of *this.
442 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000443}
444
Owen Anderson208636f2010-08-18 18:39:01 +0000445void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000446 // Shortcut if we have never seen this block.
447 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
448 if (I == SeenBlocks.end())
449 return;
450 SeenBlocks.erase(I);
451
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000452 auto ODI = OverDefinedCache.find(BB);
453 if (ODI != OverDefinedCache.end())
454 OverDefinedCache.erase(ODI);
Owen Anderson208636f2010-08-18 18:39:01 +0000455
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000456 for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
Owen Anderson208636f2010-08-18 18:39:01 +0000457 I->second.erase(BB);
458}
Owen Andersonc1561b82010-07-30 23:59:40 +0000459
Nick Lewycky55a700b2010-12-18 01:00:40 +0000460void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000461 while (!BlockValueStack.empty()) {
462 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000463 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
464
Nuno Lopese6e04902012-06-28 01:16:18 +0000465 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000466 // The work item was completely processed.
467 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
468 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
469
Owen Anderson6f060af2011-01-05 23:26:22 +0000470 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000471 BlockValueSet.erase(e);
472 } else {
473 // More work needs to be done before revisiting.
474 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000475 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000476 }
477}
478
479bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
480 // If already a constant, there is nothing to compute.
481 if (isa<Constant>(Val))
482 return true;
483
Owen Anderson118ac802011-01-05 21:15:29 +0000484 LVIValueHandle ValHandle(Val, this);
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000485 auto I = ValueCache.find(ValHandle);
Benjamin Kramerf29db272012-08-22 15:37:57 +0000486 if (I == ValueCache.end()) return false;
487 return I->second.count(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000488}
489
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000490LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000491 // If already a constant, there is nothing to compute.
492 if (Constant *VC = dyn_cast<Constant>(Val))
493 return LVILatticeVal::get(VC);
494
Benjamin Kramer36647082011-12-03 15:16:45 +0000495 SeenBlocks.insert(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000496 return lookup(Val)[BB];
497}
498
499bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
500 if (isa<Constant>(Val))
501 return true;
502
Hans Wennborg45172ac2014-11-25 17:23:05 +0000503 if (lookup(Val).count(BB)) {
504 // If we have a cached value, use that.
505 DEBUG(dbgs() << " reuse BB '" << BB->getName()
506 << "' val=" << lookup(Val)[BB] << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000507
Hans Wennborg45172ac2014-11-25 17:23:05 +0000508 // Since we're reusing a cached value, we don't need to update the
509 // OverDefinedCache. The cache will have been properly updated whenever the
510 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000511 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000512 }
513
Hans Wennborg45172ac2014-11-25 17:23:05 +0000514 // Hold off inserting this value into the Cache in case we have to return
515 // false and come back later.
516 LVILatticeVal Res;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000517
Chris Lattneraf025d32009-11-15 19:59:49 +0000518 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000519 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000520 if (!solveBlockValueNonLocal(Res, Val, BB))
521 return false;
522 insertResult(Val, BB, Res);
523 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000524 }
Chris Lattner2c708562009-11-15 20:00:52 +0000525
Nick Lewycky55a700b2010-12-18 01:00:40 +0000526 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000527 if (!solveBlockValuePHINode(Res, PN, BB))
528 return false;
529 insertResult(Val, BB, Res);
530 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000531 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000532
Nick Lewycky367f98f2011-01-15 09:16:12 +0000533 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000534 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
535 insertResult(Val, BB, Res);
536 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000537 }
538
Owen Anderson80d19f02010-08-18 21:11:37 +0000539 // We can only analyze the definitions of certain classes of instructions
540 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000541 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000542 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
543 !BBI->getType()->isIntegerTy()) {
544 DEBUG(dbgs() << " compute BB '" << BB->getName()
545 << "' - overdefined because inst def found.\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000546 Res.markOverdefined();
547 insertResult(Val, BB, Res);
548 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000549 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000550
Owen Anderson80d19f02010-08-18 21:11:37 +0000551 // FIXME: We're currently limited to binops with a constant RHS. This should
552 // be improved.
553 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
554 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
555 DEBUG(dbgs() << " compute BB '" << BB->getName()
556 << "' - overdefined because inst def found.\n");
557
Hans Wennborg45172ac2014-11-25 17:23:05 +0000558 Res.markOverdefined();
559 insertResult(Val, BB, Res);
560 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000561 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000562
Hans Wennborg45172ac2014-11-25 17:23:05 +0000563 if (!solveBlockValueConstantRange(Res, BBI, BB))
564 return false;
565 insertResult(Val, BB, Res);
566 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000567}
568
569static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
570 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
571 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000572 GetUnderlyingObject(L->getPointerOperand(),
573 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000574 }
575 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
576 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000577 GetUnderlyingObject(S->getPointerOperand(),
578 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000579 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000580 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
581 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000582
583 // FIXME: check whether it has a valuerange that excludes zero?
584 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
585 if (!Len || Len->isZero()) return false;
586
Eli Friedman7a5fc692011-05-31 20:40:16 +0000587 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 if (GetUnderlyingObject(MI->getRawDest(),
589 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000590 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000591 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000592 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000593 if (GetUnderlyingObject(MTI->getRawSource(),
594 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000595 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000596 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000597 return false;
598}
599
Owen Anderson64c2c572010-12-20 18:18:16 +0000600bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
601 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000602 LVILatticeVal Result; // Start Undefined.
603
604 // If this is a pointer, and there's a load from that pointer in this BB,
605 // then we know that the pointer can't be NULL.
606 bool NotNull = false;
607 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000608 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000609 NotNull = true;
610 } else {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000611 const DataLayout &DL = BB->getModule()->getDataLayout();
612 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000613 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
614 // inside InstructionDereferencesPointer either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000615 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000616 for (Instruction &I : *BB) {
617 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000618 NotNull = true;
619 break;
620 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000621 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000622 }
623 }
624 }
625
626 // If this is the entry block, we must be asking about an argument. The
627 // value is overdefined.
628 if (BB == &BB->getParent()->getEntryBlock()) {
629 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
630 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000631 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000632 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
633 } else {
634 Result.markOverdefined();
635 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000636 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000637 return true;
638 }
639
640 // Loop over all of our predecessors, merging what we know from them into
641 // result.
642 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000643 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000644 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000645 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000646 if (EdgesMissing)
647 continue;
648
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000649 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000650
651 // If we hit overdefined, exit early. The BlockVals entry is already set
652 // to overdefined.
653 if (Result.isOverdefined()) {
654 DEBUG(dbgs() << " compute BB '" << BB->getName()
655 << "' - overdefined because of pred.\n");
656 // If we previously determined that this is a pointer that can't be null
657 // then return that rather than giving up entirely.
658 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000659 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000660 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
661 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000662
Owen Anderson64c2c572010-12-20 18:18:16 +0000663 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000664 return true;
665 }
666 }
667 if (EdgesMissing)
668 return false;
669
670 // Return the merged value, which is more precise than 'overdefined'.
671 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000672 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000673 return true;
674}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000675
Owen Anderson64c2c572010-12-20 18:18:16 +0000676bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
677 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000678 LVILatticeVal Result; // Start Undefined.
679
680 // Loop over all of our predecessors, merging what we know from them into
681 // result.
682 bool EdgesMissing = false;
683 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
684 BasicBlock *PhiBB = PN->getIncomingBlock(i);
685 Value *PhiVal = PN->getIncomingValue(i);
686 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000687 // Note that we can provide PN as the context value to getEdgeValue, even
688 // though the results will be cached, because PN is the value being used as
689 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000690 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000691 if (EdgesMissing)
692 continue;
693
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000694 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000695
696 // If we hit overdefined, exit early. The BlockVals entry is already set
697 // to overdefined.
698 if (Result.isOverdefined()) {
699 DEBUG(dbgs() << " compute BB '" << BB->getName()
700 << "' - overdefined because of pred.\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000701
Owen Anderson64c2c572010-12-20 18:18:16 +0000702 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000703 return true;
704 }
705 }
706 if (EdgesMissing)
707 return false;
708
709 // Return the merged value, which is more precise than 'overdefined'.
710 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000711 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000712 return true;
713}
714
Hal Finkel7e184492014-09-07 20:29:59 +0000715static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
716 LVILatticeVal &Result,
717 bool isTrueDest = true);
718
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000719// If we can determine a constant range for the value Val in the context
Hal Finkel7e184492014-09-07 20:29:59 +0000720// provided by the instruction BBI, then merge it into BBLV. If we did find a
721// constant range, return true.
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000722void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
723 LVILatticeVal &BBLV,
724 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000725 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
726 if (!BBI)
727 return;
728
Chandler Carruth66b31302015-01-04 12:03:27 +0000729 for (auto &AssumeVH : AC->assumptions()) {
730 if (!AssumeVH)
731 continue;
732 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000733 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000734 continue;
735
736 Value *C = I->getArgOperand(0);
737 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
738 LVILatticeVal Result;
739 if (getValueFromFromCondition(Val, ICI, Result)) {
740 if (BBLV.isOverdefined())
741 BBLV = Result;
742 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000743 BBLV.mergeIn(Result, DL);
Hal Finkel7e184492014-09-07 20:29:59 +0000744 }
745 }
746 }
747}
748
Owen Anderson64c2c572010-12-20 18:18:16 +0000749bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
750 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000751 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000752 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000753 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000754 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
755 return false;
756 BBLV.markOverdefined();
757 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000758 }
759
Nick Lewycky55a700b2010-12-18 01:00:40 +0000760 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000761 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000762 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000763 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000764 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000765 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000766
Owen Anderson80d19f02010-08-18 21:11:37 +0000767 ConstantRange LHSRange = LHSVal.getConstantRange();
768 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000769 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000770 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000771 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
772 RHSRange = ConstantRange(RHS->getValue());
773 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000774 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000775 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000776 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000777 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000778
Owen Anderson80d19f02010-08-18 21:11:37 +0000779 // NOTE: We're currently limited by the set of operations that ConstantRange
780 // can evaluate symbolically. Enhancing that set will allows us to analyze
781 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000782 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000783 switch (BBI->getOpcode()) {
784 case Instruction::Add:
785 Result.markConstantRange(LHSRange.add(RHSRange));
786 break;
787 case Instruction::Sub:
788 Result.markConstantRange(LHSRange.sub(RHSRange));
789 break;
790 case Instruction::Mul:
791 Result.markConstantRange(LHSRange.multiply(RHSRange));
792 break;
793 case Instruction::UDiv:
794 Result.markConstantRange(LHSRange.udiv(RHSRange));
795 break;
796 case Instruction::Shl:
797 Result.markConstantRange(LHSRange.shl(RHSRange));
798 break;
799 case Instruction::LShr:
800 Result.markConstantRange(LHSRange.lshr(RHSRange));
801 break;
802 case Instruction::Trunc:
803 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
804 break;
805 case Instruction::SExt:
806 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
807 break;
808 case Instruction::ZExt:
809 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
810 break;
811 case Instruction::BitCast:
812 Result.markConstantRange(LHSRange);
813 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +0000814 case Instruction::And:
815 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
816 break;
817 case Instruction::Or:
818 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
819 break;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000820
Owen Anderson80d19f02010-08-18 21:11:37 +0000821 // Unhandled instructions are overdefined.
822 default:
823 DEBUG(dbgs() << " compute BB '" << BB->getName()
824 << "' - overdefined because inst def found.\n");
825 Result.markOverdefined();
826 break;
827 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000828
Owen Anderson64c2c572010-12-20 18:18:16 +0000829 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000830 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +0000831}
832
Hal Finkel7e184492014-09-07 20:29:59 +0000833bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
834 LVILatticeVal &Result, bool isTrueDest) {
835 if (ICI && isa<Constant>(ICI->getOperand(1))) {
836 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
837 // We know that V has the RHS constant if this is a true SETEQ or
838 // false SETNE.
839 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
840 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
841 else
842 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
843 return true;
844 }
845
846 // Recognize the range checking idiom that InstCombine produces.
847 // (X-C1) u< C2 --> [C1, C1+C2)
848 ConstantInt *NegOffset = nullptr;
849 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
850 match(ICI->getOperand(0), m_Add(m_Specific(Val),
851 m_ConstantInt(NegOffset)));
852
853 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
854 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Sanjoy Das7182d362015-03-18 00:41:24 +0000855 // Calculate the range of values that are allowed by the comparison
Hal Finkel7e184492014-09-07 20:29:59 +0000856 ConstantRange CmpRange(CI->getValue());
857 ConstantRange TrueValues =
Sanjoy Das7182d362015-03-18 00:41:24 +0000858 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
Hal Finkel7e184492014-09-07 20:29:59 +0000859
860 if (NegOffset) // Apply the offset from above.
861 TrueValues = TrueValues.subtract(NegOffset->getValue());
862
863 // If we're interested in the false dest, invert the condition.
864 if (!isTrueDest) TrueValues = TrueValues.inverse();
865
866 Result = LVILatticeVal::getRange(TrueValues);
867 return true;
868 }
869 }
870
871 return false;
872}
873
Nuno Lopese6e04902012-06-28 01:16:18 +0000874/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
875/// Val is not constrained on the edge.
876static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
877 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000878 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +0000879 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +0000880 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
881 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +0000882 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +0000883 if (BI->isConditional() &&
884 BI->getSuccessor(0) != BI->getSuccessor(1)) {
885 bool isTrueDest = BI->getSuccessor(0) == BBTo;
886 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
887 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000888
Chris Lattner19019ea2009-11-11 22:48:44 +0000889 // If V is the condition of the branch itself, then we know exactly what
890 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000891 if (BI->getCondition() == Val) {
892 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +0000893 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000894 return true;
895 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000896
Chris Lattner19019ea2009-11-11 22:48:44 +0000897 // If the condition of the branch is an equality comparison, we may be
898 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +0000899 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
900 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
901 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000902 }
903 }
Chris Lattner77358782009-11-15 20:02:12 +0000904
905 // If the edge was formed by a switch on the value, then we may know exactly
906 // what it is.
907 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000908 if (SI->getCondition() != Val)
909 return false;
910
911 bool DefaultCase = SI->getDefaultDest() == BBTo;
912 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
913 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
914
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000915 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000916 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +0000917 if (DefaultCase) {
918 // It is possible that the default destination is the destination of
919 // some cases. There is no need to perform difference for those cases.
920 if (i.getCaseSuccessor() != BBTo)
921 EdgesVals = EdgesVals.difference(EdgeVal);
922 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +0000923 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +0000924 }
Nuno Lopes8650fb82012-06-28 16:13:37 +0000925 Result = LVILatticeVal::getRange(EdgesVals);
926 return true;
Chris Lattner77358782009-11-15 20:02:12 +0000927 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000928 return false;
929}
930
Sanjay Patel938e2792015-01-09 16:35:37 +0000931/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
932/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +0000933bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +0000934 BasicBlock *BBTo, LVILatticeVal &Result,
935 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +0000936 // If already a constant, there is nothing to compute.
937 if (Constant *VC = dyn_cast<Constant>(Val)) {
938 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000939 return true;
940 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000941
942 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
943 if (!Result.isConstantRange() ||
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000944 Result.getConstantRange().getSingleElement())
Nuno Lopese6e04902012-06-28 01:16:18 +0000945 return true;
946
947 // FIXME: this check should be moved to the beginning of the function when
948 // LVI better supports recursive values. Even for the single value case, we
949 // can intersect to detect dead code (an empty range).
950 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000951 if (pushBlockValue(std::make_pair(BBFrom, Val)))
952 return false;
953 Result.markOverdefined();
954 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000955 }
956
957 // Try to intersect ranges of the BB and the constraint on the edge.
958 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000959 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000960 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
961 // and caching, below.
Hal Finkel7e184492014-09-07 20:29:59 +0000962 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000963 if (!InBlock.isConstantRange())
964 return true;
965
966 ConstantRange Range =
967 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
968 Result = LVILatticeVal::getRange(Range);
969 return true;
970 }
971
972 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000973 if (pushBlockValue(std::make_pair(BBFrom, Val)))
974 return false;
975 Result.markOverdefined();
976 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000977 }
978
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000979 // If we couldn't compute the value on the edge, use the value from the BB.
Nuno Lopese6e04902012-06-28 01:16:18 +0000980 Result = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000981 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000982 // We can use the context instruction (generically the ultimate instruction
983 // the calling pass is trying to simplify) here, even though the result of
984 // this function is generally cached when called from the solve* functions
985 // (and that cached result might be used with queries using a different
986 // context instruction), because when this function is called from the solve*
987 // functions, the context instruction is not provided. When called from
988 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
989 // but then the result is not cached.
Hal Finkel7e184492014-09-07 20:29:59 +0000990 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000991 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000992}
993
Hal Finkel7e184492014-09-07 20:29:59 +0000994LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
995 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +0000996 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +0000997 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000998
Hans Wennborg45172ac2014-11-25 17:23:05 +0000999 assert(BlockValueStack.empty() && BlockValueSet.empty());
1000 pushBlockValue(std::make_pair(BB, V));
1001
Nick Lewycky55a700b2010-12-18 01:00:40 +00001002 solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001003 LVILatticeVal Result = getBlockValue(V, BB);
Hal Finkel7e184492014-09-07 20:29:59 +00001004 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1005
1006 DEBUG(dbgs() << " Result = " << Result << "\n");
1007 return Result;
1008}
1009
1010LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1011 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1012 << CxtI->getName() << "'\n");
1013
1014 LVILatticeVal Result;
1015 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001016
David Greene37e98092009-12-23 20:43:58 +00001017 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001018 return Result;
1019}
Chris Lattner19019ea2009-11-11 22:48:44 +00001020
Chris Lattneraf025d32009-11-15 19:59:49 +00001021LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001022getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1023 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001024 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001025 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001026
Nick Lewycky55a700b2010-12-18 01:00:40 +00001027 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001028 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001029 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001030 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001031 (void)WasFastQuery;
1032 assert(WasFastQuery && "More work to do after problem solved?");
1033 }
1034
David Greene37e98092009-12-23 20:43:58 +00001035 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001036 return Result;
1037}
1038
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001039void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1040 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001041 // When an edge in the graph has been threaded, values that we could not
1042 // determine a value for before (i.e. were marked overdefined) may be
1043 // possible to solve now. We do NOT try to proactively update these values.
1044 // Instead, we clear their entries from the cache, and allow lazy updating to
1045 // recompute them when needed.
1046
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001047 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001048 // for all values that were marked overdefined in OldSucc, and for those same
1049 // values in any successor of OldSucc (except NewSucc) in which they were
1050 // also marked overdefined.
1051 std::vector<BasicBlock*> worklist;
1052 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001053
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001054 auto I = OverDefinedCache.find(OldSucc);
1055 if (I == OverDefinedCache.end())
1056 return; // Nothing to process here.
1057 SmallPtrSetImpl<Value *> &ClearSet = I->second;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001058
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001059 // Use a worklist to perform a depth-first search of OldSucc's successors.
1060 // NOTE: We do not need a visited list since any blocks we have already
1061 // visited will have had their overdefined markers cleared already, and we
1062 // thus won't loop to their successors.
1063 while (!worklist.empty()) {
1064 BasicBlock *ToUpdate = worklist.back();
1065 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001066
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001067 // Skip blocks only accessible through NewSucc.
1068 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001069
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001070 bool changed = false;
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001071 for (Value *V : ClearSet) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001072 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001073 auto OI = OverDefinedCache.find(ToUpdate);
1074 if (OI == OverDefinedCache.end())
1075 continue;
1076 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1077 if (!ValueSet.count(V))
1078 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001079
Owen Andersonaac5a722010-07-27 23:58:11 +00001080 // Remove it from the caches.
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001081 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
Owen Andersonaac5a722010-07-27 23:58:11 +00001082 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001083
Owen Andersonaac5a722010-07-27 23:58:11 +00001084 assert(CI != Entry.end() && "Couldn't find entry to update?");
1085 Entry.erase(CI);
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001086 ValueSet.erase(V);
1087 if (ValueSet.empty())
1088 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001089
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001090 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001091 // blocks successors too.
1092 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001093 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001094
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001095 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001096
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001097 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1098 }
1099}
1100
Chris Lattneraf025d32009-11-15 19:59:49 +00001101//===----------------------------------------------------------------------===//
1102// LazyValueInfo Impl
1103//===----------------------------------------------------------------------===//
1104
Sanjay Patel2a385e22015-01-09 16:47:20 +00001105/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001106static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001107 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001108 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001109 if (!PImpl) {
1110 assert(DL && "getCache() called with a null DataLayout");
1111 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1112 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001113 return *static_cast<LazyValueInfoCache*>(PImpl);
1114}
1115
Owen Anderson208636f2010-08-18 18:39:01 +00001116bool LazyValueInfo::runOnFunction(Function &F) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001117 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001118 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001119
1120 DominatorTreeWrapperPass *DTWP =
1121 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1122 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001123
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001124 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001125
Hal Finkel7e184492014-09-07 20:29:59 +00001126 if (PImpl)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001127 getCache(PImpl, AC, &DL, DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001128
Owen Anderson208636f2010-08-18 18:39:01 +00001129 // Fully lazy.
1130 return false;
1131}
1132
Chad Rosier43a33062011-12-02 01:26:24 +00001133void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1134 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001135 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001136 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001137}
1138
Chris Lattneraf025d32009-11-15 19:59:49 +00001139void LazyValueInfo::releaseMemory() {
1140 // If the cache was allocated, free it.
1141 if (PImpl) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001142 delete &getCache(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001143 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001144 }
1145}
1146
Hal Finkel7e184492014-09-07 20:29:59 +00001147Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1148 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001149 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001150 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001151 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001152
Chris Lattner19019ea2009-11-11 22:48:44 +00001153 if (Result.isConstant())
1154 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001155 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001156 ConstantRange CR = Result.getConstantRange();
1157 if (const APInt *SingleVal = CR.getSingleElement())
1158 return ConstantInt::get(V->getContext(), *SingleVal);
1159 }
Craig Topper9f008862014-04-15 04:59:12 +00001160 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001161}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001162
Sanjay Patel2a385e22015-01-09 16:47:20 +00001163/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001164/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001165Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001166 BasicBlock *ToBB,
1167 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001168 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001169 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001170 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001171
Chris Lattnerd5e25432009-11-12 01:29:10 +00001172 if (Result.isConstant())
1173 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001174 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001175 ConstantRange CR = Result.getConstantRange();
1176 if (const APInt *SingleVal = CR.getSingleElement())
1177 return ConstantInt::get(V->getContext(), *SingleVal);
1178 }
Craig Topper9f008862014-04-15 04:59:12 +00001179 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001180}
1181
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001182static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1183 LVILatticeVal &Result,
1184 const DataLayout &DL,
1185 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001186
Chris Lattner565ee2f2009-11-12 04:36:58 +00001187 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001188 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001189 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001190 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001191 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001192 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001193 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1194 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001195 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001196
Owen Anderson185fe002010-08-10 20:03:09 +00001197 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001198 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001199 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001200
Owen Anderson185fe002010-08-10 20:03:09 +00001201 ConstantRange CR = Result.getConstantRange();
1202 if (Pred == ICmpInst::ICMP_EQ) {
1203 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001204 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001205
Owen Anderson185fe002010-08-10 20:03:09 +00001206 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001207 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001208 } else if (Pred == ICmpInst::ICMP_NE) {
1209 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001210 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001211
Owen Anderson185fe002010-08-10 20:03:09 +00001212 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001213 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001214 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001215
Owen Anderson185fe002010-08-10 20:03:09 +00001216 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001217 ConstantRange TrueValues =
1218 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1219 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001220 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001221 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001222 return LazyValueInfo::False;
1223 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001224 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001225
Chris Lattneraf025d32009-11-15 19:59:49 +00001226 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001227 // If this is an equality comparison, we can try to fold it knowing that
1228 // "V != C1".
1229 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001230 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001231 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001232 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001233 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001234 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001235 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001236 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001237 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001238 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001239 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001240 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001241 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001242 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001243 }
Hal Finkel7e184492014-09-07 20:29:59 +00001244 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001245 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001246
Hal Finkel7e184492014-09-07 20:29:59 +00001247 return LazyValueInfo::Unknown;
1248}
1249
Sanjay Patel2a385e22015-01-09 16:47:20 +00001250/// Determine whether the specified value comparison with a constant is known to
1251/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001252LazyValueInfo::Tristate
1253LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1254 BasicBlock *FromBB, BasicBlock *ToBB,
1255 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001256 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001257 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001258 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001259
1260 return getPredicateResult(Pred, C, Result, DL, TLI);
1261}
1262
1263LazyValueInfo::Tristate
1264LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1265 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001266 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1267 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001268 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1269 if (Ret != Unknown)
1270 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001271
Philip Reames66ab0f02015-06-16 00:49:59 +00001272 // TODO: Move this logic inside getValueAt so that it can be cached rather
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001273 // than re-queried on each call. This would also allow us to merge the
1274 // underlying lattice values to get more information.
Philip Reames66ab0f02015-06-16 00:49:59 +00001275 if (CxtI) {
1276 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001277 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001278 // on all incoming edges.
1279 BasicBlock *BB = CxtI->getParent();
1280 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1281 if (PI != PE &&
1282 (!isa<Instruction>(V) ||
1283 cast<Instruction>(V)->getParent() != BB)) {
1284 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001285 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001286 // the value of the comparison in this block.
1287 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1288 if (Baseline != Unknown) {
1289 // Check that all remaining incoming values match the first one.
1290 while (++PI != PE) {
1291 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1292 if (Ret != Baseline) break;
1293 }
1294 // If we terminated early, then one of the values didn't match.
1295 if (PI == PE) {
1296 return Baseline;
1297 }
1298 }
1299 }
1300 }
1301 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001302}
1303
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001304void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001305 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001306 if (PImpl) {
1307 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1308 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1309 }
Owen Anderson208636f2010-08-18 18:39:01 +00001310}
1311
1312void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001313 if (PImpl) {
1314 const DataLayout &DL = BB->getModule()->getDataLayout();
1315 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1316 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001317}