blob: abc0ac8ceaff5b47352bbe67515eeec7911e76c6 [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.
Bruno Cardoso Lopes1846ea32015-08-18 16:54:36 +0000318 typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
319 ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000320
Sanjay Patel2a385e22015-01-09 16:47:20 +0000321 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000322 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000323 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000324
Sanjay Patel2a385e22015-01-09 16:47:20 +0000325 /// This tracks, on a per-block basis, the set of values that are
326 /// over-defined at the end of that block. This is required
Owen Anderson6f060af2011-01-05 23:26:22 +0000327 /// for cache updating.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000328 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
329 OverDefinedCacheTy;
330 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000331
Sanjay Patel2a385e22015-01-09 16:47:20 +0000332 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000333 /// don't spend time removing unused blocks from our caches.
334 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
335
Sanjay Patel2a385e22015-01-09 16:47:20 +0000336 /// This stack holds the state of the value solver during a query.
337 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000338 /// recursive value lookup process.
339 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000340
Sanjay Patel2a385e22015-01-09 16:47:20 +0000341 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000342 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
343
Sanjay Patel2a385e22015-01-09 16:47:20 +0000344 /// Push BV onto BlockValueStack unless it's already in there.
345 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000346 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000347 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000348 return false; // It's already in the stack.
349
350 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000351 return true;
352 }
353
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000354 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
355 const DataLayout &DL; ///< A mandatory DataLayout
356 DominatorTree *DT; ///< An optional DT pointer.
357
Owen Anderson118ac802011-01-05 21:15:29 +0000358 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000359
Hans Wennborg45172ac2014-11-25 17:23:05 +0000360 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
361 SeenBlocks.insert(BB);
362 lookup(Val)[BB] = Result;
363 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000364 OverDefinedCache[BB].insert(Val);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000365 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000366
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000367 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000368 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000369 LVILatticeVal &Result,
370 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000371 bool hasBlockValue(Value *Val, BasicBlock *BB);
372
373 // These methods process one work item and may add more. A false value
374 // returned means that the work item was not completely processed and must
375 // be revisited after going through the new items.
376 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000377 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
378 Value *Val, BasicBlock *BB);
379 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
380 PHINode *PN, BasicBlock *BB);
381 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
382 Instruction *BBI, BasicBlock *BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000383 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
384 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000385
386 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000387
Nick Lewycky11678bd2010-12-15 18:57:18 +0000388 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000389 return ValueCache[LVIValueHandle(V, this)];
390 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000391
Chris Lattneraf025d32009-11-15 19:59:49 +0000392 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000393 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000394 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000395 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
396 Instruction *CxtI = nullptr);
397
Sanjay Patel2a385e22015-01-09 16:47:20 +0000398 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000399 /// value for the specified Value* at the specified instruction (generally
400 /// from an assume intrinsic).
401 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000402
Sanjay Patel2a385e22015-01-09 16:47:20 +0000403 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000404 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000405 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
406 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000407
Sanjay Patel2a385e22015-01-09 16:47:20 +0000408 /// This is the update interface to inform the cache that an edge from
409 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000410 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000411
Sanjay Patel2a385e22015-01-09 16:47:20 +0000412 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000413 /// that a block has been deleted.
414 void eraseBlock(BasicBlock *BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000415
Owen Anderson208636f2010-08-18 18:39:01 +0000416 /// clear - Empty the cache.
417 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000418 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000419 ValueCache.clear();
420 OverDefinedCache.clear();
421 }
Hal Finkel7e184492014-09-07 20:29:59 +0000422
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000423 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000424 DominatorTree *DT = nullptr)
425 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000426 };
427} // end anonymous namespace
428
Owen Anderson118ac802011-01-05 21:15:29 +0000429void LVIValueHandle::deleted() {
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000430 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
431 for (auto &I : Parent->OverDefinedCache) {
432 SmallPtrSetImpl<Value *> &ValueSet = I.second;
433 if (ValueSet.count(getValPtr()))
434 ValueSet.erase(getValPtr());
435 if (ValueSet.empty())
436 ToErase.push_back(I.first);
437 }
438 for (auto &BB : ToErase)
439 Parent->OverDefinedCache.erase(BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000440
Owen Anderson7b974a42010-08-11 22:36:04 +0000441 // This erasure deallocates *this, so it MUST happen after we're done
442 // using any and all members of *this.
443 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000444}
445
Owen Anderson208636f2010-08-18 18:39:01 +0000446void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000447 // Shortcut if we have never seen this block.
448 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
449 if (I == SeenBlocks.end())
450 return;
451 SeenBlocks.erase(I);
452
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000453 auto ODI = OverDefinedCache.find(BB);
454 if (ODI != OverDefinedCache.end())
455 OverDefinedCache.erase(ODI);
Owen Anderson208636f2010-08-18 18:39:01 +0000456
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000457 for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
Owen Anderson208636f2010-08-18 18:39:01 +0000458 I->second.erase(BB);
459}
Owen Andersonc1561b82010-07-30 23:59:40 +0000460
Nick Lewycky55a700b2010-12-18 01:00:40 +0000461void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000462 while (!BlockValueStack.empty()) {
463 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000464 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
465
Nuno Lopese6e04902012-06-28 01:16:18 +0000466 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000467 // The work item was completely processed.
468 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
469 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
470
Owen Anderson6f060af2011-01-05 23:26:22 +0000471 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000472 BlockValueSet.erase(e);
473 } else {
474 // More work needs to be done before revisiting.
475 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000476 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000477 }
478}
479
480bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
481 // If already a constant, there is nothing to compute.
482 if (isa<Constant>(Val))
483 return true;
484
Owen Anderson118ac802011-01-05 21:15:29 +0000485 LVIValueHandle ValHandle(Val, this);
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000486 auto I = ValueCache.find(ValHandle);
Benjamin Kramerf29db272012-08-22 15:37:57 +0000487 if (I == ValueCache.end()) return false;
488 return I->second.count(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000489}
490
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000491LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000492 // If already a constant, there is nothing to compute.
493 if (Constant *VC = dyn_cast<Constant>(Val))
494 return LVILatticeVal::get(VC);
495
Benjamin Kramer36647082011-12-03 15:16:45 +0000496 SeenBlocks.insert(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000497 return lookup(Val)[BB];
498}
499
500bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
501 if (isa<Constant>(Val))
502 return true;
503
Hans Wennborg45172ac2014-11-25 17:23:05 +0000504 if (lookup(Val).count(BB)) {
505 // If we have a cached value, use that.
506 DEBUG(dbgs() << " reuse BB '" << BB->getName()
507 << "' val=" << lookup(Val)[BB] << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000508
Hans Wennborg45172ac2014-11-25 17:23:05 +0000509 // Since we're reusing a cached value, we don't need to update the
510 // OverDefinedCache. The cache will have been properly updated whenever the
511 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000512 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000513 }
514
Hans Wennborg45172ac2014-11-25 17:23:05 +0000515 // Hold off inserting this value into the Cache in case we have to return
516 // false and come back later.
517 LVILatticeVal Res;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000518
Chris Lattneraf025d32009-11-15 19:59:49 +0000519 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000520 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000521 if (!solveBlockValueNonLocal(Res, Val, BB))
522 return false;
523 insertResult(Val, BB, Res);
524 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000525 }
Chris Lattner2c708562009-11-15 20:00:52 +0000526
Nick Lewycky55a700b2010-12-18 01:00:40 +0000527 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000528 if (!solveBlockValuePHINode(Res, PN, BB))
529 return false;
530 insertResult(Val, BB, Res);
531 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000532 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000533
Nick Lewycky367f98f2011-01-15 09:16:12 +0000534 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000535 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
536 insertResult(Val, BB, Res);
537 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000538 }
539
Owen Anderson80d19f02010-08-18 21:11:37 +0000540 // We can only analyze the definitions of certain classes of instructions
541 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000542 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000543 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
544 !BBI->getType()->isIntegerTy()) {
545 DEBUG(dbgs() << " compute BB '" << BB->getName()
546 << "' - overdefined because inst def found.\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000547 Res.markOverdefined();
548 insertResult(Val, BB, Res);
549 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000550 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000551
Owen Anderson80d19f02010-08-18 21:11:37 +0000552 // FIXME: We're currently limited to binops with a constant RHS. This should
553 // be improved.
554 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
555 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
556 DEBUG(dbgs() << " compute BB '" << BB->getName()
557 << "' - overdefined because inst def found.\n");
558
Hans Wennborg45172ac2014-11-25 17:23:05 +0000559 Res.markOverdefined();
560 insertResult(Val, BB, Res);
561 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000562 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000563
Hans Wennborg45172ac2014-11-25 17:23:05 +0000564 if (!solveBlockValueConstantRange(Res, BBI, BB))
565 return false;
566 insertResult(Val, BB, Res);
567 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000568}
569
570static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
571 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
572 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000573 GetUnderlyingObject(L->getPointerOperand(),
574 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000575 }
576 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
577 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000578 GetUnderlyingObject(S->getPointerOperand(),
579 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000580 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000581 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
582 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000583
584 // FIXME: check whether it has a valuerange that excludes zero?
585 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
586 if (!Len || Len->isZero()) return false;
587
Eli Friedman7a5fc692011-05-31 20:40:16 +0000588 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000589 if (GetUnderlyingObject(MI->getRawDest(),
590 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000591 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000592 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000593 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000594 if (GetUnderlyingObject(MTI->getRawSource(),
595 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000596 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000597 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000598 return false;
599}
600
Owen Anderson64c2c572010-12-20 18:18:16 +0000601bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
602 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000603 LVILatticeVal Result; // Start Undefined.
604
605 // If this is a pointer, and there's a load from that pointer in this BB,
606 // then we know that the pointer can't be NULL.
607 bool NotNull = false;
608 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000609 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000610 NotNull = true;
611 } else {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000612 const DataLayout &DL = BB->getModule()->getDataLayout();
613 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000614 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
615 // inside InstructionDereferencesPointer either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000616 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000617 for (Instruction &I : *BB) {
618 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000619 NotNull = true;
620 break;
621 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000622 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000623 }
624 }
625 }
626
627 // If this is the entry block, we must be asking about an argument. The
628 // value is overdefined.
629 if (BB == &BB->getParent()->getEntryBlock()) {
630 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
631 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000632 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000633 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
634 } else {
635 Result.markOverdefined();
636 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000637 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000638 return true;
639 }
640
641 // Loop over all of our predecessors, merging what we know from them into
642 // result.
643 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000644 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000645 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000646 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000647 if (EdgesMissing)
648 continue;
649
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000650 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000651
652 // If we hit overdefined, exit early. The BlockVals entry is already set
653 // to overdefined.
654 if (Result.isOverdefined()) {
655 DEBUG(dbgs() << " compute BB '" << BB->getName()
656 << "' - overdefined because of pred.\n");
657 // If we previously determined that this is a pointer that can't be null
658 // then return that rather than giving up entirely.
659 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000660 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000661 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
662 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000663
Owen Anderson64c2c572010-12-20 18:18:16 +0000664 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000665 return true;
666 }
667 }
668 if (EdgesMissing)
669 return false;
670
671 // Return the merged value, which is more precise than 'overdefined'.
672 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000673 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000674 return true;
675}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000676
Owen Anderson64c2c572010-12-20 18:18:16 +0000677bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
678 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000679 LVILatticeVal Result; // Start Undefined.
680
681 // Loop over all of our predecessors, merging what we know from them into
682 // result.
683 bool EdgesMissing = false;
684 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
685 BasicBlock *PhiBB = PN->getIncomingBlock(i);
686 Value *PhiVal = PN->getIncomingValue(i);
687 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000688 // Note that we can provide PN as the context value to getEdgeValue, even
689 // though the results will be cached, because PN is the value being used as
690 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000691 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000692 if (EdgesMissing)
693 continue;
694
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000695 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000696
697 // If we hit overdefined, exit early. The BlockVals entry is already set
698 // to overdefined.
699 if (Result.isOverdefined()) {
700 DEBUG(dbgs() << " compute BB '" << BB->getName()
701 << "' - overdefined because of pred.\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000702
Owen Anderson64c2c572010-12-20 18:18:16 +0000703 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000704 return true;
705 }
706 }
707 if (EdgesMissing)
708 return false;
709
710 // Return the merged value, which is more precise than 'overdefined'.
711 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000712 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000713 return true;
714}
715
Hal Finkel7e184492014-09-07 20:29:59 +0000716static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
717 LVILatticeVal &Result,
718 bool isTrueDest = true);
719
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000720// If we can determine a constant range for the value Val in the context
Hal Finkel7e184492014-09-07 20:29:59 +0000721// provided by the instruction BBI, then merge it into BBLV. If we did find a
722// constant range, return true.
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000723void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
724 LVILatticeVal &BBLV,
725 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000726 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
727 if (!BBI)
728 return;
729
Chandler Carruth66b31302015-01-04 12:03:27 +0000730 for (auto &AssumeVH : AC->assumptions()) {
731 if (!AssumeVH)
732 continue;
733 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000734 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000735 continue;
736
737 Value *C = I->getArgOperand(0);
738 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
739 LVILatticeVal Result;
740 if (getValueFromFromCondition(Val, ICI, Result)) {
741 if (BBLV.isOverdefined())
742 BBLV = Result;
743 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000744 BBLV.mergeIn(Result, DL);
Hal Finkel7e184492014-09-07 20:29:59 +0000745 }
746 }
747 }
748}
749
Owen Anderson64c2c572010-12-20 18:18:16 +0000750bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
751 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000752 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000753 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000754 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000755 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
756 return false;
757 BBLV.markOverdefined();
758 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000759 }
760
Nick Lewycky55a700b2010-12-18 01:00:40 +0000761 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000762 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000763 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000764 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000765 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000766 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000767
Owen Anderson80d19f02010-08-18 21:11:37 +0000768 ConstantRange LHSRange = LHSVal.getConstantRange();
769 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000770 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000771 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000772 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
773 RHSRange = ConstantRange(RHS->getValue());
774 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000775 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000776 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000777 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000778 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000779
Owen Anderson80d19f02010-08-18 21:11:37 +0000780 // NOTE: We're currently limited by the set of operations that ConstantRange
781 // can evaluate symbolically. Enhancing that set will allows us to analyze
782 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000783 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000784 switch (BBI->getOpcode()) {
785 case Instruction::Add:
786 Result.markConstantRange(LHSRange.add(RHSRange));
787 break;
788 case Instruction::Sub:
789 Result.markConstantRange(LHSRange.sub(RHSRange));
790 break;
791 case Instruction::Mul:
792 Result.markConstantRange(LHSRange.multiply(RHSRange));
793 break;
794 case Instruction::UDiv:
795 Result.markConstantRange(LHSRange.udiv(RHSRange));
796 break;
797 case Instruction::Shl:
798 Result.markConstantRange(LHSRange.shl(RHSRange));
799 break;
800 case Instruction::LShr:
801 Result.markConstantRange(LHSRange.lshr(RHSRange));
802 break;
803 case Instruction::Trunc:
804 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
805 break;
806 case Instruction::SExt:
807 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
808 break;
809 case Instruction::ZExt:
810 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
811 break;
812 case Instruction::BitCast:
813 Result.markConstantRange(LHSRange);
814 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +0000815 case Instruction::And:
816 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
817 break;
818 case Instruction::Or:
819 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
820 break;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000821
Owen Anderson80d19f02010-08-18 21:11:37 +0000822 // Unhandled instructions are overdefined.
823 default:
824 DEBUG(dbgs() << " compute BB '" << BB->getName()
825 << "' - overdefined because inst def found.\n");
826 Result.markOverdefined();
827 break;
828 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000829
Owen Anderson64c2c572010-12-20 18:18:16 +0000830 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000831 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +0000832}
833
Hal Finkel7e184492014-09-07 20:29:59 +0000834bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
835 LVILatticeVal &Result, bool isTrueDest) {
836 if (ICI && isa<Constant>(ICI->getOperand(1))) {
837 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
838 // We know that V has the RHS constant if this is a true SETEQ or
839 // false SETNE.
840 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
841 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
842 else
843 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
844 return true;
845 }
846
847 // Recognize the range checking idiom that InstCombine produces.
848 // (X-C1) u< C2 --> [C1, C1+C2)
849 ConstantInt *NegOffset = nullptr;
850 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
851 match(ICI->getOperand(0), m_Add(m_Specific(Val),
852 m_ConstantInt(NegOffset)));
853
854 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
855 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Sanjoy Das7182d362015-03-18 00:41:24 +0000856 // Calculate the range of values that are allowed by the comparison
Hal Finkel7e184492014-09-07 20:29:59 +0000857 ConstantRange CmpRange(CI->getValue());
858 ConstantRange TrueValues =
Sanjoy Das7182d362015-03-18 00:41:24 +0000859 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
Hal Finkel7e184492014-09-07 20:29:59 +0000860
861 if (NegOffset) // Apply the offset from above.
862 TrueValues = TrueValues.subtract(NegOffset->getValue());
863
864 // If we're interested in the false dest, invert the condition.
865 if (!isTrueDest) TrueValues = TrueValues.inverse();
866
867 Result = LVILatticeVal::getRange(TrueValues);
868 return true;
869 }
870 }
871
872 return false;
873}
874
Nuno Lopese6e04902012-06-28 01:16:18 +0000875/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
876/// Val is not constrained on the edge.
877static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
878 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000879 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +0000880 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +0000881 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
882 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +0000883 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +0000884 if (BI->isConditional() &&
885 BI->getSuccessor(0) != BI->getSuccessor(1)) {
886 bool isTrueDest = BI->getSuccessor(0) == BBTo;
887 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
888 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000889
Chris Lattner19019ea2009-11-11 22:48:44 +0000890 // If V is the condition of the branch itself, then we know exactly what
891 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000892 if (BI->getCondition() == Val) {
893 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +0000894 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000895 return true;
896 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000897
Chris Lattner19019ea2009-11-11 22:48:44 +0000898 // If the condition of the branch is an equality comparison, we may be
899 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +0000900 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
901 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
902 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000903 }
904 }
Chris Lattner77358782009-11-15 20:02:12 +0000905
906 // If the edge was formed by a switch on the value, then we may know exactly
907 // what it is.
908 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000909 if (SI->getCondition() != Val)
910 return false;
911
912 bool DefaultCase = SI->getDefaultDest() == BBTo;
913 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
914 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
915
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000916 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000917 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +0000918 if (DefaultCase) {
919 // It is possible that the default destination is the destination of
920 // some cases. There is no need to perform difference for those cases.
921 if (i.getCaseSuccessor() != BBTo)
922 EdgesVals = EdgesVals.difference(EdgeVal);
923 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +0000924 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +0000925 }
Nuno Lopes8650fb82012-06-28 16:13:37 +0000926 Result = LVILatticeVal::getRange(EdgesVals);
927 return true;
Chris Lattner77358782009-11-15 20:02:12 +0000928 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000929 return false;
930}
931
Sanjay Patel938e2792015-01-09 16:35:37 +0000932/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
933/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +0000934bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +0000935 BasicBlock *BBTo, LVILatticeVal &Result,
936 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +0000937 // If already a constant, there is nothing to compute.
938 if (Constant *VC = dyn_cast<Constant>(Val)) {
939 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000940 return true;
941 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000942
943 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
944 if (!Result.isConstantRange() ||
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000945 Result.getConstantRange().getSingleElement())
Nuno Lopese6e04902012-06-28 01:16:18 +0000946 return true;
947
948 // FIXME: this check should be moved to the beginning of the function when
949 // LVI better supports recursive values. Even for the single value case, we
950 // can intersect to detect dead code (an empty range).
951 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000952 if (pushBlockValue(std::make_pair(BBFrom, Val)))
953 return false;
954 Result.markOverdefined();
955 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000956 }
957
958 // Try to intersect ranges of the BB and the constraint on the edge.
959 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000960 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000961 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
962 // and caching, below.
Hal Finkel7e184492014-09-07 20:29:59 +0000963 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000964 if (!InBlock.isConstantRange())
965 return true;
966
967 ConstantRange Range =
968 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
969 Result = LVILatticeVal::getRange(Range);
970 return true;
971 }
972
973 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000974 if (pushBlockValue(std::make_pair(BBFrom, Val)))
975 return false;
976 Result.markOverdefined();
977 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000978 }
979
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000980 // If we couldn't compute the value on the edge, use the value from the BB.
Nuno Lopese6e04902012-06-28 01:16:18 +0000981 Result = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000982 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000983 // We can use the context instruction (generically the ultimate instruction
984 // the calling pass is trying to simplify) here, even though the result of
985 // this function is generally cached when called from the solve* functions
986 // (and that cached result might be used with queries using a different
987 // context instruction), because when this function is called from the solve*
988 // functions, the context instruction is not provided. When called from
989 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
990 // but then the result is not cached.
Hal Finkel7e184492014-09-07 20:29:59 +0000991 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000992 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000993}
994
Hal Finkel7e184492014-09-07 20:29:59 +0000995LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
996 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +0000997 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +0000998 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000999
Hans Wennborg45172ac2014-11-25 17:23:05 +00001000 assert(BlockValueStack.empty() && BlockValueSet.empty());
1001 pushBlockValue(std::make_pair(BB, V));
1002
Nick Lewycky55a700b2010-12-18 01:00:40 +00001003 solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001004 LVILatticeVal Result = getBlockValue(V, BB);
Hal Finkel7e184492014-09-07 20:29:59 +00001005 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1006
1007 DEBUG(dbgs() << " Result = " << Result << "\n");
1008 return Result;
1009}
1010
1011LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1012 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1013 << CxtI->getName() << "'\n");
1014
1015 LVILatticeVal Result;
1016 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001017
David Greene37e98092009-12-23 20:43:58 +00001018 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001019 return Result;
1020}
Chris Lattner19019ea2009-11-11 22:48:44 +00001021
Chris Lattneraf025d32009-11-15 19:59:49 +00001022LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001023getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1024 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001025 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001026 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001027
Nick Lewycky55a700b2010-12-18 01:00:40 +00001028 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001029 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001030 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001031 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001032 (void)WasFastQuery;
1033 assert(WasFastQuery && "More work to do after problem solved?");
1034 }
1035
David Greene37e98092009-12-23 20:43:58 +00001036 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001037 return Result;
1038}
1039
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001040void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1041 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001042 // When an edge in the graph has been threaded, values that we could not
1043 // determine a value for before (i.e. were marked overdefined) may be
1044 // possible to solve now. We do NOT try to proactively update these values.
1045 // Instead, we clear their entries from the cache, and allow lazy updating to
1046 // recompute them when needed.
1047
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001048 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001049 // for all values that were marked overdefined in OldSucc, and for those same
1050 // values in any successor of OldSucc (except NewSucc) in which they were
1051 // also marked overdefined.
1052 std::vector<BasicBlock*> worklist;
1053 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001054
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001055 auto I = OverDefinedCache.find(OldSucc);
1056 if (I == OverDefinedCache.end())
1057 return; // Nothing to process here.
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001058 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001059
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001060 // Use a worklist to perform a depth-first search of OldSucc's successors.
1061 // NOTE: We do not need a visited list since any blocks we have already
1062 // visited will have had their overdefined markers cleared already, and we
1063 // thus won't loop to their successors.
1064 while (!worklist.empty()) {
1065 BasicBlock *ToUpdate = worklist.back();
1066 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001067
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001068 // Skip blocks only accessible through NewSucc.
1069 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001070
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001071 bool changed = false;
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001072 for (Value *V : ValsToClear) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001073 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001074 auto OI = OverDefinedCache.find(ToUpdate);
1075 if (OI == OverDefinedCache.end())
1076 continue;
1077 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1078 if (!ValueSet.count(V))
1079 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001080
Owen Andersonaac5a722010-07-27 23:58:11 +00001081 // Remove it from the caches.
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001082 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
Owen Andersonaac5a722010-07-27 23:58:11 +00001083 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001084
Owen Andersonaac5a722010-07-27 23:58:11 +00001085 assert(CI != Entry.end() && "Couldn't find entry to update?");
1086 Entry.erase(CI);
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001087 ValueSet.erase(V);
1088 if (ValueSet.empty())
1089 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001090
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001091 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001092 // blocks successors too.
1093 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001094 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001095
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001096 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001097
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001098 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1099 }
1100}
1101
Chris Lattneraf025d32009-11-15 19:59:49 +00001102//===----------------------------------------------------------------------===//
1103// LazyValueInfo Impl
1104//===----------------------------------------------------------------------===//
1105
Sanjay Patel2a385e22015-01-09 16:47:20 +00001106/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001107static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001108 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001109 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001110 if (!PImpl) {
1111 assert(DL && "getCache() called with a null DataLayout");
1112 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1113 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001114 return *static_cast<LazyValueInfoCache*>(PImpl);
1115}
1116
Owen Anderson208636f2010-08-18 18:39:01 +00001117bool LazyValueInfo::runOnFunction(Function &F) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001118 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001119 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001120
1121 DominatorTreeWrapperPass *DTWP =
1122 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1123 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001124
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001125 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001126
Hal Finkel7e184492014-09-07 20:29:59 +00001127 if (PImpl)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001128 getCache(PImpl, AC, &DL, DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001129
Owen Anderson208636f2010-08-18 18:39:01 +00001130 // Fully lazy.
1131 return false;
1132}
1133
Chad Rosier43a33062011-12-02 01:26:24 +00001134void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1135 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001136 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001137 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001138}
1139
Chris Lattneraf025d32009-11-15 19:59:49 +00001140void LazyValueInfo::releaseMemory() {
1141 // If the cache was allocated, free it.
1142 if (PImpl) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001143 delete &getCache(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001144 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001145 }
1146}
1147
Hal Finkel7e184492014-09-07 20:29:59 +00001148Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1149 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001150 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001151 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001152 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001153
Chris Lattner19019ea2009-11-11 22:48:44 +00001154 if (Result.isConstant())
1155 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001156 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001157 ConstantRange CR = Result.getConstantRange();
1158 if (const APInt *SingleVal = CR.getSingleElement())
1159 return ConstantInt::get(V->getContext(), *SingleVal);
1160 }
Craig Topper9f008862014-04-15 04:59:12 +00001161 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001162}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001163
Sanjay Patel2a385e22015-01-09 16:47:20 +00001164/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001165/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001166Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001167 BasicBlock *ToBB,
1168 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001169 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001170 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001171 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001172
Chris Lattnerd5e25432009-11-12 01:29:10 +00001173 if (Result.isConstant())
1174 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001175 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001176 ConstantRange CR = Result.getConstantRange();
1177 if (const APInt *SingleVal = CR.getSingleElement())
1178 return ConstantInt::get(V->getContext(), *SingleVal);
1179 }
Craig Topper9f008862014-04-15 04:59:12 +00001180 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001181}
1182
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001183static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1184 LVILatticeVal &Result,
1185 const DataLayout &DL,
1186 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001187
Chris Lattner565ee2f2009-11-12 04:36:58 +00001188 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001189 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001190 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001191 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001192 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001193 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001194 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1195 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001196 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001197
Owen Anderson185fe002010-08-10 20:03:09 +00001198 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001199 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001200 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001201
Owen Anderson185fe002010-08-10 20:03:09 +00001202 ConstantRange CR = Result.getConstantRange();
1203 if (Pred == ICmpInst::ICMP_EQ) {
1204 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001205 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001206
Owen Anderson185fe002010-08-10 20:03:09 +00001207 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001208 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001209 } else if (Pred == ICmpInst::ICMP_NE) {
1210 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001211 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001212
Owen Anderson185fe002010-08-10 20:03:09 +00001213 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001214 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001215 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001216
Owen Anderson185fe002010-08-10 20:03:09 +00001217 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001218 ConstantRange TrueValues =
1219 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1220 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001221 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001222 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001223 return LazyValueInfo::False;
1224 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001225 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001226
Chris Lattneraf025d32009-11-15 19:59:49 +00001227 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001228 // If this is an equality comparison, we can try to fold it knowing that
1229 // "V != C1".
1230 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001231 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001232 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001233 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001234 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001235 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001236 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001237 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001238 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001239 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001240 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001241 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001242 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001243 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001244 }
Hal Finkel7e184492014-09-07 20:29:59 +00001245 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001246 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001247
Hal Finkel7e184492014-09-07 20:29:59 +00001248 return LazyValueInfo::Unknown;
1249}
1250
Sanjay Patel2a385e22015-01-09 16:47:20 +00001251/// Determine whether the specified value comparison with a constant is known to
1252/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001253LazyValueInfo::Tristate
1254LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1255 BasicBlock *FromBB, BasicBlock *ToBB,
1256 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001257 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001258 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001259 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001260
1261 return getPredicateResult(Pred, C, Result, DL, TLI);
1262}
1263
1264LazyValueInfo::Tristate
1265LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1266 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001267 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1268 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001269 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1270 if (Ret != Unknown)
1271 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001272
Philip Reames66ab0f02015-06-16 00:49:59 +00001273 // TODO: Move this logic inside getValueAt so that it can be cached rather
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001274 // than re-queried on each call. This would also allow us to merge the
1275 // underlying lattice values to get more information.
Philip Reames66ab0f02015-06-16 00:49:59 +00001276 if (CxtI) {
1277 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001278 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001279 // on all incoming edges.
1280 BasicBlock *BB = CxtI->getParent();
1281 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1282 if (PI != PE &&
1283 (!isa<Instruction>(V) ||
1284 cast<Instruction>(V)->getParent() != BB)) {
1285 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001286 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001287 // the value of the comparison in this block.
1288 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1289 if (Baseline != Unknown) {
1290 // Check that all remaining incoming values match the first one.
1291 while (++PI != PE) {
1292 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1293 if (Ret != Baseline) break;
1294 }
1295 // If we terminated early, then one of the values didn't match.
1296 if (PI == PE) {
1297 return Baseline;
1298 }
1299 }
1300 }
1301 }
1302 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001303}
1304
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001305void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001306 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001307 if (PImpl) {
1308 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1309 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1310 }
Owen Anderson208636f2010-08-18 18:39:01 +00001311}
1312
1313void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001314 if (PImpl) {
1315 const DataLayout &DL = BB->getModule()->getDataLayout();
1316 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1317 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001318}