blob: 74267e045ae7f1c9dd2840cea8e2ea8bd9a29add [file] [log] [blame]
Chris Lattner10f2d132009-11-11 00:22:30 +00001//===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
2//
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
Chris Lattnerb8c124c2009-11-12 01:22:16 +000015#define DEBUG_TYPE "lazy-value-info"
Chris Lattner10f2d132009-11-11 00:22:30 +000016#include "llvm/Analysis/LazyValueInfo.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000017#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Target/TargetData.h"
Chris Lattner16976522009-11-11 22:48:44 +000021#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000022#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000023#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000024#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000025#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000026#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000027#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000028#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000029#include <map>
30#include <set>
Chris Lattner10f2d132009-11-11 00:22:30 +000031using namespace llvm;
32
33char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000034INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
35 "Lazy Value Information Analysis", false, true);
Chris Lattner10f2d132009-11-11 00:22:30 +000036
37namespace llvm {
38 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
39}
40
Chris Lattnercc4d3b22009-11-11 02:08:33 +000041
42//===----------------------------------------------------------------------===//
43// LVILatticeVal
44//===----------------------------------------------------------------------===//
45
46/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
47/// value.
48///
49/// FIXME: This is basically just for bringup, this can be made a lot more rich
50/// in the future.
51///
52namespace {
53class LVILatticeVal {
54 enum LatticeValueTy {
55 /// undefined - This LLVM Value has no known value yet.
56 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000057
Chris Lattnercc4d3b22009-11-11 02:08:33 +000058 /// constant - This LLVM Value has a specific constant value.
59 constant,
Chris Lattnerb52675b2009-11-12 04:36:58 +000060 /// notconstant - This LLVM value is known to not have the specified value.
61 notconstant,
62
Owen Anderson5be2e782010-08-05 22:59:19 +000063 /// constantrange
64 constantrange,
65
Chris Lattnercc4d3b22009-11-11 02:08:33 +000066 /// overdefined - This instruction is not known to be constant, and we know
67 /// it has a value.
68 overdefined
69 };
70
71 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000072 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000073 LatticeValueTy Tag;
74 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000075 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000076
77public:
Owen Anderson5be2e782010-08-05 22:59:19 +000078 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000079
Chris Lattner16976522009-11-11 22:48:44 +000080 static LVILatticeVal get(Constant *C) {
81 LVILatticeVal Res;
Owen Anderson9f014062010-08-10 20:03:09 +000082 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
83 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
84 else if (!isa<UndefValue>(C))
85 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000086 return Res;
87 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000088 static LVILatticeVal getNot(Constant *C) {
89 LVILatticeVal Res;
Owen Anderson9f014062010-08-10 20:03:09 +000090 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
91 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
92 else
93 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000094 return Res;
95 }
Owen Anderson625051b2010-08-10 23:20:01 +000096 static LVILatticeVal getRange(ConstantRange CR) {
97 LVILatticeVal Res;
98 Res.markConstantRange(CR);
99 return Res;
100 }
Chris Lattner16976522009-11-11 22:48:44 +0000101
Owen Anderson5be2e782010-08-05 22:59:19 +0000102 bool isUndefined() const { return Tag == undefined; }
103 bool isConstant() const { return Tag == constant; }
104 bool isNotConstant() const { return Tag == notconstant; }
105 bool isConstantRange() const { return Tag == constantrange; }
106 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000107
108 Constant *getConstant() const {
109 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000110 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000111 }
112
Chris Lattnerb52675b2009-11-12 04:36:58 +0000113 Constant *getNotConstant() const {
114 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000115 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000116 }
117
Owen Anderson5be2e782010-08-05 22:59:19 +0000118 ConstantRange getConstantRange() const {
119 assert(isConstantRange() &&
120 "Cannot get the constant-range of a non-constant-range!");
121 return Range;
122 }
123
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000124 /// markOverdefined - Return true if this is a change in status.
125 bool markOverdefined() {
126 if (isOverdefined())
127 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000128 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000129 return true;
130 }
131
132 /// markConstant - Return true if this is a change in status.
133 bool markConstant(Constant *V) {
134 if (isConstant()) {
135 assert(getConstant() == V && "Marking constant with different value");
136 return false;
137 }
138
139 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000140 Tag = constant;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000141 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000142 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000143 return true;
144 }
145
Chris Lattnerb52675b2009-11-12 04:36:58 +0000146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
148 if (isNotConstant()) {
149 assert(getNotConstant() == V && "Marking !constant with different value");
150 return false;
151 }
152
153 if (isConstant())
154 assert(getConstant() != V && "Marking not constant with different value");
155 else
156 assert(isUndefined());
157
Owen Andersondb78d732010-08-05 22:10:46 +0000158 Tag = notconstant;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000159 assert(V && "Marking constant with NULL");
Owen Andersondb78d732010-08-05 22:10:46 +0000160 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000161 return true;
162 }
163
Owen Anderson5be2e782010-08-05 22:59:19 +0000164 /// markConstantRange - Return true if this is a change in status.
165 bool markConstantRange(const ConstantRange NewR) {
166 if (isConstantRange()) {
167 if (NewR.isEmptySet())
168 return markOverdefined();
169
Owen Anderson5be2e782010-08-05 22:59:19 +0000170 bool changed = Range == NewR;
171 Range = NewR;
172 return changed;
173 }
174
175 assert(isUndefined());
176 if (NewR.isEmptySet())
177 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000178
179 Tag = constantrange;
180 Range = NewR;
181 return true;
182 }
183
Chris Lattner16976522009-11-11 22:48:44 +0000184 /// mergeIn - Merge the specified lattice value into this one, updating this
185 /// one and returning true if anything changed.
186 bool mergeIn(const LVILatticeVal &RHS) {
187 if (RHS.isUndefined() || isOverdefined()) return false;
188 if (RHS.isOverdefined()) return markOverdefined();
189
Chris Lattnerb52675b2009-11-12 04:36:58 +0000190 if (RHS.isNotConstant()) {
191 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000192 if (getNotConstant() != RHS.getNotConstant() ||
193 isa<ConstantExpr>(getNotConstant()) ||
194 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000195 return markOverdefined();
196 return false;
Owen Anderson39295322010-08-30 17:03:45 +0000197 } else if (isConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000198 if (getConstant() == RHS.getNotConstant() ||
199 isa<ConstantExpr>(RHS.getNotConstant()) ||
200 isa<ConstantExpr>(getConstant()))
201 return markOverdefined();
202 return markNotConstant(RHS.getNotConstant());
Owen Anderson39295322010-08-30 17:03:45 +0000203 } else if (isConstantRange()) {
204 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000205 }
206
207 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000208 return markNotConstant(RHS.getNotConstant());
209 }
210
Owen Anderson5be2e782010-08-05 22:59:19 +0000211 if (RHS.isConstantRange()) {
212 if (isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000213 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
214 if (NewR.isFullSet())
Owen Anderson5be2e782010-08-05 22:59:19 +0000215 return markOverdefined();
216 else
217 return markConstantRange(NewR);
Owen Anderson59b06dc2010-08-24 07:55:44 +0000218 } else if (!isUndefined()) {
219 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000220 }
221
222 assert(isUndefined() && "Unexpected lattice");
223 return markConstantRange(RHS.getConstantRange());
224 }
225
Chris Lattnerf496e792009-11-12 04:57:13 +0000226 // RHS must be a constant, we must be undef, constant, or notconstant.
Owen Anderson5be2e782010-08-05 22:59:19 +0000227 assert(!isConstantRange() &&
228 "Constant and ConstantRange cannot be merged.");
229
Chris Lattnerf496e792009-11-12 04:57:13 +0000230 if (isUndefined())
231 return markConstant(RHS.getConstant());
232
233 if (isConstant()) {
234 if (getConstant() != RHS.getConstant())
235 return markOverdefined();
236 return false;
237 }
238
239 // If we are known "!=4" and RHS is "==5", stay at "!=4".
240 if (getNotConstant() == RHS.getConstant() ||
241 isa<ConstantExpr>(getNotConstant()) ||
242 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000243 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000244 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000245 }
246
247};
248
249} // end anonymous namespace.
250
Chris Lattner16976522009-11-11 22:48:44 +0000251namespace llvm {
252raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
253 if (Val.isUndefined())
254 return OS << "undefined";
255 if (Val.isOverdefined())
256 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000257
258 if (Val.isNotConstant())
259 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000260 else if (Val.isConstantRange())
261 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
262 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000263 return OS << "constant<" << *Val.getConstant() << '>';
264}
265}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000266
267//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000268// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000269//===----------------------------------------------------------------------===//
270
Chris Lattner2c5adf82009-11-15 19:59:49 +0000271namespace {
272 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
273 /// maintains information about queries across the clients' queries.
274 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000275 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000276 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
277 /// specified basic block for a Value* that depends on context.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000278 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000279
280 /// ValueCacheEntryTy - This is all of the cached block information for
281 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
282 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000283 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000284
Owen Anderson81881bc2010-07-30 20:56:07 +0000285 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000286 /// LVIValueHandle - A callback value handle update the cache when
287 /// values are erased.
288 struct LVIValueHandle : public CallbackVH {
289 LazyValueInfoCache *Parent;
290
291 LVIValueHandle(Value *V, LazyValueInfoCache *P)
292 : CallbackVH(V), Parent(P) { }
293
294 void deleted();
295 void allUsesReplacedWith(Value* V) {
296 deleted();
297 }
Owen Anderson7f9cb742010-07-30 23:59:40 +0000298 };
299
Chris Lattner2c5adf82009-11-15 19:59:49 +0000300 /// ValueCache - This is all of the cached information for all values,
301 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000302 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000303
304 /// OverDefinedCache - This tracks, on a per-block basis, the set of
305 /// values that are over-defined at the end of that block. This is required
306 /// for cache updating.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000307 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000308
Chris Lattner2c5adf82009-11-15 19:59:49 +0000309 public:
310
311 /// getValueInBlock - This is the query interface to determine the lattice
312 /// value for the specified Value* at the end of the specified block.
313 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
314
315 /// getValueOnEdge - This is the query interface to determine the lattice
316 /// value for the specified Value* that is true on the specified edge.
317 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000318
319 /// threadEdge - This is the update interface to inform the cache that an
320 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
321 /// NewSucc.
322 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000323
324 /// eraseBlock - This is part of the update interface to inform the cache
325 /// that a block has been deleted.
326 void eraseBlock(BasicBlock *BB);
327
328 /// clear - Empty the cache.
329 void clear() {
330 ValueCache.clear();
331 OverDefinedCache.clear();
332 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000333 };
334} // end anonymous namespace
335
Owen Anderson81881bc2010-07-30 20:56:07 +0000336//===----------------------------------------------------------------------===//
337// LVIQuery Impl
338//===----------------------------------------------------------------------===//
339
340namespace {
341 /// LVIQuery - This is a transient object that exists while a query is
342 /// being performed.
343 ///
344 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
345 /// reallocation of the densemap on every query.
346 class LVIQuery {
347 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
348 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
349
350 /// This is the current value being queried for.
351 Value *Val;
352
Owen Anderson7f9cb742010-07-30 23:59:40 +0000353 /// This is a pointer to the owning cache, for recursive queries.
354 LazyValueInfoCache &Parent;
355
Owen Anderson81881bc2010-07-30 20:56:07 +0000356 /// This is all of the cached information about this value.
357 ValueCacheEntryTy &Cache;
358
359 /// This tracks, for each block, what values are overdefined.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000360 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000361
362 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
363 /// added to cache but that are not in sorted order.
364 DenseSet<BasicBlock*> NewBlockInfo;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000365
Owen Anderson81881bc2010-07-30 20:56:07 +0000366 public:
367
Owen Anderson7f9cb742010-07-30 23:59:40 +0000368 LVIQuery(Value *V, LazyValueInfoCache &P,
369 ValueCacheEntryTy &VC,
Owen Anderson00ac77e2010-08-18 18:39:01 +0000370 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
Owen Anderson7f9cb742010-07-30 23:59:40 +0000371 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000372 }
373
374 ~LVIQuery() {
375 // When the query is done, insert the newly discovered facts into the
376 // cache in sorted order.
377 if (NewBlockInfo.empty()) return;
378
379 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
380 E = NewBlockInfo.end(); I != E; ++I) {
381 if (Cache[*I].isOverdefined())
382 OverDefinedCache.insert(std::make_pair(*I, Val));
383 }
384 }
385
386 LVILatticeVal getBlockValue(BasicBlock *BB);
387 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
388
389 private:
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000390 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
Owen Anderson81881bc2010-07-30 20:56:07 +0000391 };
392} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000393
Owen Anderson7f9cb742010-07-30 23:59:40 +0000394void LazyValueInfoCache::LVIValueHandle::deleted() {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000395 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000396 I = Parent->OverDefinedCache.begin(),
397 E = Parent->OverDefinedCache.end();
398 I != E; ) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000399 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000400 ++I;
401 if (tmp->second == getValPtr())
402 Parent->OverDefinedCache.erase(tmp);
403 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000404
405 // This erasure deallocates *this, so it MUST happen after we're done
406 // using any and all members of *this.
407 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000408}
409
Owen Anderson00ac77e2010-08-18 18:39:01 +0000410void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
411 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
412 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
413 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
414 ++I;
415 if (tmp->first == BB)
416 OverDefinedCache.erase(tmp);
417 }
418
419 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
420 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
421 I->second.erase(BB);
422}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000423
Chris Lattnere5642812009-11-15 20:00:52 +0000424/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000425/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000426LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000427 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000428 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000429}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000430
Owen Anderson81881bc2010-07-30 20:56:07 +0000431LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000432 // See if we already have a value for this block.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000433 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000434
435 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000436 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000437 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000438 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000439 }
440
Chris Lattner2c5adf82009-11-15 19:59:49 +0000441 // Otherwise, this is the first time we're seeing this block. Reset the
442 // lattice value to overdefined, so that cycles will terminate and be
443 // conservatively correct.
444 BBLV.markOverdefined();
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000445 Cache[BB] = BBLV;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000446
Chris Lattner2c5adf82009-11-15 19:59:49 +0000447 Instruction *BBI = dyn_cast<Instruction>(Val);
448 if (BBI == 0 || BBI->getParent() != BB) {
449 LVILatticeVal Result; // Start Undefined.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000450
Owen Andersonc8ef7502010-08-24 20:47:29 +0000451 // If this is a pointer, and there's a load from that pointer in this BB,
452 // then we know that the pointer can't be NULL.
Owen Anderson1593dd62010-09-03 19:08:37 +0000453 bool NotNull = false;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000454 if (Val->getType()->isPointerTy()) {
Owen Anderson6cd20752010-08-25 01:16:47 +0000455 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
456 LoadInst *L = dyn_cast<LoadInst>(BI);
457 if (L && L->getPointerAddressSpace() == 0 &&
458 L->getPointerOperand()->getUnderlyingObject() ==
459 Val->getUnderlyingObject()) {
Owen Anderson1593dd62010-09-03 19:08:37 +0000460 NotNull = true;
461 break;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000462 }
463 }
464 }
465
466 unsigned NumPreds = 0;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000467 // Loop over all of our predecessors, merging what we know from them into
468 // result.
469 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000470 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000471
472 // If we hit overdefined, exit early. The BlockVals entry is already set
473 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000474 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000475 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000476 << "' - overdefined because of pred.\n");
Owen Anderson1593dd62010-09-03 19:08:37 +0000477 // If we previously determined that this is a pointer that can't be null
478 // then return that rather than giving up entirely.
479 if (NotNull) {
480 const PointerType *PTy = cast<PointerType>(Val->getType());
481 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
482 }
483
Chris Lattner2c5adf82009-11-15 19:59:49 +0000484 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000485 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000486 ++NumPreds;
487 }
488
Owen Anderson1593dd62010-09-03 19:08:37 +0000489
Chris Lattner2c5adf82009-11-15 19:59:49 +0000490 // If this is the entry block, we must be asking about an argument. The
491 // value is overdefined.
492 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
493 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
494 Result.markOverdefined();
495 return Result;
496 }
497
498 // Return the merged value, which is more precise than 'overdefined'.
499 assert(!Result.isOverdefined());
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000500 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000501 }
502
503 // If this value is defined by an instruction in this block, we have to
504 // process it here somehow or return overdefined.
505 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000506 LVILatticeVal Result; // Start Undefined.
507
508 // Loop over all of our predecessors, merging what we know from them into
509 // result.
510 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
511 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
512 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
513
514 // If we hit overdefined, exit early. The BlockVals entry is already set
515 // to overdefined.
516 if (Result.isOverdefined()) {
517 DEBUG(dbgs() << " compute BB '" << BB->getName()
518 << "' - overdefined because of pred.\n");
519 return Result;
520 }
521 }
522
523 // Return the merged value, which is more precise than 'overdefined'.
524 assert(!Result.isOverdefined());
Owen Anderson00ac77e2010-08-18 18:39:01 +0000525 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000526 }
Chris Lattnere5642812009-11-15 20:00:52 +0000527
Owen Andersonb81fd622010-08-18 21:11:37 +0000528 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
529
530 // We can only analyze the definitions of certain classes of instructions
531 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000532 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000533 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
534 !BBI->getType()->isIntegerTy()) {
535 DEBUG(dbgs() << " compute BB '" << BB->getName()
536 << "' - overdefined because inst def found.\n");
537 Result.markOverdefined();
538 return Result;
539 }
540
541 // FIXME: We're currently limited to binops with a constant RHS. This should
542 // be improved.
543 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
544 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
545 DEBUG(dbgs() << " compute BB '" << BB->getName()
546 << "' - overdefined because inst def found.\n");
547
548 Result.markOverdefined();
549 return Result;
550 }
551
552 // Figure out the range of the LHS. If that fails, bail.
553 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
554 if (!LHSVal.isConstantRange()) {
555 Result.markOverdefined();
556 return Result;
557 }
558
559 ConstantInt *RHS = 0;
560 ConstantRange LHSRange = LHSVal.getConstantRange();
561 ConstantRange RHSRange(1);
562 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
563 if (isa<BinaryOperator>(BBI)) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000564 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
565 if (!RHS) {
566 Result.markOverdefined();
567 return Result;
568 }
569
Owen Andersonb81fd622010-08-18 21:11:37 +0000570 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
571 }
572
573 // NOTE: We're currently limited by the set of operations that ConstantRange
574 // can evaluate symbolically. Enhancing that set will allows us to analyze
575 // more definitions.
576 switch (BBI->getOpcode()) {
577 case Instruction::Add:
578 Result.markConstantRange(LHSRange.add(RHSRange));
579 break;
580 case Instruction::Sub:
581 Result.markConstantRange(LHSRange.sub(RHSRange));
582 break;
583 case Instruction::Mul:
584 Result.markConstantRange(LHSRange.multiply(RHSRange));
585 break;
586 case Instruction::UDiv:
587 Result.markConstantRange(LHSRange.udiv(RHSRange));
588 break;
589 case Instruction::Shl:
590 Result.markConstantRange(LHSRange.shl(RHSRange));
591 break;
592 case Instruction::LShr:
593 Result.markConstantRange(LHSRange.lshr(RHSRange));
594 break;
595 case Instruction::Trunc:
596 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
597 break;
598 case Instruction::SExt:
599 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
600 break;
601 case Instruction::ZExt:
602 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
603 break;
604 case Instruction::BitCast:
605 Result.markConstantRange(LHSRange);
606 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000607 case Instruction::And:
608 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
609 break;
610 case Instruction::Or:
611 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
612 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000613
614 // Unhandled instructions are overdefined.
615 default:
616 DEBUG(dbgs() << " compute BB '" << BB->getName()
617 << "' - overdefined because inst def found.\n");
618 Result.markOverdefined();
619 break;
620 }
621
622 return Cache[BB] = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000623}
624
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000625
Chris Lattner800c47e2009-11-15 20:02:12 +0000626/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000627LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000628 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
629 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000630 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
631 // If this is a conditional branch and only one successor goes to BBTo, then
632 // we maybe able to infer something from the condition.
633 if (BI->isConditional() &&
634 BI->getSuccessor(0) != BI->getSuccessor(1)) {
635 bool isTrueDest = BI->getSuccessor(0) == BBTo;
636 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
637 "BBTo isn't a successor of BBFrom");
638
639 // If V is the condition of the branch itself, then we know exactly what
640 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000641 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000642 return LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000643 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000644
645 // If the condition of the branch is an equality comparison, we may be
646 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000647 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
648 if (ICI && ICI->getOperand(0) == Val &&
649 isa<Constant>(ICI->getOperand(1))) {
650 if (ICI->isEquality()) {
651 // We know that V has the RHS constant if this is a true SETEQ or
652 // false SETNE.
653 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
654 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
655 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
Chris Lattner16976522009-11-11 22:48:44 +0000656 }
Owen Anderson2d0f2472010-08-11 04:24:25 +0000657
658 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
659 // Calculate the range of values that would satisfy the comparison.
660 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
661 ConstantRange TrueValues =
662 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
663
664 // If we're interested in the false dest, invert the condition.
665 if (!isTrueDest) TrueValues = TrueValues.inverse();
666
667 // Figure out the possible values of the query BEFORE this branch.
668 LVILatticeVal InBlock = getBlockValue(BBFrom);
Owen Anderson660cab32010-08-27 17:12:29 +0000669 if (!InBlock.isConstantRange())
670 return LVILatticeVal::getRange(TrueValues);
Owen Anderson2d0f2472010-08-11 04:24:25 +0000671
672 // Find all potential values that satisfy both the input and output
673 // conditions.
674 ConstantRange PossibleValues =
675 TrueValues.intersectWith(InBlock.getConstantRange());
676
677 return LVILatticeVal::getRange(PossibleValues);
678 }
679 }
Chris Lattner16976522009-11-11 22:48:44 +0000680 }
681 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000682
683 // If the edge was formed by a switch on the value, then we may know exactly
684 // what it is.
685 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000686 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000687 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000688 if (SI->getDefaultDest() == BBTo) {
Owen Andersondae90c62010-08-24 21:59:42 +0000689 LVILatticeVal Result;
Owen Anderson4caef602010-09-02 22:16:52 +0000690 Result.markOverdefined();
Owen Andersondae90c62010-08-24 21:59:42 +0000691 return Result;
692 }
693
Chris Lattner800c47e2009-11-15 20:02:12 +0000694 // We only know something if there is exactly one value that goes from
695 // BBFrom to BBTo.
696 unsigned NumEdges = 0;
697 ConstantInt *EdgeVal = 0;
698 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
699 if (SI->getSuccessor(i) != BBTo) continue;
700 if (NumEdges++) break;
701 EdgeVal = SI->getCaseValue(i);
702 }
703 assert(EdgeVal && "Missing successor?");
704 if (NumEdges == 1)
705 return LVILatticeVal::get(EdgeVal);
706 }
707 }
Chris Lattner16976522009-11-11 22:48:44 +0000708
709 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000710 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000711}
712
Owen Anderson81881bc2010-07-30 20:56:07 +0000713
714//===----------------------------------------------------------------------===//
715// LazyValueInfoCache Impl
716//===----------------------------------------------------------------------===//
717
Chris Lattner2c5adf82009-11-15 19:59:49 +0000718LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
719 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000720 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000721 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000722
David Greene5d93a1f2009-12-23 20:43:58 +0000723 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000724 << BB->getName() << "'\n");
725
Owen Anderson7f9cb742010-07-30 23:59:40 +0000726 LVILatticeVal Result = LVIQuery(V, *this,
Owen Andersonc8ef7502010-08-24 20:47:29 +0000727 ValueCache[LVIValueHandle(V, this)],
728 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000729
David Greene5d93a1f2009-12-23 20:43:58 +0000730 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000731 return Result;
732}
Chris Lattner16976522009-11-11 22:48:44 +0000733
Chris Lattner2c5adf82009-11-15 19:59:49 +0000734LVILatticeVal LazyValueInfoCache::
735getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
736 // If already a constant, there is nothing to compute.
737 if (Constant *VC = dyn_cast<Constant>(V))
738 return LVILatticeVal::get(VC);
739
David Greene5d93a1f2009-12-23 20:43:58 +0000740 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000741 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000742
Owen Anderson81881bc2010-07-30 20:56:07 +0000743 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000744 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000745 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000746
David Greene5d93a1f2009-12-23 20:43:58 +0000747 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000748
749 return Result;
750}
751
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000752void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
753 BasicBlock *NewSucc) {
754 // When an edge in the graph has been threaded, values that we could not
755 // determine a value for before (i.e. were marked overdefined) may be possible
756 // to solve now. We do NOT try to proactively update these values. Instead,
757 // we clear their entries from the cache, and allow lazy updating to recompute
758 // them when needed.
759
760 // The updating process is fairly simple: we need to dropped cached info
761 // for all values that were marked overdefined in OldSucc, and for those same
762 // values in any successor of OldSucc (except NewSucc) in which they were
763 // also marked overdefined.
764 std::vector<BasicBlock*> worklist;
765 worklist.push_back(OldSucc);
766
Owen Anderson9a65dc92010-07-27 23:58:11 +0000767 DenseSet<Value*> ClearSet;
Owen Anderson00ac77e2010-08-18 18:39:01 +0000768 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000769 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
770 if (I->first == OldSucc)
771 ClearSet.insert(I->second);
772 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000773
774 // Use a worklist to perform a depth-first search of OldSucc's successors.
775 // NOTE: We do not need a visited list since any blocks we have already
776 // visited will have had their overdefined markers cleared already, and we
777 // thus won't loop to their successors.
778 while (!worklist.empty()) {
779 BasicBlock *ToUpdate = worklist.back();
780 worklist.pop_back();
781
782 // Skip blocks only accessible through NewSucc.
783 if (ToUpdate == NewSucc) continue;
784
785 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000786 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000787 I != E; ++I) {
788 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson00ac77e2010-08-18 18:39:01 +0000789 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000790 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
791 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000792
Owen Anderson9a65dc92010-07-27 23:58:11 +0000793 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000794 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000795 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
796
797 assert(CI != Entry.end() && "Couldn't find entry to update?");
798 Entry.erase(CI);
799 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000800
Owen Anderson9a65dc92010-07-27 23:58:11 +0000801 // If we removed anything, then we potentially need to update
802 // blocks successors too.
803 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000804 }
805
806 if (!changed) continue;
807
808 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
809 }
810}
811
Chris Lattner2c5adf82009-11-15 19:59:49 +0000812//===----------------------------------------------------------------------===//
813// LazyValueInfo Impl
814//===----------------------------------------------------------------------===//
815
Chris Lattner2c5adf82009-11-15 19:59:49 +0000816/// getCache - This lazily constructs the LazyValueInfoCache.
817static LazyValueInfoCache &getCache(void *&PImpl) {
818 if (!PImpl)
819 PImpl = new LazyValueInfoCache();
820 return *static_cast<LazyValueInfoCache*>(PImpl);
821}
822
Owen Anderson00ac77e2010-08-18 18:39:01 +0000823bool LazyValueInfo::runOnFunction(Function &F) {
824 if (PImpl)
825 getCache(PImpl).clear();
826
827 TD = getAnalysisIfAvailable<TargetData>();
828 // Fully lazy.
829 return false;
830}
831
Chris Lattner2c5adf82009-11-15 19:59:49 +0000832void LazyValueInfo::releaseMemory() {
833 // If the cache was allocated, free it.
834 if (PImpl) {
835 delete &getCache(PImpl);
836 PImpl = 0;
837 }
838}
839
840Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
841 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
842
Chris Lattner16976522009-11-11 22:48:44 +0000843 if (Result.isConstant())
844 return Result.getConstant();
Owen Andersonee61fcf2010-08-27 23:29:38 +0000845 else if (Result.isConstantRange()) {
846 ConstantRange CR = Result.getConstantRange();
847 if (const APInt *SingleVal = CR.getSingleElement())
848 return ConstantInt::get(V->getContext(), *SingleVal);
849 }
Chris Lattner16976522009-11-11 22:48:44 +0000850 return 0;
851}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000852
Chris Lattner38392bb2009-11-12 01:29:10 +0000853/// getConstantOnEdge - Determine whether the specified value is known to be a
854/// constant on the specified edge. Return null if not.
855Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
856 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000857 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000858
859 if (Result.isConstant())
860 return Result.getConstant();
Owen Anderson9f014062010-08-10 20:03:09 +0000861 else if (Result.isConstantRange()) {
862 ConstantRange CR = Result.getConstantRange();
863 if (const APInt *SingleVal = CR.getSingleElement())
864 return ConstantInt::get(V->getContext(), *SingleVal);
865 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000866 return 0;
867}
868
Chris Lattnerb52675b2009-11-12 04:36:58 +0000869/// getPredicateOnEdge - Determine whether the specified value comparison
870/// with a constant is known to be true or false on the specified CFG edge.
871/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000872LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000873LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
874 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000875 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000876
Chris Lattnerb52675b2009-11-12 04:36:58 +0000877 // If we know the value is a constant, evaluate the conditional.
878 Constant *Res = 0;
879 if (Result.isConstant()) {
880 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
881 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
882 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000883 return Unknown;
884 }
885
Owen Anderson9f014062010-08-10 20:03:09 +0000886 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000887 ConstantInt *CI = dyn_cast<ConstantInt>(C);
888 if (!CI) return Unknown;
889
Owen Anderson9f014062010-08-10 20:03:09 +0000890 ConstantRange CR = Result.getConstantRange();
891 if (Pred == ICmpInst::ICMP_EQ) {
892 if (!CR.contains(CI->getValue()))
893 return False;
894
895 if (CR.isSingleElement() && CR.contains(CI->getValue()))
896 return True;
897 } else if (Pred == ICmpInst::ICMP_NE) {
898 if (!CR.contains(CI->getValue()))
899 return True;
900
901 if (CR.isSingleElement() && CR.contains(CI->getValue()))
902 return False;
903 }
904
905 // Handle more complex predicates.
906 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
907 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
908 if (CR.intersectWith(TrueValues).isEmptySet())
909 return False;
Owen Anderson625051b2010-08-10 23:20:01 +0000910 else if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +0000911 return True;
912
913 return Unknown;
914 }
915
Chris Lattner2c5adf82009-11-15 19:59:49 +0000916 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000917 // If this is an equality comparison, we can try to fold it knowing that
918 // "V != C1".
919 if (Pred == ICmpInst::ICMP_EQ) {
920 // !C1 == C -> false iff C1 == C.
921 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
922 Result.getNotConstant(), C, TD);
923 if (Res->isNullValue())
924 return False;
925 } else if (Pred == ICmpInst::ICMP_NE) {
926 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000927 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000928 Result.getNotConstant(), C, TD);
929 if (Res->isNullValue())
930 return True;
931 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000932 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000933 }
934
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000935 return Unknown;
936}
937
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000938void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
939 BasicBlock* NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000940 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
941}
942
943void LazyValueInfo::eraseBlock(BasicBlock *BB) {
944 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000945}