Bug Summary

File:build/source/llvm/include/llvm/Analysis/ValueLattice.h
Warning:line 260, column 5
Undefined or garbage value returned to caller

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name LazyValueInfo.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Analysis -I /build/source/llvm/lib/Analysis -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1668078801 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-11-10-135928-647445-1 -x c++ /build/source/llvm/lib/Analysis/LazyValueInfo.cpp

/build/source/llvm/lib/Analysis/LazyValueInfo.cpp

1//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interface for lazy computation of value constraint
10// information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/LazyValueInfo.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/ValueLattice.h"
23#include "llvm/Analysis/ValueTracking.h"
24#include "llvm/IR/AssemblyAnnotationWriter.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/ConstantRange.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/PatternMatch.h"
35#include "llvm/IR/ValueHandle.h"
36#include "llvm/InitializePasses.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/FormattedStream.h"
39#include "llvm/Support/KnownBits.h"
40#include "llvm/Support/raw_ostream.h"
41using namespace llvm;
42using namespace PatternMatch;
43
44#define DEBUG_TYPE"lazy-value-info" "lazy-value-info"
45
46// This is the number of worklist items we will process to try to discover an
47// answer for a given value.
48static const unsigned MaxProcessedPerValue = 500;
49
50char LazyValueInfoWrapperPass::ID = 0;
51LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
52 initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
53}
54INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",static void *initializeLazyValueInfoWrapperPassPassOnce(PassRegistry
&Registry) {
55 "Lazy Value Information Analysis", false, true)static void *initializeLazyValueInfoWrapperPassPassOnce(PassRegistry
&Registry) {
56INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
57INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
58INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",PassInfo *PI = new PassInfo( "Lazy Value Information Analysis"
, "lazy-value-info", &LazyValueInfoWrapperPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<LazyValueInfoWrapperPass>
), false, true); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeLazyValueInfoWrapperPassPassFlag
; void llvm::initializeLazyValueInfoWrapperPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLazyValueInfoWrapperPassPassFlag
, initializeLazyValueInfoWrapperPassPassOnce, std::ref(Registry
)); }
59 "Lazy Value Information Analysis", false, true)PassInfo *PI = new PassInfo( "Lazy Value Information Analysis"
, "lazy-value-info", &LazyValueInfoWrapperPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<LazyValueInfoWrapperPass>
), false, true); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeLazyValueInfoWrapperPassPassFlag
; void llvm::initializeLazyValueInfoWrapperPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLazyValueInfoWrapperPassPassFlag
, initializeLazyValueInfoWrapperPassPassOnce, std::ref(Registry
)); }
60
61namespace llvm {
62 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
63}
64
65AnalysisKey LazyValueAnalysis::Key;
66
67/// Returns true if this lattice value represents at most one possible value.
68/// This is as precise as any lattice value can get while still representing
69/// reachable code.
70static bool hasSingleValue(const ValueLatticeElement &Val) {
71 if (Val.isConstantRange() &&
72 Val.getConstantRange().isSingleElement())
73 // Integer constants are single element ranges
74 return true;
75 if (Val.isConstant())
76 // Non integer constants
77 return true;
78 return false;
79}
80
81/// Combine two sets of facts about the same value into a single set of
82/// facts. Note that this method is not suitable for merging facts along
83/// different paths in a CFG; that's what the mergeIn function is for. This
84/// is for merging facts gathered about the same value at the same location
85/// through two independent means.
86/// Notes:
87/// * This method does not promise to return the most precise possible lattice
88/// value implied by A and B. It is allowed to return any lattice element
89/// which is at least as strong as *either* A or B (unless our facts
90/// conflict, see below).
91/// * Due to unreachable code, the intersection of two lattice values could be
92/// contradictory. If this happens, we return some valid lattice value so as
93/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
94/// we do not make this guarantee. TODO: This would be a useful enhancement.
95static ValueLatticeElement intersect(const ValueLatticeElement &A,
96 const ValueLatticeElement &B) {
97 // Undefined is the strongest state. It means the value is known to be along
98 // an unreachable path.
99 if (A.isUnknown())
100 return A;
101 if (B.isUnknown())
102 return B;
103
104 // If we gave up for one, but got a useable fact from the other, use it.
105 if (A.isOverdefined())
106 return B;
107 if (B.isOverdefined())
108 return A;
109
110 // Can't get any more precise than constants.
111 if (hasSingleValue(A))
112 return A;
113 if (hasSingleValue(B))
114 return B;
115
116 // Could be either constant range or not constant here.
117 if (!A.isConstantRange() || !B.isConstantRange()) {
118 // TODO: Arbitrary choice, could be improved
119 return A;
120 }
121
122 // Intersect two constant ranges
123 ConstantRange Range =
124 A.getConstantRange().intersectWith(B.getConstantRange());
125 // Note: An empty range is implicitly converted to unknown or undef depending
126 // on MayIncludeUndef internally.
127 return ValueLatticeElement::getRange(
128 std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() ||
129 B.isConstantRangeIncludingUndef());
130}
131
132//===----------------------------------------------------------------------===//
133// LazyValueInfoCache Decl
134//===----------------------------------------------------------------------===//
135
136namespace {
137 /// A callback value handle updates the cache when values are erased.
138 class LazyValueInfoCache;
139 struct LVIValueHandle final : public CallbackVH {
140 LazyValueInfoCache *Parent;
141
142 LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
143 : CallbackVH(V), Parent(P) { }
144
145 void deleted() override;
146 void allUsesReplacedWith(Value *V) override {
147 deleted();
148 }
149 };
150} // end anonymous namespace
151
152namespace {
153 using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
154
155 /// This is the cache kept by LazyValueInfo which
156 /// maintains information about queries across the clients' queries.
157 class LazyValueInfoCache {
158 /// This is all of the cached information for one basic block. It contains
159 /// the per-value lattice elements, as well as a separate set for
160 /// overdefined values to reduce memory usage. Additionally pointers
161 /// dereferenced in the block are cached for nullability queries.
162 struct BlockCacheEntry {
163 SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
164 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
165 // None indicates that the nonnull pointers for this basic block
166 // block have not been computed yet.
167 Optional<NonNullPointerSet> NonNullPointers;
168 };
169
170 /// Cached information per basic block.
171 DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
172 BlockCache;
173 /// Set of value handles used to erase values from the cache on deletion.
174 DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
175
176 const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
177 auto It = BlockCache.find_as(BB);
178 if (It == BlockCache.end())
179 return nullptr;
180 return It->second.get();
181 }
182
183 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
184 auto It = BlockCache.find_as(BB);
185 if (It == BlockCache.end())
186 It = BlockCache.insert({ BB, std::make_unique<BlockCacheEntry>() })
187 .first;
188
189 return It->second.get();
190 }
191
192 void addValueHandle(Value *Val) {
193 auto HandleIt = ValueHandles.find_as(Val);
194 if (HandleIt == ValueHandles.end())
195 ValueHandles.insert({ Val, this });
196 }
197
198 public:
199 void insertResult(Value *Val, BasicBlock *BB,
200 const ValueLatticeElement &Result) {
201 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
202
203 // Insert over-defined values into their own cache to reduce memory
204 // overhead.
205 if (Result.isOverdefined())
206 Entry->OverDefined.insert(Val);
207 else
208 Entry->LatticeElements.insert({ Val, Result });
209
210 addValueHandle(Val);
211 }
212
213 Optional<ValueLatticeElement> getCachedValueInfo(Value *V,
214 BasicBlock *BB) const {
215 const BlockCacheEntry *Entry = getBlockEntry(BB);
216 if (!Entry)
217 return None;
218
219 if (Entry->OverDefined.count(V))
220 return ValueLatticeElement::getOverdefined();
221
222 auto LatticeIt = Entry->LatticeElements.find_as(V);
223 if (LatticeIt == Entry->LatticeElements.end())
224 return None;
225
226 return LatticeIt->second;
227 }
228
229 bool isNonNullAtEndOfBlock(
230 Value *V, BasicBlock *BB,
231 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
232 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
233 if (!Entry->NonNullPointers) {
234 Entry->NonNullPointers = InitFn(BB);
235 for (Value *V : *Entry->NonNullPointers)
236 addValueHandle(V);
237 }
238
239 return Entry->NonNullPointers->count(V);
240 }
241
242 /// clear - Empty the cache.
243 void clear() {
244 BlockCache.clear();
245 ValueHandles.clear();
246 }
247
248 /// Inform the cache that a given value has been deleted.
249 void eraseValue(Value *V);
250
251 /// This is part of the update interface to inform the cache
252 /// that a block has been deleted.
253 void eraseBlock(BasicBlock *BB);
254
255 /// Updates the cache to remove any influence an overdefined value in
256 /// OldSucc might have (unless also overdefined in NewSucc). This just
257 /// flushes elements from the cache and does not add any.
258 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
259 };
260}
261
262void LazyValueInfoCache::eraseValue(Value *V) {
263 for (auto &Pair : BlockCache) {
264 Pair.second->LatticeElements.erase(V);
265 Pair.second->OverDefined.erase(V);
266 if (Pair.second->NonNullPointers)
267 Pair.second->NonNullPointers->erase(V);
268 }
269
270 auto HandleIt = ValueHandles.find_as(V);
271 if (HandleIt != ValueHandles.end())
272 ValueHandles.erase(HandleIt);
273}
274
275void LVIValueHandle::deleted() {
276 // This erasure deallocates *this, so it MUST happen after we're done
277 // using any and all members of *this.
278 Parent->eraseValue(*this);
279}
280
281void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
282 BlockCache.erase(BB);
283}
284
285void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
286 BasicBlock *NewSucc) {
287 // When an edge in the graph has been threaded, values that we could not
288 // determine a value for before (i.e. were marked overdefined) may be
289 // possible to solve now. We do NOT try to proactively update these values.
290 // Instead, we clear their entries from the cache, and allow lazy updating to
291 // recompute them when needed.
292
293 // The updating process is fairly simple: we need to drop cached info
294 // for all values that were marked overdefined in OldSucc, and for those same
295 // values in any successor of OldSucc (except NewSucc) in which they were
296 // also marked overdefined.
297 std::vector<BasicBlock*> worklist;
298 worklist.push_back(OldSucc);
299
300 const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
301 if (!Entry || Entry->OverDefined.empty())
302 return; // Nothing to process here.
303 SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
304 Entry->OverDefined.end());
305
306 // Use a worklist to perform a depth-first search of OldSucc's successors.
307 // NOTE: We do not need a visited list since any blocks we have already
308 // visited will have had their overdefined markers cleared already, and we
309 // thus won't loop to their successors.
310 while (!worklist.empty()) {
311 BasicBlock *ToUpdate = worklist.back();
312 worklist.pop_back();
313
314 // Skip blocks only accessible through NewSucc.
315 if (ToUpdate == NewSucc) continue;
316
317 // If a value was marked overdefined in OldSucc, and is here too...
318 auto OI = BlockCache.find_as(ToUpdate);
319 if (OI == BlockCache.end() || OI->second->OverDefined.empty())
320 continue;
321 auto &ValueSet = OI->second->OverDefined;
322
323 bool changed = false;
324 for (Value *V : ValsToClear) {
325 if (!ValueSet.erase(V))
326 continue;
327
328 // If we removed anything, then we potentially need to update
329 // blocks successors too.
330 changed = true;
331 }
332
333 if (!changed) continue;
334
335 llvm::append_range(worklist, successors(ToUpdate));
336 }
337}
338
339
340namespace {
341/// An assembly annotator class to print LazyValueCache information in
342/// comments.
343class LazyValueInfoImpl;
344class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
345 LazyValueInfoImpl *LVIImpl;
346 // While analyzing which blocks we can solve values for, we need the dominator
347 // information.
348 DominatorTree &DT;
349
350public:
351 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
352 : LVIImpl(L), DT(DTree) {}
353
354 void emitBasicBlockStartAnnot(const BasicBlock *BB,
355 formatted_raw_ostream &OS) override;
356
357 void emitInstructionAnnot(const Instruction *I,
358 formatted_raw_ostream &OS) override;
359};
360}
361namespace {
362// The actual implementation of the lazy analysis and update. Note that the
363// inheritance from LazyValueInfoCache is intended to be temporary while
364// splitting the code and then transitioning to a has-a relationship.
365class LazyValueInfoImpl {
366
367 /// Cached results from previous queries
368 LazyValueInfoCache TheCache;
369
370 /// This stack holds the state of the value solver during a query.
371 /// It basically emulates the callstack of the naive
372 /// recursive value lookup process.
373 SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
374
375 /// Keeps track of which block-value pairs are in BlockValueStack.
376 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
377
378 /// Push BV onto BlockValueStack unless it's already in there.
379 /// Returns true on success.
380 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
381 if (!BlockValueSet.insert(BV).second)
382 return false; // It's already in the stack.
383
384 LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "PUSH: " << *BV.
second << " in " << BV.first->getName() <<
"\n"; } } while (false)
385 << BV.first->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "PUSH: " << *BV.
second << " in " << BV.first->getName() <<
"\n"; } } while (false)
;
386 BlockValueStack.push_back(BV);
387 return true;
388 }
389
390 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
391 const DataLayout &DL; ///< A mandatory DataLayout
392
393 /// Declaration of the llvm.experimental.guard() intrinsic,
394 /// if it exists in the module.
395 Function *GuardDecl;
396
397 Optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
398 Instruction *CxtI);
399 Optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
400 BasicBlock *T, Instruction *CxtI = nullptr);
401
402 // These methods process one work item and may add more. A false value
403 // returned means that the work item was not completely processed and must
404 // be revisited after going through the new items.
405 bool solveBlockValue(Value *Val, BasicBlock *BB);
406 Optional<ValueLatticeElement> solveBlockValueImpl(Value *Val, BasicBlock *BB);
407 Optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
408 BasicBlock *BB);
409 Optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
410 BasicBlock *BB);
411 Optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
412 BasicBlock *BB);
413 Optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
414 BasicBlock *BB);
415 Optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
416 Instruction *I, BasicBlock *BB,
417 std::function<ConstantRange(const ConstantRange &,
418 const ConstantRange &)> OpFn);
419 Optional<ValueLatticeElement> solveBlockValueBinaryOp(BinaryOperator *BBI,
420 BasicBlock *BB);
421 Optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
422 BasicBlock *BB);
423 Optional<ValueLatticeElement> solveBlockValueOverflowIntrinsic(
424 WithOverflowInst *WO, BasicBlock *BB);
425 Optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
426 BasicBlock *BB);
427 Optional<ValueLatticeElement> solveBlockValueExtractValue(
428 ExtractValueInst *EVI, BasicBlock *BB);
429 bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
430 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
431 ValueLatticeElement &BBLV,
432 Instruction *BBI);
433
434 void solve();
435
436public:
437 /// This is the query interface to determine the lattice value for the
438 /// specified Value* at the context instruction (if specified) or at the
439 /// start of the block.
440 ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
441 Instruction *CxtI = nullptr);
442
443 /// This is the query interface to determine the lattice value for the
444 /// specified Value* at the specified instruction using only information
445 /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
446 /// recursive query is performed.
447 ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
448
449 /// This is the query interface to determine the lattice
450 /// value for the specified Value* that is true on the specified edge.
451 ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
452 BasicBlock *ToBB,
453 Instruction *CxtI = nullptr);
454
455 /// Complete flush all previously computed values
456 void clear() {
457 TheCache.clear();
458 }
459
460 /// Printing the LazyValueInfo Analysis.
461 void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
462 LazyValueInfoAnnotatedWriter Writer(this, DTree);
463 F.print(OS, &Writer);
464 }
465
466 /// This is part of the update interface to inform the cache
467 /// that a block has been deleted.
468 void eraseBlock(BasicBlock *BB) {
469 TheCache.eraseBlock(BB);
470 }
471
472 /// This is the update interface to inform the cache that an edge from
473 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
474 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
475
476 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
477 Function *GuardDecl)
478 : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
479};
480} // end anonymous namespace
481
482
483void LazyValueInfoImpl::solve() {
484 SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
485 BlockValueStack.begin(), BlockValueStack.end());
486
487 unsigned processedCount = 0;
488 while (!BlockValueStack.empty()) {
489 processedCount++;
490 // Abort if we have to process too many values to get a result for this one.
491 // Because of the design of the overdefined cache currently being per-block
492 // to avoid naming-related issues (IE it wants to try to give different
493 // results for the same name in different blocks), overdefined results don't
494 // get cached globally, which in turn means we will often try to rediscover
495 // the same overdefined result again and again. Once something like
496 // PredicateInfo is used in LVI or CVP, we should be able to make the
497 // overdefined cache global, and remove this throttle.
498 if (processedCount > MaxProcessedPerValue) {
499 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "Giving up on stack because we are getting too deep\n"
; } } while (false)
500 dbgs() << "Giving up on stack because we are getting too deep\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "Giving up on stack because we are getting too deep\n"
; } } while (false)
;
501 // Fill in the original values
502 while (!StartingStack.empty()) {
503 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
504 TheCache.insertResult(e.second, e.first,
505 ValueLatticeElement::getOverdefined());
506 StartingStack.pop_back();
507 }
508 BlockValueSet.clear();
509 BlockValueStack.clear();
510 return;
511 }
512 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
513 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!")(static_cast <bool> (BlockValueSet.count(e) && "Stack value should be in BlockValueSet!"
) ? void (0) : __assert_fail ("BlockValueSet.count(e) && \"Stack value should be in BlockValueSet!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 513, __extension__ __PRETTY_FUNCTION__
))
;
514
515 if (solveBlockValue(e.second, e.first)) {
516 // The work item was completely processed.
517 assert(BlockValueStack.back() == e && "Nothing should have been pushed!")(static_cast <bool> (BlockValueStack.back() == e &&
"Nothing should have been pushed!") ? void (0) : __assert_fail
("BlockValueStack.back() == e && \"Nothing should have been pushed!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 517, __extension__ __PRETTY_FUNCTION__
))
;
518#ifndef NDEBUG
519 Optional<ValueLatticeElement> BBLV =
520 TheCache.getCachedValueInfo(e.second, e.first);
521 assert(BBLV && "Result should be in cache!")(static_cast <bool> (BBLV && "Result should be in cache!"
) ? void (0) : __assert_fail ("BBLV && \"Result should be in cache!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 521, __extension__ __PRETTY_FUNCTION__
))
;
522 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< *BBLV << "\n"; } } while (false)
523 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< *BBLV << "\n"; } } while (false)
524 << *BBLV << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< *BBLV << "\n"; } } while (false)
;
525#endif
526
527 BlockValueStack.pop_back();
528 BlockValueSet.erase(e);
529 } else {
530 // More work needs to be done before revisiting.
531 assert(BlockValueStack.back() != e && "Stack should have been pushed!")(static_cast <bool> (BlockValueStack.back() != e &&
"Stack should have been pushed!") ? void (0) : __assert_fail
("BlockValueStack.back() != e && \"Stack should have been pushed!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 531, __extension__ __PRETTY_FUNCTION__
))
;
532 }
533 }
534}
535
536Optional<ValueLatticeElement> LazyValueInfoImpl::getBlockValue(
537 Value *Val, BasicBlock *BB, Instruction *CxtI) {
538 // If already a constant, there is nothing to compute.
539 if (Constant *VC = dyn_cast<Constant>(Val))
540 return ValueLatticeElement::get(VC);
541
542 if (Optional<ValueLatticeElement> OptLatticeVal =
543 TheCache.getCachedValueInfo(Val, BB)) {
544 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
545 return OptLatticeVal;
546 }
547
548 // We have hit a cycle, assume overdefined.
549 if (!pushBlockValue({ BB, Val }))
550 return ValueLatticeElement::getOverdefined();
551
552 // Yet to be resolved.
553 return None;
554}
555
556static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
557 switch (BBI->getOpcode()) {
558 default: break;
559 case Instruction::Load:
560 case Instruction::Call:
561 case Instruction::Invoke:
562 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
563 if (isa<IntegerType>(BBI->getType())) {
564 return ValueLatticeElement::getRange(
565 getConstantRangeFromMetadata(*Ranges));
566 }
567 break;
568 };
569 // Nothing known - will be intersected with other facts
570 return ValueLatticeElement::getOverdefined();
571}
572
573bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
574 assert(!isa<Constant>(Val) && "Value should not be constant")(static_cast <bool> (!isa<Constant>(Val) &&
"Value should not be constant") ? void (0) : __assert_fail (
"!isa<Constant>(Val) && \"Value should not be constant\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 574, __extension__ __PRETTY_FUNCTION__
))
;
575 assert(!TheCache.getCachedValueInfo(Val, BB) &&(static_cast <bool> (!TheCache.getCachedValueInfo(Val, BB
) && "Value should not be in cache") ? void (0) : __assert_fail
("!TheCache.getCachedValueInfo(Val, BB) && \"Value should not be in cache\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 576, __extension__ __PRETTY_FUNCTION__
))
576 "Value should not be in cache")(static_cast <bool> (!TheCache.getCachedValueInfo(Val, BB
) && "Value should not be in cache") ? void (0) : __assert_fail
("!TheCache.getCachedValueInfo(Val, BB) && \"Value should not be in cache\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 576, __extension__ __PRETTY_FUNCTION__
))
;
577
578 // Hold off inserting this value into the Cache in case we have to return
579 // false and come back later.
580 Optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
581 if (!Res)
582 // Work pushed, will revisit
583 return false;
584
585 TheCache.insertResult(Val, BB, *Res);
586 return true;
587}
588
589Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueImpl(
590 Value *Val, BasicBlock *BB) {
591 Instruction *BBI = dyn_cast<Instruction>(Val);
592 if (!BBI || BBI->getParent() != BB)
593 return solveBlockValueNonLocal(Val, BB);
594
595 if (PHINode *PN = dyn_cast<PHINode>(BBI))
596 return solveBlockValuePHINode(PN, BB);
597
598 if (auto *SI = dyn_cast<SelectInst>(BBI))
599 return solveBlockValueSelect(SI, BB);
600
601 // If this value is a nonnull pointer, record it's range and bailout. Note
602 // that for all other pointer typed values, we terminate the search at the
603 // definition. We could easily extend this to look through geps, bitcasts,
604 // and the like to prove non-nullness, but it's not clear that's worth it
605 // compile time wise. The context-insensitive value walk done inside
606 // isKnownNonZero gets most of the profitable cases at much less expense.
607 // This does mean that we have a sensitivity to where the defining
608 // instruction is placed, even if it could legally be hoisted much higher.
609 // That is unfortunate.
610 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
611 if (PT && isKnownNonZero(BBI, DL))
612 return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
613
614 if (BBI->getType()->isIntegerTy()) {
615 if (auto *CI = dyn_cast<CastInst>(BBI))
616 return solveBlockValueCast(CI, BB);
617
618 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
619 return solveBlockValueBinaryOp(BO, BB);
620
621 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
622 return solveBlockValueExtractValue(EVI, BB);
623
624 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
625 return solveBlockValueIntrinsic(II, BB);
626 }
627
628 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown inst def found.\n"; }
} while (false)
629 << "' - unknown inst def found.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown inst def found.\n"; }
} while (false)
;
630 return getFromRangeMetadata(BBI);
631}
632
633static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
634 // TODO: Use NullPointerIsDefined instead.
635 if (Ptr->getType()->getPointerAddressSpace() == 0)
636 PtrSet.insert(getUnderlyingObject(Ptr));
637}
638
639static void AddNonNullPointersByInstruction(
640 Instruction *I, NonNullPointerSet &PtrSet) {
641 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
642 AddNonNullPointer(L->getPointerOperand(), PtrSet);
643 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
644 AddNonNullPointer(S->getPointerOperand(), PtrSet);
645 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
646 if (MI->isVolatile()) return;
647
648 // FIXME: check whether it has a valuerange that excludes zero?
649 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
650 if (!Len || Len->isZero()) return;
651
652 AddNonNullPointer(MI->getRawDest(), PtrSet);
653 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
654 AddNonNullPointer(MTI->getRawSource(), PtrSet);
655 }
656}
657
658bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
659 if (NullPointerIsDefined(BB->getParent(),
660 Val->getType()->getPointerAddressSpace()))
661 return false;
662
663 Val = Val->stripInBoundsOffsets();
664 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
665 NonNullPointerSet NonNullPointers;
666 for (Instruction &I : *BB)
667 AddNonNullPointersByInstruction(&I, NonNullPointers);
668 return NonNullPointers;
669 });
670}
671
672Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueNonLocal(
673 Value *Val, BasicBlock *BB) {
674 ValueLatticeElement Result; // Start Undefined.
675
676 // If this is the entry block, we must be asking about an argument. The
677 // value is overdefined.
678 if (BB->isEntryBlock()) {
679 assert(isa<Argument>(Val) && "Unknown live-in to the entry block")(static_cast <bool> (isa<Argument>(Val) &&
"Unknown live-in to the entry block") ? void (0) : __assert_fail
("isa<Argument>(Val) && \"Unknown live-in to the entry block\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 679, __extension__ __PRETTY_FUNCTION__
))
;
680 return ValueLatticeElement::getOverdefined();
681 }
682
683 // Loop over all of our predecessors, merging what we know from them into
684 // result. If we encounter an unexplored predecessor, we eagerly explore it
685 // in a depth first manner. In practice, this has the effect of discovering
686 // paths we can't analyze eagerly without spending compile times analyzing
687 // other paths. This heuristic benefits from the fact that predecessors are
688 // frequently arranged such that dominating ones come first and we quickly
689 // find a path to function entry. TODO: We should consider explicitly
690 // canonicalizing to make this true rather than relying on this happy
691 // accident.
692 for (BasicBlock *Pred : predecessors(BB)) {
693 Optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
694 if (!EdgeResult)
695 // Explore that input, then return here
696 return None;
697
698 Result.mergeIn(*EdgeResult);
699
700 // If we hit overdefined, exit early. The BlockVals entry is already set
701 // to overdefined.
702 if (Result.isOverdefined()) {
703 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred '"
<< Pred->getName() << "' (non local).\n"; } }
while (false)
704 << "' - overdefined because of pred '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred '"
<< Pred->getName() << "' (non local).\n"; } }
while (false)
705 << Pred->getName() << "' (non local).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred '"
<< Pred->getName() << "' (non local).\n"; } }
while (false)
;
706 return Result;
707 }
708 }
709
710 // Return the merged value, which is more precise than 'overdefined'.
711 assert(!Result.isOverdefined())(static_cast <bool> (!Result.isOverdefined()) ? void (0
) : __assert_fail ("!Result.isOverdefined()", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 711, __extension__ __PRETTY_FUNCTION__))
;
712 return Result;
713}
714
715Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValuePHINode(
716 PHINode *PN, BasicBlock *BB) {
717 ValueLatticeElement Result; // Start Undefined.
718
719 // Loop over all of our predecessors, merging what we know from them into
720 // result. See the comment about the chosen traversal order in
721 // solveBlockValueNonLocal; the same reasoning applies here.
722 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
723 BasicBlock *PhiBB = PN->getIncomingBlock(i);
724 Value *PhiVal = PN->getIncomingValue(i);
725 // Note that we can provide PN as the context value to getEdgeValue, even
726 // though the results will be cached, because PN is the value being used as
727 // the cache key in the caller.
728 Optional<ValueLatticeElement> EdgeResult =
729 getEdgeValue(PhiVal, PhiBB, BB, PN);
730 if (!EdgeResult)
731 // Explore that input, then return here
732 return None;
733
734 Result.mergeIn(*EdgeResult);
735
736 // If we hit overdefined, exit early. The BlockVals entry is already set
737 // to overdefined.
738 if (Result.isOverdefined()) {
739 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (local).\n"
; } } while (false)
740 << "' - overdefined because of pred (local).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (local).\n"
; } } while (false)
;
741
742 return Result;
743 }
744 }
745
746 // Return the merged value, which is more precise than 'overdefined'.
747 assert(!Result.isOverdefined() && "Possible PHI in entry block?")(static_cast <bool> (!Result.isOverdefined() &&
"Possible PHI in entry block?") ? void (0) : __assert_fail (
"!Result.isOverdefined() && \"Possible PHI in entry block?\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 747, __extension__ __PRETTY_FUNCTION__
))
;
748 return Result;
749}
750
751static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
752 bool isTrueDest = true);
753
754// If we can determine a constraint on the value given conditions assumed by
755// the program, intersect those constraints with BBLV
756void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
757 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
758 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
759 if (!BBI)
760 return;
761
762 BasicBlock *BB = BBI->getParent();
763 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
764 if (!AssumeVH)
765 continue;
766
767 // Only check assumes in the block of the context instruction. Other
768 // assumes will have already been taken into account when the value was
769 // propagated from predecessor blocks.
770 auto *I = cast<CallInst>(AssumeVH);
771 if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
772 continue;
773
774 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
775 }
776
777 // If guards are not used in the module, don't spend time looking for them
778 if (GuardDecl && !GuardDecl->use_empty() &&
779 BBI->getIterator() != BB->begin()) {
780 for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
781 BB->rend())) {
782 Value *Cond = nullptr;
783 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
784 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
785 }
786 }
787
788 if (BBLV.isOverdefined()) {
789 // Check whether we're checking at the terminator, and the pointer has
790 // been dereferenced in this block.
791 PointerType *PTy = dyn_cast<PointerType>(Val->getType());
792 if (PTy && BB->getTerminator() == BBI &&
793 isNonNullAtEndOfBlock(Val, BB))
794 BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
795 }
796}
797
798static ConstantRange getConstantRangeOrFull(const ValueLatticeElement &Val,
799 Type *Ty, const DataLayout &DL) {
800 if (Val.isConstantRange())
801 return Val.getConstantRange();
802 return ConstantRange::getFull(DL.getTypeSizeInBits(Ty));
803}
804
805Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueSelect(
806 SelectInst *SI, BasicBlock *BB) {
807 // Recurse on our inputs if needed
808 Optional<ValueLatticeElement> OptTrueVal =
809 getBlockValue(SI->getTrueValue(), BB, SI);
810 if (!OptTrueVal)
811 return None;
812 ValueLatticeElement &TrueVal = *OptTrueVal;
813
814 Optional<ValueLatticeElement> OptFalseVal =
815 getBlockValue(SI->getFalseValue(), BB, SI);
816 if (!OptFalseVal)
817 return None;
818 ValueLatticeElement &FalseVal = *OptFalseVal;
819
820 if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
821 const ConstantRange &TrueCR =
822 getConstantRangeOrFull(TrueVal, SI->getType(), DL);
823 const ConstantRange &FalseCR =
824 getConstantRangeOrFull(FalseVal, SI->getType(), DL);
825 Value *LHS = nullptr;
826 Value *RHS = nullptr;
827 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
828 // Is this a min specifically of our two inputs? (Avoid the risk of
829 // ValueTracking getting smarter looking back past our immediate inputs.)
830 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
831 ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
832 (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
833 ConstantRange ResultCR = [&]() {
834 switch (SPR.Flavor) {
835 default:
836 llvm_unreachable("unexpected minmax type!")::llvm::llvm_unreachable_internal("unexpected minmax type!", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 836)
;
837 case SPF_SMIN: /// Signed minimum
838 return TrueCR.smin(FalseCR);
839 case SPF_UMIN: /// Unsigned minimum
840 return TrueCR.umin(FalseCR);
841 case SPF_SMAX: /// Signed maximum
842 return TrueCR.smax(FalseCR);
843 case SPF_UMAX: /// Unsigned maximum
844 return TrueCR.umax(FalseCR);
845 };
846 }();
847 return ValueLatticeElement::getRange(
848 ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
849 FalseVal.isConstantRangeIncludingUndef());
850 }
851
852 if (SPR.Flavor == SPF_ABS) {
853 if (LHS == SI->getTrueValue())
854 return ValueLatticeElement::getRange(
855 TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
856 if (LHS == SI->getFalseValue())
857 return ValueLatticeElement::getRange(
858 FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
859 }
860
861 if (SPR.Flavor == SPF_NABS) {
862 ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
863 if (LHS == SI->getTrueValue())
864 return ValueLatticeElement::getRange(
865 Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
866 if (LHS == SI->getFalseValue())
867 return ValueLatticeElement::getRange(
868 Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
869 }
870 }
871
872 // Can we constrain the facts about the true and false values by using the
873 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
874 // TODO: We could potentially refine an overdefined true value above.
875 Value *Cond = SI->getCondition();
876 TrueVal = intersect(TrueVal,
877 getValueFromCondition(SI->getTrueValue(), Cond, true));
878 FalseVal = intersect(FalseVal,
879 getValueFromCondition(SI->getFalseValue(), Cond, false));
880
881 ValueLatticeElement Result = TrueVal;
882 Result.mergeIn(FalseVal);
883 return Result;
884}
885
886Optional<ConstantRange> LazyValueInfoImpl::getRangeFor(Value *V,
887 Instruction *CxtI,
888 BasicBlock *BB) {
889 Optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
890 if (!OptVal)
891 return None;
892 return getConstantRangeOrFull(*OptVal, V->getType(), DL);
893}
894
895Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast(
896 CastInst *CI, BasicBlock *BB) {
897 // Without knowing how wide the input is, we can't analyze it in any useful
898 // way.
899 if (!CI->getOperand(0)->getType()->isSized())
900 return ValueLatticeElement::getOverdefined();
901
902 // Filter out casts we don't know how to reason about before attempting to
903 // recurse on our operand. This can cut a long search short if we know we're
904 // not going to be able to get any useful information anways.
905 switch (CI->getOpcode()) {
906 case Instruction::Trunc:
907 case Instruction::SExt:
908 case Instruction::ZExt:
909 case Instruction::BitCast:
910 break;
911 default:
912 // Unhandled instructions are overdefined.
913 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown cast).\n"
; } } while (false)
914 << "' - overdefined (unknown cast).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown cast).\n"
; } } while (false)
;
915 return ValueLatticeElement::getOverdefined();
916 }
917
918 // Figure out the range of the LHS. If that fails, we still apply the
919 // transfer rule on the full set since we may be able to locally infer
920 // interesting facts.
921 Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
922 if (!LHSRes)
923 // More work to do before applying this transfer rule.
924 return None;
925 const ConstantRange &LHSRange = LHSRes.value();
926
927 const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
928
929 // NOTE: We're currently limited by the set of operations that ConstantRange
930 // can evaluate symbolically. Enhancing that set will allows us to analyze
931 // more definitions.
932 return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
933 ResultBitWidth));
934}
935
936Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
937 Instruction *I, BasicBlock *BB,
938 std::function<ConstantRange(const ConstantRange &,
939 const ConstantRange &)> OpFn) {
940 // Figure out the ranges of the operands. If that fails, use a
941 // conservative range, but apply the transfer rule anyways. This
942 // lets us pick up facts from expressions like "and i32 (call i32
943 // @foo()), 32"
944 Optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
945 Optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
946 if (!LHSRes || !RHSRes)
947 // More work to do before applying this transfer rule.
948 return None;
949
950 const ConstantRange &LHSRange = LHSRes.value();
951 const ConstantRange &RHSRange = RHSRes.value();
952 return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
953}
954
955Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOp(
956 BinaryOperator *BO, BasicBlock *BB) {
957 assert(BO->getOperand(0)->getType()->isSized() &&(static_cast <bool> (BO->getOperand(0)->getType()
->isSized() && "all operands to binary operators are sized"
) ? void (0) : __assert_fail ("BO->getOperand(0)->getType()->isSized() && \"all operands to binary operators are sized\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 958, __extension__ __PRETTY_FUNCTION__
))
958 "all operands to binary operators are sized")(static_cast <bool> (BO->getOperand(0)->getType()
->isSized() && "all operands to binary operators are sized"
) ? void (0) : __assert_fail ("BO->getOperand(0)->getType()->isSized() && \"all operands to binary operators are sized\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 958, __extension__ __PRETTY_FUNCTION__
))
;
959 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
960 unsigned NoWrapKind = 0;
961 if (OBO->hasNoUnsignedWrap())
962 NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
963 if (OBO->hasNoSignedWrap())
964 NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
965
966 return solveBlockValueBinaryOpImpl(
967 BO, BB,
968 [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
969 return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
970 });
971 }
972
973 return solveBlockValueBinaryOpImpl(
974 BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
975 return CR1.binaryOp(BO->getOpcode(), CR2);
976 });
977}
978
979Optional<ValueLatticeElement>
980LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
981 BasicBlock *BB) {
982 return solveBlockValueBinaryOpImpl(
983 WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
984 return CR1.binaryOp(WO->getBinaryOp(), CR2);
985 });
986}
987
988Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueIntrinsic(
989 IntrinsicInst *II, BasicBlock *BB) {
990 if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
991 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown intrinsic.\n"; } } while
(false)
992 << "' - unknown intrinsic.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown intrinsic.\n"; } } while
(false)
;
993 return getFromRangeMetadata(II);
994 }
995
996 SmallVector<ConstantRange, 2> OpRanges;
997 for (Value *Op : II->args()) {
998 Optional<ConstantRange> Range = getRangeFor(Op, II, BB);
999 if (!Range)
1000 return None;
1001 OpRanges.push_back(*Range);
1002 }
1003
1004 return ValueLatticeElement::getRange(
1005 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges));
1006}
1007
1008Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueExtractValue(
1009 ExtractValueInst *EVI, BasicBlock *BB) {
1010 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1011 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1012 return solveBlockValueOverflowIntrinsic(WO, BB);
1013
1014 // Handle extractvalue of insertvalue to allow further simplification
1015 // based on replaced with.overflow intrinsics.
1016 if (Value *V = simplifyExtractValueInst(
1017 EVI->getAggregateOperand(), EVI->getIndices(),
1018 EVI->getModule()->getDataLayout()))
1019 return getBlockValue(V, BB, EVI);
1020
1021 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown extractvalue).\n"
; } } while (false)
1022 << "' - overdefined (unknown extractvalue).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown extractvalue).\n"
; } } while (false)
;
1023 return ValueLatticeElement::getOverdefined();
1024}
1025
1026static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
1027 ICmpInst::Predicate Pred) {
1028 if (LHS == Val)
1029 return true;
1030
1031 // Handle range checking idiom produced by InstCombine. We will subtract the
1032 // offset from the allowed range for RHS in this case.
1033 const APInt *C;
1034 if (match(LHS, m_Add(m_Specific(Val), m_APInt(C)))) {
1035 Offset = *C;
1036 return true;
1037 }
1038
1039 // Handle the symmetric case. This appears in saturation patterns like
1040 // (x == 16) ? 16 : (x + 1).
1041 if (match(Val, m_Add(m_Specific(LHS), m_APInt(C)))) {
1042 Offset = -*C;
1043 return true;
1044 }
1045
1046 // If (x | y) < C, then (x < C) && (y < C).
1047 if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1048 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
1049 return true;
1050
1051 // If (x & y) > C, then (x > C) && (y > C).
1052 if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1053 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
1054 return true;
1055
1056 return false;
1057}
1058
1059/// Get value range for a "(Val + Offset) Pred RHS" condition.
1060static ValueLatticeElement getValueFromSimpleICmpCondition(
1061 CmpInst::Predicate Pred, Value *RHS, const APInt &Offset) {
1062 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1063 /*isFullSet=*/true);
1064 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1065 RHSRange = ConstantRange(CI->getValue());
1066 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1067 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1068 RHSRange = getConstantRangeFromMetadata(*Ranges);
1069
1070 ConstantRange TrueValues =
1071 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1072 return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1073}
1074
1075static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1076 bool isTrueDest) {
1077 Value *LHS = ICI->getOperand(0);
1078 Value *RHS = ICI->getOperand(1);
1079
1080 // Get the predicate that must hold along the considered edge.
1081 CmpInst::Predicate EdgePred =
1082 isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1083
1084 if (isa<Constant>(RHS)) {
1085 if (ICI->isEquality() && LHS == Val) {
1086 if (EdgePred == ICmpInst::ICMP_EQ)
1087 return ValueLatticeElement::get(cast<Constant>(RHS));
1088 else if (!isa<UndefValue>(RHS))
1089 return ValueLatticeElement::getNot(cast<Constant>(RHS));
1090 }
1091 }
1092
1093 Type *Ty = Val->getType();
1094 if (!Ty->isIntegerTy())
1095 return ValueLatticeElement::getOverdefined();
1096
1097 unsigned BitWidth = Ty->getScalarSizeInBits();
1098 APInt Offset(BitWidth, 0);
1099 if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1100 return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset);
1101
1102 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1103 if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1104 return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset);
1105
1106 const APInt *Mask, *C;
1107 if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1108 match(RHS, m_APInt(C))) {
1109 // If (Val & Mask) == C then all the masked bits are known and we can
1110 // compute a value range based on that.
1111 if (EdgePred == ICmpInst::ICMP_EQ) {
1112 KnownBits Known;
1113 Known.Zero = ~*C & *Mask;
1114 Known.One = *C & *Mask;
1115 return ValueLatticeElement::getRange(
1116 ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1117 }
1118 // If (Val & Mask) != 0 then the value must be larger than the lowest set
1119 // bit of Mask.
1120 if (EdgePred == ICmpInst::ICMP_NE && !Mask->isZero() && C->isZero()) {
1121 return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
1122 APInt::getOneBitSet(BitWidth, Mask->countTrailingZeros()),
1123 APInt::getZero(BitWidth)));
1124 }
1125 }
1126
1127 // If (X urem Modulus) >= C, then X >= C.
1128 // If trunc X >= C, then X >= C.
1129 // TODO: An upper bound could be computed as well.
1130 if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
1131 m_Trunc(m_Specific(Val)))) &&
1132 match(RHS, m_APInt(C))) {
1133 // Use the icmp region so we don't have to deal with different predicates.
1134 ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
1135 if (!CR.isEmptySet())
1136 return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
1137 CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
1138 }
1139
1140 return ValueLatticeElement::getOverdefined();
1141}
1142
1143// Handle conditions of the form
1144// extractvalue(op.with.overflow(%x, C), 1).
1145static ValueLatticeElement getValueFromOverflowCondition(
1146 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1147 // TODO: This only works with a constant RHS for now. We could also compute
1148 // the range of the RHS, but this doesn't fit into the current structure of
1149 // the edge value calculation.
1150 const APInt *C;
1151 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1152 return ValueLatticeElement::getOverdefined();
1153
1154 // Calculate the possible values of %x for which no overflow occurs.
1155 ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
1156 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1157
1158 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1159 // constrained to it's inverse (all values that might cause overflow).
1160 if (IsTrueDest)
1161 NWR = NWR.inverse();
1162 return ValueLatticeElement::getRange(NWR);
1163}
1164
1165static Optional<ValueLatticeElement>
1166getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1167 bool isRevisit,
1168 SmallDenseMap<Value *, ValueLatticeElement> &Visited,
1169 SmallVectorImpl<Value *> &Worklist) {
1170 if (!isRevisit) {
1171 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1172 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1173
1174 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1175 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1176 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1177 return getValueFromOverflowCondition(Val, WO, isTrueDest);
1178 }
1179
1180 Value *L, *R;
1181 bool IsAnd;
1182 if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1183 IsAnd = true;
1184 else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1185 IsAnd = false;
1186 else
1187 return ValueLatticeElement::getOverdefined();
1188
1189 auto LV = Visited.find(L);
1190 auto RV = Visited.find(R);
1191
1192 // if (L && R) -> intersect L and R
1193 // if (!(L || R)) -> intersect L and R
1194 // if (L || R) -> union L and R
1195 // if (!(L && R)) -> union L and R
1196 if ((isTrueDest ^ IsAnd) && (LV != Visited.end())) {
1197 ValueLatticeElement V = LV->second;
1198 if (V.isOverdefined())
1199 return V;
1200 if (RV != Visited.end()) {
1201 V.mergeIn(RV->second);
1202 return V;
1203 }
1204 }
1205
1206 if (LV == Visited.end() || RV == Visited.end()) {
1207 assert(!isRevisit)(static_cast <bool> (!isRevisit) ? void (0) : __assert_fail
("!isRevisit", "llvm/lib/Analysis/LazyValueInfo.cpp", 1207, __extension__
__PRETTY_FUNCTION__))
;
1208 if (LV == Visited.end())
1209 Worklist.push_back(L);
1210 if (RV == Visited.end())
1211 Worklist.push_back(R);
1212 return None;
1213 }
1214
1215 return intersect(LV->second, RV->second);
1216}
1217
1218ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
1219 bool isTrueDest) {
1220 assert(Cond && "precondition")(static_cast <bool> (Cond && "precondition") ? void
(0) : __assert_fail ("Cond && \"precondition\"", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 1220, __extension__ __PRETTY_FUNCTION__))
;
1221 SmallDenseMap<Value*, ValueLatticeElement> Visited;
1222 SmallVector<Value *> Worklist;
1223
1224 Worklist.push_back(Cond);
1225 do {
1226 Value *CurrentCond = Worklist.back();
1227 // Insert an Overdefined placeholder into the set to prevent
1228 // infinite recursion if there exists IRs that use not
1229 // dominated by its def as in this example:
1230 // "%tmp3 = or i1 undef, %tmp4"
1231 // "%tmp4 = or i1 undef, %tmp3"
1232 auto Iter =
1233 Visited.try_emplace(CurrentCond, ValueLatticeElement::getOverdefined());
1234 bool isRevisit = !Iter.second;
1235 Optional<ValueLatticeElement> Result = getValueFromConditionImpl(
1236 Val, CurrentCond, isTrueDest, isRevisit, Visited, Worklist);
1237 if (Result) {
1238 Visited[CurrentCond] = *Result;
1239 Worklist.pop_back();
1240 }
1241 } while (!Worklist.empty());
1242
1243 auto Result = Visited.find(Cond);
1244 assert(Result != Visited.end())(static_cast <bool> (Result != Visited.end()) ? void (0
) : __assert_fail ("Result != Visited.end()", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 1244, __extension__ __PRETTY_FUNCTION__))
;
1245 return Result->second;
1246}
1247
1248// Return true if Usr has Op as an operand, otherwise false.
1249static bool usesOperand(User *Usr, Value *Op) {
1250 return is_contained(Usr->operands(), Op);
1251}
1252
1253// Return true if the instruction type of Val is supported by
1254// constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1255// Call this before calling constantFoldUser() to find out if it's even worth
1256// attempting to call it.
1257static bool isOperationFoldable(User *Usr) {
1258 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1259}
1260
1261// Check if Usr can be simplified to an integer constant when the value of one
1262// of its operands Op is an integer constant OpConstVal. If so, return it as an
1263// lattice value range with a single element or otherwise return an overdefined
1264// lattice value.
1265static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
1266 const APInt &OpConstVal,
1267 const DataLayout &DL) {
1268 assert(isOperationFoldable(Usr) && "Precondition")(static_cast <bool> (isOperationFoldable(Usr) &&
"Precondition") ? void (0) : __assert_fail ("isOperationFoldable(Usr) && \"Precondition\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1268, __extension__ __PRETTY_FUNCTION__
))
;
1269 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1270 // Check if Usr can be simplified to a constant.
1271 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1272 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op")(static_cast <bool> (CI->getOperand(0) == Op &&
"Operand 0 isn't Op") ? void (0) : __assert_fail ("CI->getOperand(0) == Op && \"Operand 0 isn't Op\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1272, __extension__ __PRETTY_FUNCTION__
))
;
1273 if (auto *C = dyn_cast_or_null<ConstantInt>(
1274 simplifyCastInst(CI->getOpcode(), OpConst,
1275 CI->getDestTy(), DL))) {
1276 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1277 }
1278 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1279 bool Op0Match = BO->getOperand(0) == Op;
1280 bool Op1Match = BO->getOperand(1) == Op;
1281 assert((Op0Match || Op1Match) &&(static_cast <bool> ((Op0Match || Op1Match) && "Operand 0 nor Operand 1 isn't a match"
) ? void (0) : __assert_fail ("(Op0Match || Op1Match) && \"Operand 0 nor Operand 1 isn't a match\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1282, __extension__ __PRETTY_FUNCTION__
))
1282 "Operand 0 nor Operand 1 isn't a match")(static_cast <bool> ((Op0Match || Op1Match) && "Operand 0 nor Operand 1 isn't a match"
) ? void (0) : __assert_fail ("(Op0Match || Op1Match) && \"Operand 0 nor Operand 1 isn't a match\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1282, __extension__ __PRETTY_FUNCTION__
))
;
1283 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1284 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1285 if (auto *C = dyn_cast_or_null<ConstantInt>(
1286 simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1287 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1288 }
1289 } else if (isa<FreezeInst>(Usr)) {
1290 assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op")(static_cast <bool> (cast<FreezeInst>(Usr)->getOperand
(0) == Op && "Operand 0 isn't Op") ? void (0) : __assert_fail
("cast<FreezeInst>(Usr)->getOperand(0) == Op && \"Operand 0 isn't Op\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1290, __extension__ __PRETTY_FUNCTION__
))
;
1291 return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1292 }
1293 return ValueLatticeElement::getOverdefined();
1294}
1295
1296/// Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1297/// Val is not constrained on the edge. Result is unspecified if return value
1298/// is false.
1299static Optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
1300 BasicBlock *BBFrom,
1301 BasicBlock *BBTo) {
1302 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1303 // know that v != 0.
1304 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1305 // If this is a conditional branch and only one successor goes to BBTo, then
1306 // we may be able to infer something from the condition.
1307 if (BI->isConditional() &&
1308 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1309 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1310 assert(BI->getSuccessor(!isTrueDest) == BBTo &&(static_cast <bool> (BI->getSuccessor(!isTrueDest) ==
BBTo && "BBTo isn't a successor of BBFrom") ? void (
0) : __assert_fail ("BI->getSuccessor(!isTrueDest) == BBTo && \"BBTo isn't a successor of BBFrom\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1311, __extension__ __PRETTY_FUNCTION__
))
1311 "BBTo isn't a successor of BBFrom")(static_cast <bool> (BI->getSuccessor(!isTrueDest) ==
BBTo && "BBTo isn't a successor of BBFrom") ? void (
0) : __assert_fail ("BI->getSuccessor(!isTrueDest) == BBTo && \"BBTo isn't a successor of BBFrom\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1311, __extension__ __PRETTY_FUNCTION__
))
;
1312 Value *Condition = BI->getCondition();
1313
1314 // If V is the condition of the branch itself, then we know exactly what
1315 // it is.
1316 if (Condition == Val)
1317 return ValueLatticeElement::get(ConstantInt::get(
1318 Type::getInt1Ty(Val->getContext()), isTrueDest));
1319
1320 // If the condition of the branch is an equality comparison, we may be
1321 // able to infer the value.
1322 ValueLatticeElement Result = getValueFromCondition(Val, Condition,
1323 isTrueDest);
1324 if (!Result.isOverdefined())
1325 return Result;
1326
1327 if (User *Usr = dyn_cast<User>(Val)) {
1328 assert(Result.isOverdefined() && "Result isn't overdefined")(static_cast <bool> (Result.isOverdefined() && "Result isn't overdefined"
) ? void (0) : __assert_fail ("Result.isOverdefined() && \"Result isn't overdefined\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1328, __extension__ __PRETTY_FUNCTION__
))
;
1329 // Check with isOperationFoldable() first to avoid linearly iterating
1330 // over the operands unnecessarily which can be expensive for
1331 // instructions with many operands.
1332 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1333 const DataLayout &DL = BBTo->getModule()->getDataLayout();
1334 if (usesOperand(Usr, Condition)) {
1335 // If Val has Condition as an operand and Val can be folded into a
1336 // constant with either Condition == true or Condition == false,
1337 // propagate the constant.
1338 // eg.
1339 // ; %Val is true on the edge to %then.
1340 // %Val = and i1 %Condition, true.
1341 // br %Condition, label %then, label %else
1342 APInt ConditionVal(1, isTrueDest ? 1 : 0);
1343 Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1344 } else {
1345 // If one of Val's operand has an inferred value, we may be able to
1346 // infer the value of Val.
1347 // eg.
1348 // ; %Val is 94 on the edge to %then.
1349 // %Val = add i8 %Op, 1
1350 // %Condition = icmp eq i8 %Op, 93
1351 // br i1 %Condition, label %then, label %else
1352 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1353 Value *Op = Usr->getOperand(i);
1354 ValueLatticeElement OpLatticeVal =
1355 getValueFromCondition(Op, Condition, isTrueDest);
1356 if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
1357 Result = constantFoldUser(Usr, Op, *OpConst, DL);
1358 break;
1359 }
1360 }
1361 }
1362 }
1363 }
1364 if (!Result.isOverdefined())
1365 return Result;
1366 }
1367 }
1368
1369 // If the edge was formed by a switch on the value, then we may know exactly
1370 // what it is.
1371 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1372 Value *Condition = SI->getCondition();
1373 if (!isa<IntegerType>(Val->getType()))
1374 return None;
1375 bool ValUsesConditionAndMayBeFoldable = false;
1376 if (Condition != Val) {
1377 // Check if Val has Condition as an operand.
1378 if (User *Usr = dyn_cast<User>(Val))
1379 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1380 usesOperand(Usr, Condition);
1381 if (!ValUsesConditionAndMayBeFoldable)
1382 return None;
1383 }
1384 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&(static_cast <bool> ((Condition == Val || ValUsesConditionAndMayBeFoldable
) && "Condition != Val nor Val doesn't use Condition"
) ? void (0) : __assert_fail ("(Condition == Val || ValUsesConditionAndMayBeFoldable) && \"Condition != Val nor Val doesn't use Condition\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1385, __extension__ __PRETTY_FUNCTION__
))
1385 "Condition != Val nor Val doesn't use Condition")(static_cast <bool> ((Condition == Val || ValUsesConditionAndMayBeFoldable
) && "Condition != Val nor Val doesn't use Condition"
) ? void (0) : __assert_fail ("(Condition == Val || ValUsesConditionAndMayBeFoldable) && \"Condition != Val nor Val doesn't use Condition\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1385, __extension__ __PRETTY_FUNCTION__
))
;
1386
1387 bool DefaultCase = SI->getDefaultDest() == BBTo;
1388 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1389 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1390
1391 for (auto Case : SI->cases()) {
1392 APInt CaseValue = Case.getCaseValue()->getValue();
1393 ConstantRange EdgeVal(CaseValue);
1394 if (ValUsesConditionAndMayBeFoldable) {
1395 User *Usr = cast<User>(Val);
1396 const DataLayout &DL = BBTo->getModule()->getDataLayout();
1397 ValueLatticeElement EdgeLatticeVal =
1398 constantFoldUser(Usr, Condition, CaseValue, DL);
1399 if (EdgeLatticeVal.isOverdefined())
1400 return None;
1401 EdgeVal = EdgeLatticeVal.getConstantRange();
1402 }
1403 if (DefaultCase) {
1404 // It is possible that the default destination is the destination of
1405 // some cases. We cannot perform difference for those cases.
1406 // We know Condition != CaseValue in BBTo. In some cases we can use
1407 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1408 // only do this when f is identity (i.e. Val == Condition), but we
1409 // should be able to do this for any injective f.
1410 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1411 EdgesVals = EdgesVals.difference(EdgeVal);
1412 } else if (Case.getCaseSuccessor() == BBTo)
1413 EdgesVals = EdgesVals.unionWith(EdgeVal);
1414 }
1415 return ValueLatticeElement::getRange(std::move(EdgesVals));
1416 }
1417 return None;
1418}
1419
1420/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1421/// the basic block if the edge does not constrain Val.
1422Optional<ValueLatticeElement> LazyValueInfoImpl::getEdgeValue(
1423 Value *Val, BasicBlock *BBFrom, BasicBlock *BBTo, Instruction *CxtI) {
1424 // If already a constant, there is nothing to compute.
1425 if (Constant *VC = dyn_cast<Constant>(Val))
1426 return ValueLatticeElement::get(VC);
1427
1428 ValueLatticeElement LocalResult =
1429 getEdgeValueLocal(Val, BBFrom, BBTo)
1430 .value_or(ValueLatticeElement::getOverdefined());
1431 if (hasSingleValue(LocalResult))
1432 // Can't get any more precise here
1433 return LocalResult;
1434
1435 Optional<ValueLatticeElement> OptInBlock =
1436 getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1437 if (!OptInBlock)
1438 return None;
1439 ValueLatticeElement &InBlock = *OptInBlock;
1440
1441 // We can use the context instruction (generically the ultimate instruction
1442 // the calling pass is trying to simplify) here, even though the result of
1443 // this function is generally cached when called from the solve* functions
1444 // (and that cached result might be used with queries using a different
1445 // context instruction), because when this function is called from the solve*
1446 // functions, the context instruction is not provided. When called from
1447 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1448 // but then the result is not cached.
1449 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1450
1451 return intersect(LocalResult, InBlock);
1452}
1453
1454ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1455 Instruction *CxtI) {
1456 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting block end value "
<< *V << " at '" << BB->getName() <<
"'\n"; } } while (false)
1457 << BB->getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting block end value "
<< *V << " at '" << BB->getName() <<
"'\n"; } } while (false)
;
1458
1459 assert(BlockValueStack.empty() && BlockValueSet.empty())(static_cast <bool> (BlockValueStack.empty() &&
BlockValueSet.empty()) ? void (0) : __assert_fail ("BlockValueStack.empty() && BlockValueSet.empty()"
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1459, __extension__ __PRETTY_FUNCTION__
))
;
1460 Optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1461 if (!OptResult) {
1462 solve();
1463 OptResult = getBlockValue(V, BB, CxtI);
1464 assert(OptResult && "Value not available after solving")(static_cast <bool> (OptResult && "Value not available after solving"
) ? void (0) : __assert_fail ("OptResult && \"Value not available after solving\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1464, __extension__ __PRETTY_FUNCTION__
))
;
1465 }
1466
1467 ValueLatticeElement Result = *OptResult;
1468 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
Result << "\n"; } } while (false)
;
1469 return Result;
1470}
1471
1472ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1473 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting value " <<
*V << " at '" << CxtI->getName() << "'\n"
; } } while (false)
1474 << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting value " <<
*V << " at '" << CxtI->getName() << "'\n"
; } } while (false)
;
1475
1476 if (auto *C = dyn_cast<Constant>(V))
1477 return ValueLatticeElement::get(C);
1478
1479 ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
1480 if (auto *I = dyn_cast<Instruction>(V))
1481 Result = getFromRangeMetadata(I);
1482 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1483
1484 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
Result << "\n"; } } while (false)
;
1485 return Result;
1486}
1487
1488ValueLatticeElement LazyValueInfoImpl::
1489getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1490 Instruction *CxtI) {
1491 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
2
Assuming 'DebugFlag' is false
3
Loop condition is false. Exiting loop
1492 << FromBB->getName() << "' to '" << ToBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
1493 << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
;
1494
1495 Optional<ValueLatticeElement> Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1496 if (!Result) {
4
Taking true branch
1497 solve();
1498 Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1499 assert(Result && "More work to do after problem solved?")(static_cast <bool> (Result && "More work to do after problem solved?"
) ? void (0) : __assert_fail ("Result && \"More work to do after problem solved?\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1499, __extension__ __PRETTY_FUNCTION__
))
;
5
'?' condition is true
1500 }
1501
1502 LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
*Result << "\n"; } } while (false)
;
6
Assuming 'DebugFlag' is false
7
Loop condition is false. Exiting loop
1503 return *Result;
8
Calling copy constructor for 'ValueLatticeElement'
12
Returning from copy constructor for 'ValueLatticeElement'
1504}
1505
1506void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1507 BasicBlock *NewSucc) {
1508 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1509}
1510
1511//===----------------------------------------------------------------------===//
1512// LazyValueInfo Impl
1513//===----------------------------------------------------------------------===//
1514
1515/// This lazily constructs the LazyValueInfoImpl.
1516static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1517 const Module *M) {
1518 if (!PImpl) {
1519 assert(M && "getCache() called with a null Module")(static_cast <bool> (M && "getCache() called with a null Module"
) ? void (0) : __assert_fail ("M && \"getCache() called with a null Module\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1519, __extension__ __PRETTY_FUNCTION__
))
;
1520 const DataLayout &DL = M->getDataLayout();
1521 Function *GuardDecl = M->getFunction(
1522 Intrinsic::getName(Intrinsic::experimental_guard));
1523 PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
1524 }
1525 return *static_cast<LazyValueInfoImpl*>(PImpl);
1526}
1527
1528bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1529 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1530 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1531
1532 if (Info.PImpl)
1533 getImpl(Info.PImpl, Info.AC, F.getParent()).clear();
1534
1535 // Fully lazy.
1536 return false;
1537}
1538
1539void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1540 AU.setPreservesAll();
1541 AU.addRequired<AssumptionCacheTracker>();
1542 AU.addRequired<TargetLibraryInfoWrapperPass>();
1543}
1544
1545LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1546
1547LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1548
1549void LazyValueInfo::releaseMemory() {
1550 // If the cache was allocated, free it.
1551 if (PImpl) {
1552 delete &getImpl(PImpl, AC, nullptr);
1553 PImpl = nullptr;
1554 }
1555}
1556
1557bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1558 FunctionAnalysisManager::Invalidator &Inv) {
1559 // We need to invalidate if we have either failed to preserve this analyses
1560 // result directly or if any of its dependencies have been invalidated.
1561 auto PAC = PA.getChecker<LazyValueAnalysis>();
1562 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1563 return true;
1564
1565 return false;
1566}
1567
1568void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1569
1570LazyValueInfo LazyValueAnalysis::run(Function &F,
1571 FunctionAnalysisManager &FAM) {
1572 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1573 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1574
1575 return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI);
1576}
1577
1578/// Returns true if we can statically tell that this value will never be a
1579/// "useful" constant. In practice, this means we've got something like an
1580/// alloca or a malloc call for which a comparison against a constant can
1581/// only be guarding dead code. Note that we are potentially giving up some
1582/// precision in dead code (a constant result) in favour of avoiding a
1583/// expensive search for a easily answered common query.
1584static bool isKnownNonConstant(Value *V) {
1585 V = V->stripPointerCasts();
1586 // The return val of alloc cannot be a Constant.
1587 if (isa<AllocaInst>(V))
1588 return true;
1589 return false;
1590}
1591
1592Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
1593 // Bail out early if V is known not to be a Constant.
1594 if (isKnownNonConstant(V))
1595 return nullptr;
1596
1597 BasicBlock *BB = CxtI->getParent();
1598 ValueLatticeElement Result =
1599 getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1600
1601 if (Result.isConstant())
1602 return Result.getConstant();
1603 if (Result.isConstantRange()) {
1604 const ConstantRange &CR = Result.getConstantRange();
1605 if (const APInt *SingleVal = CR.getSingleElement())
1606 return ConstantInt::get(V->getContext(), *SingleVal);
1607 }
1608 return nullptr;
1609}
1610
1611ConstantRange LazyValueInfo::getConstantRange(Value *V, Instruction *CxtI,
1612 bool UndefAllowed) {
1613 assert(V->getType()->isIntegerTy())(static_cast <bool> (V->getType()->isIntegerTy())
? void (0) : __assert_fail ("V->getType()->isIntegerTy()"
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1613, __extension__ __PRETTY_FUNCTION__
))
;
1614 unsigned Width = V->getType()->getIntegerBitWidth();
1615 BasicBlock *BB = CxtI->getParent();
1616 ValueLatticeElement Result =
1617 getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1618 if (Result.isUnknown())
1619 return ConstantRange::getEmpty(Width);
1620 if (Result.isConstantRange(UndefAllowed))
1621 return Result.getConstantRange(UndefAllowed);
1622 // We represent ConstantInt constants as constant ranges but other kinds
1623 // of integer constants, i.e. ConstantExpr will be tagged as constants
1624 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1625, __extension__ __PRETTY_FUNCTION__
))
1625 "ConstantInt value must be represented as constantrange")(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1625, __extension__ __PRETTY_FUNCTION__
))
;
1626 return ConstantRange::getFull(Width);
1627}
1628
1629/// Determine whether the specified value is known to be a
1630/// constant on the specified edge. Return null if not.
1631Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1632 BasicBlock *ToBB,
1633 Instruction *CxtI) {
1634 Module *M = FromBB->getModule();
1635 ValueLatticeElement Result =
1636 getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1
Calling 'LazyValueInfoImpl::getValueOnEdge'
13
Returning from 'LazyValueInfoImpl::getValueOnEdge'
1637
1638 if (Result.isConstant())
14
Assuming the condition is true
15
Taking true branch
1639 return Result.getConstant();
16
Calling 'ValueLatticeElement::getConstant'
1640 if (Result.isConstantRange()) {
1641 const ConstantRange &CR = Result.getConstantRange();
1642 if (const APInt *SingleVal = CR.getSingleElement())
1643 return ConstantInt::get(V->getContext(), *SingleVal);
1644 }
1645 return nullptr;
1646}
1647
1648ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1649 BasicBlock *FromBB,
1650 BasicBlock *ToBB,
1651 Instruction *CxtI) {
1652 unsigned Width = V->getType()->getIntegerBitWidth();
1653 Module *M = FromBB->getModule();
1654 ValueLatticeElement Result =
1655 getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1656
1657 if (Result.isUnknown())
1658 return ConstantRange::getEmpty(Width);
1659 if (Result.isConstantRange())
1660 return Result.getConstantRange();
1661 // We represent ConstantInt constants as constant ranges but other kinds
1662 // of integer constants, i.e. ConstantExpr will be tagged as constants
1663 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1664, __extension__ __PRETTY_FUNCTION__
))
1664 "ConstantInt value must be represented as constantrange")(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1664, __extension__ __PRETTY_FUNCTION__
))
;
1665 return ConstantRange::getFull(Width);
1666}
1667
1668static LazyValueInfo::Tristate
1669getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
1670 const DataLayout &DL, TargetLibraryInfo *TLI) {
1671 // If we know the value is a constant, evaluate the conditional.
1672 Constant *Res = nullptr;
1673 if (Val.isConstant()) {
1674 Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
1675 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1676 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1677 return LazyValueInfo::Unknown;
1678 }
1679
1680 if (Val.isConstantRange()) {
1681 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1682 if (!CI) return LazyValueInfo::Unknown;
1683
1684 const ConstantRange &CR = Val.getConstantRange();
1685 if (Pred == ICmpInst::ICMP_EQ) {
1686 if (!CR.contains(CI->getValue()))
1687 return LazyValueInfo::False;
1688
1689 if (CR.isSingleElement())
1690 return LazyValueInfo::True;
1691 } else if (Pred == ICmpInst::ICMP_NE) {
1692 if (!CR.contains(CI->getValue()))
1693 return LazyValueInfo::True;
1694
1695 if (CR.isSingleElement())
1696 return LazyValueInfo::False;
1697 } else {
1698 // Handle more complex predicates.
1699 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1700 (ICmpInst::Predicate)Pred, CI->getValue());
1701 if (TrueValues.contains(CR))
1702 return LazyValueInfo::True;
1703 if (TrueValues.inverse().contains(CR))
1704 return LazyValueInfo::False;
1705 }
1706 return LazyValueInfo::Unknown;
1707 }
1708
1709 if (Val.isNotConstant()) {
1710 // If this is an equality comparison, we can try to fold it knowing that
1711 // "V != C1".
1712 if (Pred == ICmpInst::ICMP_EQ) {
1713 // !C1 == C -> false iff C1 == C.
1714 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1715 Val.getNotConstant(), C, DL,
1716 TLI);
1717 if (Res->isNullValue())
1718 return LazyValueInfo::False;
1719 } else if (Pred == ICmpInst::ICMP_NE) {
1720 // !C1 != C -> true iff C1 == C.
1721 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1722 Val.getNotConstant(), C, DL,
1723 TLI);
1724 if (Res->isNullValue())
1725 return LazyValueInfo::True;
1726 }
1727 return LazyValueInfo::Unknown;
1728 }
1729
1730 return LazyValueInfo::Unknown;
1731}
1732
1733/// Determine whether the specified value comparison with a constant is known to
1734/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1735LazyValueInfo::Tristate
1736LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1737 BasicBlock *FromBB, BasicBlock *ToBB,
1738 Instruction *CxtI) {
1739 Module *M = FromBB->getModule();
1740 ValueLatticeElement Result =
1741 getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1742
1743 return getPredicateResult(Pred, C, Result, M->getDataLayout(), TLI);
1744}
1745
1746LazyValueInfo::Tristate
1747LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1748 Instruction *CxtI, bool UseBlockValue) {
1749 // Is or is not NonNull are common predicates being queried. If
1750 // isKnownNonZero can tell us the result of the predicate, we can
1751 // return it quickly. But this is only a fastpath, and falling
1752 // through would still be correct.
1753 Module *M = CxtI->getModule();
1754 const DataLayout &DL = M->getDataLayout();
1755 if (V->getType()->isPointerTy() && C->isNullValue() &&
1756 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1757 if (Pred == ICmpInst::ICMP_EQ)
1758 return LazyValueInfo::False;
1759 else if (Pred == ICmpInst::ICMP_NE)
1760 return LazyValueInfo::True;
1761 }
1762
1763 ValueLatticeElement Result = UseBlockValue
1764 ? getImpl(PImpl, AC, M).getValueInBlock(V, CxtI->getParent(), CxtI)
1765 : getImpl(PImpl, AC, M).getValueAt(V, CxtI);
1766 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1767 if (Ret != Unknown)
1768 return Ret;
1769
1770 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1771 // LVI as a whole tries to compute a lattice value which is conservatively
1772 // correct at a given location. In this case, we have a predicate which we
1773 // weren't able to prove about the merged result, and we're pushing that
1774 // predicate back along each incoming edge to see if we can prove it
1775 // separately for each input. As a motivating example, consider:
1776 // bb1:
1777 // %v1 = ... ; constantrange<1, 5>
1778 // br label %merge
1779 // bb2:
1780 // %v2 = ... ; constantrange<10, 20>
1781 // br label %merge
1782 // merge:
1783 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1784 // %pred = icmp eq i32 %phi, 8
1785 // We can't tell from the lattice value for '%phi' that '%pred' is false
1786 // along each path, but by checking the predicate over each input separately,
1787 // we can.
1788 // We limit the search to one step backwards from the current BB and value.
1789 // We could consider extending this to search further backwards through the
1790 // CFG and/or value graph, but there are non-obvious compile time vs quality
1791 // tradeoffs.
1792 BasicBlock *BB = CxtI->getParent();
1793
1794 // Function entry or an unreachable block. Bail to avoid confusing
1795 // analysis below.
1796 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1797 if (PI == PE)
1798 return Unknown;
1799
1800 // If V is a PHI node in the same block as the context, we need to ask
1801 // questions about the predicate as applied to the incoming value along
1802 // each edge. This is useful for eliminating cases where the predicate is
1803 // known along all incoming edges.
1804 if (auto *PHI = dyn_cast<PHINode>(V))
1805 if (PHI->getParent() == BB) {
1806 Tristate Baseline = Unknown;
1807 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1808 Value *Incoming = PHI->getIncomingValue(i);
1809 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1810 // Note that PredBB may be BB itself.
1811 Tristate Result =
1812 getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
1813
1814 // Keep going as long as we've seen a consistent known result for
1815 // all inputs.
1816 Baseline = (i == 0) ? Result /* First iteration */
1817 : (Baseline == Result ? Baseline
1818 : Unknown); /* All others */
1819 if (Baseline == Unknown)
1820 break;
1821 }
1822 if (Baseline != Unknown)
1823 return Baseline;
1824 }
1825
1826 // For a comparison where the V is outside this block, it's possible
1827 // that we've branched on it before. Look to see if the value is known
1828 // on all incoming edges.
1829 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
1830 // For predecessor edge, determine if the comparison is true or false
1831 // on that edge. If they're all true or all false, we can conclude
1832 // the value of the comparison in this block.
1833 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1834 if (Baseline != Unknown) {
1835 // Check that all remaining incoming values match the first one.
1836 while (++PI != PE) {
1837 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1838 if (Ret != Baseline)
1839 break;
1840 }
1841 // If we terminated early, then one of the values didn't match.
1842 if (PI == PE) {
1843 return Baseline;
1844 }
1845 }
1846 }
1847
1848 return Unknown;
1849}
1850
1851LazyValueInfo::Tristate LazyValueInfo::getPredicateAt(unsigned P, Value *LHS,
1852 Value *RHS,
1853 Instruction *CxtI,
1854 bool UseBlockValue) {
1855 CmpInst::Predicate Pred = (CmpInst::Predicate)P;
1856
1857 if (auto *C = dyn_cast<Constant>(RHS))
1858 return getPredicateAt(P, LHS, C, CxtI, UseBlockValue);
1859 if (auto *C = dyn_cast<Constant>(LHS))
1860 return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1861 UseBlockValue);
1862
1863 // Got two non-Constant values. Try to determine the comparison results based
1864 // on the block values of the two operands, e.g. because they have
1865 // non-overlapping ranges.
1866 if (UseBlockValue) {
1867 Module *M = CxtI->getModule();
1868 ValueLatticeElement L =
1869 getImpl(PImpl, AC, M).getValueInBlock(LHS, CxtI->getParent(), CxtI);
1870 if (L.isOverdefined())
1871 return LazyValueInfo::Unknown;
1872
1873 ValueLatticeElement R =
1874 getImpl(PImpl, AC, M).getValueInBlock(RHS, CxtI->getParent(), CxtI);
1875 Type *Ty = CmpInst::makeCmpResultType(LHS->getType());
1876 if (Constant *Res = L.getCompare((CmpInst::Predicate)P, Ty, R,
1877 M->getDataLayout())) {
1878 if (Res->isNullValue())
1879 return LazyValueInfo::False;
1880 if (Res->isOneValue())
1881 return LazyValueInfo::True;
1882 }
1883 }
1884 return LazyValueInfo::Unknown;
1885}
1886
1887void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1888 BasicBlock *NewSucc) {
1889 if (PImpl) {
1890 getImpl(PImpl, AC, PredBB->getModule())
1891 .threadEdge(PredBB, OldSucc, NewSucc);
1892 }
1893}
1894
1895void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1896 if (PImpl) {
1897 getImpl(PImpl, AC, BB->getModule()).eraseBlock(BB);
1898 }
1899}
1900
1901void LazyValueInfo::clear(const Module *M) {
1902 if (PImpl) {
1903 getImpl(PImpl, AC, M).clear();
1904 }
1905}
1906
1907void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
1908 if (PImpl) {
1909 getImpl(PImpl, AC, F.getParent()).printLVI(F, DTree, OS);
1910 }
1911}
1912
1913// Print the LVI for the function arguments at the start of each basic block.
1914void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
1915 const BasicBlock *BB, formatted_raw_ostream &OS) {
1916 // Find if there are latticevalues defined for arguments of the function.
1917 auto *F = BB->getParent();
1918 for (const auto &Arg : F->args()) {
1919 ValueLatticeElement Result = LVIImpl->getValueInBlock(
1920 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
1921 if (Result.isUnknown())
1922 continue;
1923 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
1924 }
1925}
1926
1927// This function prints the LVI analysis for the instruction I at the beginning
1928// of various basic blocks. It relies on calculated values that are stored in
1929// the LazyValueInfoCache, and in the absence of cached values, recalculate the
1930// LazyValueInfo for `I`, and print that info.
1931void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
1932 const Instruction *I, formatted_raw_ostream &OS) {
1933
1934 auto *ParentBB = I->getParent();
1935 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
1936 // We can generate (solve) LVI values only for blocks that are dominated by
1937 // the I's parent. However, to avoid generating LVI for all dominating blocks,
1938 // that contain redundant/uninteresting information, we print LVI for
1939 // blocks that may use this LVI information (such as immediate successor
1940 // blocks, and blocks that contain uses of `I`).
1941 auto printResult = [&](const BasicBlock *BB) {
1942 if (!BlocksContainingLVI.insert(BB).second)
1943 return;
1944 ValueLatticeElement Result = LVIImpl->getValueInBlock(
1945 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
1946 OS << "; LatticeVal for: '" << *I << "' in BB: '";
1947 BB->printAsOperand(OS, false);
1948 OS << "' is: " << Result << "\n";
1949 };
1950
1951 printResult(ParentBB);
1952 // Print the LVI analysis results for the immediate successor blocks, that
1953 // are dominated by `ParentBB`.
1954 for (const auto *BBSucc : successors(ParentBB))
1955 if (DT.dominates(ParentBB, BBSucc))
1956 printResult(BBSucc);
1957
1958 // Print LVI in blocks where `I` is used.
1959 for (const auto *U : I->users())
1960 if (auto *UseI = dyn_cast<Instruction>(U))
1961 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
1962 printResult(UseI->getParent());
1963
1964}
1965
1966namespace {
1967// Printer class for LazyValueInfo results.
1968class LazyValueInfoPrinter : public FunctionPass {
1969public:
1970 static char ID; // Pass identification, replacement for typeid
1971 LazyValueInfoPrinter() : FunctionPass(ID) {
1972 initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
1973 }
1974
1975 void getAnalysisUsage(AnalysisUsage &AU) const override {
1976 AU.setPreservesAll();
1977 AU.addRequired<LazyValueInfoWrapperPass>();
1978 AU.addRequired<DominatorTreeWrapperPass>();
1979 }
1980
1981 // Get the mandatory dominator tree analysis and pass this in to the
1982 // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
1983 bool runOnFunction(Function &F) override {
1984 dbgs() << "LVI for function '" << F.getName() << "':\n";
1985 auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1986 auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1987 LVI.printLVI(F, DTree, dbgs());
1988 return false;
1989 }
1990};
1991}
1992
1993char LazyValueInfoPrinter::ID = 0;
1994INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",static void *initializeLazyValueInfoPrinterPassOnce(PassRegistry
&Registry) {
1995 "Lazy Value Info Printer Pass", false, false)static void *initializeLazyValueInfoPrinterPassOnce(PassRegistry
&Registry) {
1996INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)initializeLazyValueInfoWrapperPassPass(Registry);
1997INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",PassInfo *PI = new PassInfo( "Lazy Value Info Printer Pass", "print-lazy-value-info"
, &LazyValueInfoPrinter::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LazyValueInfoPrinter>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLazyValueInfoPrinterPassFlag
; void llvm::initializeLazyValueInfoPrinterPass(PassRegistry &
Registry) { llvm::call_once(InitializeLazyValueInfoPrinterPassFlag
, initializeLazyValueInfoPrinterPassOnce, std::ref(Registry))
; }
1998 "Lazy Value Info Printer Pass", false, false)PassInfo *PI = new PassInfo( "Lazy Value Info Printer Pass", "print-lazy-value-info"
, &LazyValueInfoPrinter::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LazyValueInfoPrinter>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLazyValueInfoPrinterPassFlag
; void llvm::initializeLazyValueInfoPrinterPass(PassRegistry &
Registry) { llvm::call_once(InitializeLazyValueInfoPrinterPassFlag
, initializeLazyValueInfoPrinterPassOnce, std::ref(Registry))
; }

/build/source/llvm/include/llvm/Analysis/ValueLattice.h

1//===- ValueLattice.h - Value constraint analysis ---------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_ANALYSIS_VALUELATTICE_H
10#define LLVM_ANALYSIS_VALUELATTICE_H
11
12#include "llvm/IR/Constants.h"
13#include "llvm/IR/ConstantRange.h"
14#include "llvm/IR/Instructions.h"
15
16//===----------------------------------------------------------------------===//
17// ValueLatticeElement
18//===----------------------------------------------------------------------===//
19
20namespace llvm {
21
22class Constant;
23
24/// This class represents lattice values for constants.
25///
26/// FIXME: This is basically just for bringup, this can be made a lot more rich
27/// in the future.
28///
29class ValueLatticeElement {
30 enum ValueLatticeElementTy {
31 /// This Value has no known value yet. As a result, this implies the
32 /// producing instruction is dead. Caution: We use this as the starting
33 /// state in our local meet rules. In this usage, it's taken to mean
34 /// "nothing known yet".
35 /// Transition to any other state allowed.
36 unknown,
37
38 /// This Value is an UndefValue constant or produces undef. Undefined values
39 /// can be merged with constants (or single element constant ranges),
40 /// assuming all uses of the result will be replaced.
41 /// Transition allowed to the following states:
42 /// constant
43 /// constantrange_including_undef
44 /// overdefined
45 undef,
46
47 /// This Value has a specific constant value. The constant cannot be undef.
48 /// (For constant integers, constantrange is used instead. Integer typed
49 /// constantexprs can appear as constant.) Note that the constant state
50 /// can be reached by merging undef & constant states.
51 /// Transition allowed to the following states:
52 /// overdefined
53 constant,
54
55 /// This Value is known to not have the specified value. (For constant
56 /// integers, constantrange is used instead. As above, integer typed
57 /// constantexprs can appear here.)
58 /// Transition allowed to the following states:
59 /// overdefined
60 notconstant,
61
62 /// The Value falls within this range. (Used only for integer typed values.)
63 /// Transition allowed to the following states:
64 /// constantrange (new range must be a superset of the existing range)
65 /// constantrange_including_undef
66 /// overdefined
67 constantrange,
68
69 /// This Value falls within this range, but also may be undef.
70 /// Merging it with other constant ranges results in
71 /// constantrange_including_undef.
72 /// Transition allowed to the following states:
73 /// overdefined
74 constantrange_including_undef,
75
76 /// We can not precisely model the dynamic values this value might take.
77 /// No transitions are allowed after reaching overdefined.
78 overdefined,
79 };
80
81 ValueLatticeElementTy Tag : 8;
82 /// Number of times a constant range has been extended with widening enabled.
83 unsigned NumRangeExtensions : 8;
84
85 /// The union either stores a pointer to a constant or a constant range,
86 /// associated to the lattice element. We have to ensure that Range is
87 /// initialized or destroyed when changing state to or from constantrange.
88 union {
89 Constant *ConstVal;
90 ConstantRange Range;
91 };
92
93 /// Destroy contents of lattice value, without destructing the object.
94 void destroy() {
95 switch (Tag) {
96 case overdefined:
97 case unknown:
98 case undef:
99 case constant:
100 case notconstant:
101 break;
102 case constantrange_including_undef:
103 case constantrange:
104 Range.~ConstantRange();
105 break;
106 };
107 }
108
109public:
110 /// Struct to control some aspects related to merging constant ranges.
111 struct MergeOptions {
112 /// The merge value may include undef.
113 bool MayIncludeUndef;
114
115 /// Handle repeatedly extending a range by going to overdefined after a
116 /// number of steps.
117 bool CheckWiden;
118
119 /// The number of allowed widening steps (including setting the range
120 /// initially).
121 unsigned MaxWidenSteps;
122
123 MergeOptions() : MergeOptions(false, false) {}
124
125 MergeOptions(bool MayIncludeUndef, bool CheckWiden,
126 unsigned MaxWidenSteps = 1)
127 : MayIncludeUndef(MayIncludeUndef), CheckWiden(CheckWiden),
128 MaxWidenSteps(MaxWidenSteps) {}
129
130 MergeOptions &setMayIncludeUndef(bool V = true) {
131 MayIncludeUndef = V;
132 return *this;
133 }
134
135 MergeOptions &setCheckWiden(bool V = true) {
136 CheckWiden = V;
137 return *this;
138 }
139
140 MergeOptions &setMaxWidenSteps(unsigned Steps = 1) {
141 CheckWiden = true;
142 MaxWidenSteps = Steps;
143 return *this;
144 }
145 };
146
147 // ConstVal and Range are initialized on-demand.
148 ValueLatticeElement() : Tag(unknown), NumRangeExtensions(0) {}
149
150 ~ValueLatticeElement() { destroy(); }
151
152 ValueLatticeElement(const ValueLatticeElement &Other)
153 : Tag(Other.Tag), NumRangeExtensions(0) {
154 switch (Other.Tag) {
9
Control jumps to 'case undef:' at line 166
10
Execution continues on line 154
155 case constantrange:
156 case constantrange_including_undef:
157 new (&Range) ConstantRange(Other.Range);
158 NumRangeExtensions = Other.NumRangeExtensions;
159 break;
160 case constant:
161 case notconstant:
162 ConstVal = Other.ConstVal;
163 break;
164 case overdefined:
165 case unknown:
166 case undef:
167 break;
168 }
169 }
11
Returning without writing to 'this->.ConstVal'
170
171 ValueLatticeElement(ValueLatticeElement &&Other)
172 : Tag(Other.Tag), NumRangeExtensions(0) {
173 switch (Other.Tag) {
174 case constantrange:
175 case constantrange_including_undef:
176 new (&Range) ConstantRange(std::move(Other.Range));
177 NumRangeExtensions = Other.NumRangeExtensions;
178 break;
179 case constant:
180 case notconstant:
181 ConstVal = Other.ConstVal;
182 break;
183 case overdefined:
184 case unknown:
185 case undef:
186 break;
187 }
188 Other.Tag = unknown;
189 }
190
191 ValueLatticeElement &operator=(const ValueLatticeElement &Other) {
192 destroy();
193 new (this) ValueLatticeElement(Other);
194 return *this;
195 }
196
197 ValueLatticeElement &operator=(ValueLatticeElement &&Other) {
198 destroy();
199 new (this) ValueLatticeElement(std::move(Other));
200 return *this;
201 }
202
203 static ValueLatticeElement get(Constant *C) {
204 ValueLatticeElement Res;
205 if (isa<UndefValue>(C))
206 Res.markUndef();
207 else
208 Res.markConstant(C);
209 return Res;
210 }
211 static ValueLatticeElement getNot(Constant *C) {
212 ValueLatticeElement Res;
213 assert(!isa<UndefValue>(C) && "!= undef is not supported")(static_cast <bool> (!isa<UndefValue>(C) &&
"!= undef is not supported") ? void (0) : __assert_fail ("!isa<UndefValue>(C) && \"!= undef is not supported\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 213, __extension__
__PRETTY_FUNCTION__))
;
214 Res.markNotConstant(C);
215 return Res;
216 }
217 static ValueLatticeElement getRange(ConstantRange CR,
218 bool MayIncludeUndef = false) {
219 if (CR.isFullSet())
220 return getOverdefined();
221
222 if (CR.isEmptySet()) {
223 ValueLatticeElement Res;
224 if (MayIncludeUndef)
225 Res.markUndef();
226 return Res;
227 }
228
229 ValueLatticeElement Res;
230 Res.markConstantRange(std::move(CR),
231 MergeOptions().setMayIncludeUndef(MayIncludeUndef));
232 return Res;
233 }
234 static ValueLatticeElement getOverdefined() {
235 ValueLatticeElement Res;
236 Res.markOverdefined();
237 return Res;
238 }
239
240 bool isUndef() const { return Tag == undef; }
241 bool isUnknown() const { return Tag == unknown; }
242 bool isUnknownOrUndef() const { return Tag == unknown || Tag == undef; }
243 bool isConstant() const { return Tag == constant; }
244 bool isNotConstant() const { return Tag == notconstant; }
245 bool isConstantRangeIncludingUndef() const {
246 return Tag == constantrange_including_undef;
247 }
248 /// Returns true if this value is a constant range. Use \p UndefAllowed to
249 /// exclude non-singleton constant ranges that may also be undef. Note that
250 /// this function also returns true if the range may include undef, but only
251 /// contains a single element. In that case, it can be replaced by a constant.
252 bool isConstantRange(bool UndefAllowed = true) const {
253 return Tag == constantrange || (Tag == constantrange_including_undef &&
254 (UndefAllowed || Range.isSingleElement()));
255 }
256 bool isOverdefined() const { return Tag == overdefined; }
257
258 Constant *getConstant() const {
259 assert(isConstant() && "Cannot get the constant of a non-constant!")(static_cast <bool> (isConstant() && "Cannot get the constant of a non-constant!"
) ? void (0) : __assert_fail ("isConstant() && \"Cannot get the constant of a non-constant!\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 259, __extension__
__PRETTY_FUNCTION__))
;
17
Assuming the condition is true
18
'?' condition is true
260 return ConstVal;
19
Undefined or garbage value returned to caller
261 }
262
263 Constant *getNotConstant() const {
264 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!")(static_cast <bool> (isNotConstant() && "Cannot get the constant of a non-notconstant!"
) ? void (0) : __assert_fail ("isNotConstant() && \"Cannot get the constant of a non-notconstant!\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 264, __extension__
__PRETTY_FUNCTION__))
;
265 return ConstVal;
266 }
267
268 /// Returns the constant range for this value. Use \p UndefAllowed to exclude
269 /// non-singleton constant ranges that may also be undef. Note that this
270 /// function also returns a range if the range may include undef, but only
271 /// contains a single element. In that case, it can be replaced by a constant.
272 const ConstantRange &getConstantRange(bool UndefAllowed = true) const {
273 assert(isConstantRange(UndefAllowed) &&(static_cast <bool> (isConstantRange(UndefAllowed) &&
"Cannot get the constant-range of a non-constant-range!") ? void
(0) : __assert_fail ("isConstantRange(UndefAllowed) && \"Cannot get the constant-range of a non-constant-range!\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 274, __extension__
__PRETTY_FUNCTION__))
274 "Cannot get the constant-range of a non-constant-range!")(static_cast <bool> (isConstantRange(UndefAllowed) &&
"Cannot get the constant-range of a non-constant-range!") ? void
(0) : __assert_fail ("isConstantRange(UndefAllowed) && \"Cannot get the constant-range of a non-constant-range!\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 274, __extension__
__PRETTY_FUNCTION__))
;
275 return Range;
276 }
277
278 Optional<APInt> asConstantInteger() const {
279 if (isConstant() && isa<ConstantInt>(getConstant())) {
280 return cast<ConstantInt>(getConstant())->getValue();
281 } else if (isConstantRange() && getConstantRange().isSingleElement()) {
282 return *getConstantRange().getSingleElement();
283 }
284 return None;
285 }
286
287 bool markOverdefined() {
288 if (isOverdefined())
289 return false;
290 destroy();
291 Tag = overdefined;
292 return true;
293 }
294
295 bool markUndef() {
296 if (isUndef())
297 return false;
298
299 assert(isUnknown())(static_cast <bool> (isUnknown()) ? void (0) : __assert_fail
("isUnknown()", "llvm/include/llvm/Analysis/ValueLattice.h",
299, __extension__ __PRETTY_FUNCTION__))
;
300 Tag = undef;
301 return true;
302 }
303
304 bool markConstant(Constant *V, bool MayIncludeUndef = false) {
305 if (isa<UndefValue>(V))
306 return markUndef();
307
308 if (isConstant()) {
309 assert(getConstant() == V && "Marking constant with different value")(static_cast <bool> (getConstant() == V && "Marking constant with different value"
) ? void (0) : __assert_fail ("getConstant() == V && \"Marking constant with different value\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 309, __extension__
__PRETTY_FUNCTION__))
;
310 return false;
311 }
312
313 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
314 return markConstantRange(
315 ConstantRange(CI->getValue()),
316 MergeOptions().setMayIncludeUndef(MayIncludeUndef));
317
318 assert(isUnknown() || isUndef())(static_cast <bool> (isUnknown() || isUndef()) ? void (
0) : __assert_fail ("isUnknown() || isUndef()", "llvm/include/llvm/Analysis/ValueLattice.h"
, 318, __extension__ __PRETTY_FUNCTION__))
;
319 Tag = constant;
320 ConstVal = V;
321 return true;
322 }
323
324 bool markNotConstant(Constant *V) {
325 assert(V && "Marking constant with NULL")(static_cast <bool> (V && "Marking constant with NULL"
) ? void (0) : __assert_fail ("V && \"Marking constant with NULL\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 325, __extension__
__PRETTY_FUNCTION__))
;
326 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
327 return markConstantRange(
328 ConstantRange(CI->getValue() + 1, CI->getValue()));
329
330 if (isa<UndefValue>(V))
331 return false;
332
333 if (isNotConstant()) {
334 assert(getNotConstant() == V && "Marking !constant with different value")(static_cast <bool> (getNotConstant() == V && "Marking !constant with different value"
) ? void (0) : __assert_fail ("getNotConstant() == V && \"Marking !constant with different value\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 334, __extension__
__PRETTY_FUNCTION__))
;
335 return false;
336 }
337
338 assert(isUnknown())(static_cast <bool> (isUnknown()) ? void (0) : __assert_fail
("isUnknown()", "llvm/include/llvm/Analysis/ValueLattice.h",
338, __extension__ __PRETTY_FUNCTION__))
;
339 Tag = notconstant;
340 ConstVal = V;
341 return true;
342 }
343
344 /// Mark the object as constant range with \p NewR. If the object is already a
345 /// constant range, nothing changes if the existing range is equal to \p
346 /// NewR and the tag. Otherwise \p NewR must be a superset of the existing
347 /// range or the object must be undef. The tag is set to
348 /// constant_range_including_undef if either the existing value or the new
349 /// range may include undef.
350 bool markConstantRange(ConstantRange NewR,
351 MergeOptions Opts = MergeOptions()) {
352 assert(!NewR.isEmptySet() && "should only be called for non-empty sets")(static_cast <bool> (!NewR.isEmptySet() && "should only be called for non-empty sets"
) ? void (0) : __assert_fail ("!NewR.isEmptySet() && \"should only be called for non-empty sets\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 352, __extension__
__PRETTY_FUNCTION__))
;
353
354 if (NewR.isFullSet())
355 return markOverdefined();
356
357 ValueLatticeElementTy OldTag = Tag;
358 ValueLatticeElementTy NewTag =
359 (isUndef() || isConstantRangeIncludingUndef() || Opts.MayIncludeUndef)
360 ? constantrange_including_undef
361 : constantrange;
362 if (isConstantRange()) {
363 Tag = NewTag;
364 if (getConstantRange() == NewR)
365 return Tag != OldTag;
366
367 // Simple form of widening. If a range is extended multiple times, go to
368 // overdefined.
369 if (Opts.CheckWiden && ++NumRangeExtensions > Opts.MaxWidenSteps)
370 return markOverdefined();
371
372 assert(NewR.contains(getConstantRange()) &&(static_cast <bool> (NewR.contains(getConstantRange()) &&
"Existing range must be a subset of NewR") ? void (0) : __assert_fail
("NewR.contains(getConstantRange()) && \"Existing range must be a subset of NewR\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 373, __extension__
__PRETTY_FUNCTION__))
373 "Existing range must be a subset of NewR")(static_cast <bool> (NewR.contains(getConstantRange()) &&
"Existing range must be a subset of NewR") ? void (0) : __assert_fail
("NewR.contains(getConstantRange()) && \"Existing range must be a subset of NewR\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 373, __extension__
__PRETTY_FUNCTION__))
;
374 Range = std::move(NewR);
375 return true;
376 }
377
378 assert(isUnknown() || isUndef())(static_cast <bool> (isUnknown() || isUndef()) ? void (
0) : __assert_fail ("isUnknown() || isUndef()", "llvm/include/llvm/Analysis/ValueLattice.h"
, 378, __extension__ __PRETTY_FUNCTION__))
;
379
380 NumRangeExtensions = 0;
381 Tag = NewTag;
382 new (&Range) ConstantRange(std::move(NewR));
383 return true;
384 }
385
386 /// Updates this object to approximate both this object and RHS. Returns
387 /// true if this object has been changed.
388 bool mergeIn(const ValueLatticeElement &RHS,
389 MergeOptions Opts = MergeOptions()) {
390 if (RHS.isUnknown() || isOverdefined())
391 return false;
392 if (RHS.isOverdefined()) {
393 markOverdefined();
394 return true;
395 }
396
397 if (isUndef()) {
398 assert(!RHS.isUnknown())(static_cast <bool> (!RHS.isUnknown()) ? void (0) : __assert_fail
("!RHS.isUnknown()", "llvm/include/llvm/Analysis/ValueLattice.h"
, 398, __extension__ __PRETTY_FUNCTION__))
;
399 if (RHS.isUndef())
400 return false;
401 if (RHS.isConstant())
402 return markConstant(RHS.getConstant(), true);
403 if (RHS.isConstantRange())
404 return markConstantRange(RHS.getConstantRange(true),
405 Opts.setMayIncludeUndef());
406 return markOverdefined();
407 }
408
409 if (isUnknown()) {
410 assert(!RHS.isUnknown() && "Unknow RHS should be handled earlier")(static_cast <bool> (!RHS.isUnknown() && "Unknow RHS should be handled earlier"
) ? void (0) : __assert_fail ("!RHS.isUnknown() && \"Unknow RHS should be handled earlier\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 410, __extension__
__PRETTY_FUNCTION__))
;
411 *this = RHS;
412 return true;
413 }
414
415 if (isConstant()) {
416 if (RHS.isConstant() && getConstant() == RHS.getConstant())
417 return false;
418 if (RHS.isUndef())
419 return false;
420 markOverdefined();
421 return true;
422 }
423
424 if (isNotConstant()) {
425 if (RHS.isNotConstant() && getNotConstant() == RHS.getNotConstant())
426 return false;
427 markOverdefined();
428 return true;
429 }
430
431 auto OldTag = Tag;
432 assert(isConstantRange() && "New ValueLattice type?")(static_cast <bool> (isConstantRange() && "New ValueLattice type?"
) ? void (0) : __assert_fail ("isConstantRange() && \"New ValueLattice type?\""
, "llvm/include/llvm/Analysis/ValueLattice.h", 432, __extension__
__PRETTY_FUNCTION__))
;
433 if (RHS.isUndef()) {
434 Tag = constantrange_including_undef;
435 return OldTag != Tag;
436 }
437
438 if (!RHS.isConstantRange()) {
439 // We can get here if we've encountered a constantexpr of integer type
440 // and merge it with a constantrange.
441 markOverdefined();
442 return true;
443 }
444
445 ConstantRange NewR = getConstantRange().unionWith(RHS.getConstantRange());
446 return markConstantRange(
447 std::move(NewR),
448 Opts.setMayIncludeUndef(RHS.isConstantRangeIncludingUndef()));
449 }
450
451 // Compares this symbolic value with Other using Pred and returns either
452 /// true, false or undef constants, or nullptr if the comparison cannot be
453 /// evaluated.
454 Constant *getCompare(CmpInst::Predicate Pred, Type *Ty,
455 const ValueLatticeElement &Other,
456 const DataLayout &DL) const;
457
458 unsigned getNumRangeExtensions() const { return NumRangeExtensions; }
459 void setNumRangeExtensions(unsigned N) { NumRangeExtensions = N; }
460};
461
462static_assert(sizeof(ValueLatticeElement) <= 40,
463 "size of ValueLatticeElement changed unexpectedly");
464
465raw_ostream &operator<<(raw_ostream &OS, const ValueLatticeElement &Val);
466} // end namespace llvm
467#endif