LLVM 20.0.0git
LazyValueInfo.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/STLExtras.h"
25#include "llvm/IR/CFG.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
37#include "llvm/IR/ValueHandle.h"
39#include "llvm/Support/Debug.h"
43#include <optional>
44using namespace llvm;
45using namespace PatternMatch;
46
47#define DEBUG_TYPE "lazy-value-info"
48
49// This is the number of worklist items we will process to try to discover an
50// answer for a given value.
51static const unsigned MaxProcessedPerValue = 500;
52
56}
58 "Lazy Value Information Analysis", false, true)
63
64namespace llvm {
66 return new LazyValueInfoWrapperPass();
67}
68} // namespace llvm
69
70AnalysisKey LazyValueAnalysis::Key;
71
72/// Returns true if this lattice value represents at most one possible value.
73/// This is as precise as any lattice value can get while still representing
74/// reachable code.
75static bool hasSingleValue(const ValueLatticeElement &Val) {
76 if (Val.isConstantRange() &&
78 // Integer constants are single element ranges
79 return true;
80 if (Val.isConstant())
81 // Non integer constants
82 return true;
83 return false;
84}
85
86/// Combine two sets of facts about the same value into a single set of
87/// facts. Note that this method is not suitable for merging facts along
88/// different paths in a CFG; that's what the mergeIn function is for. This
89/// is for merging facts gathered about the same value at the same location
90/// through two independent means.
91/// Notes:
92/// * This method does not promise to return the most precise possible lattice
93/// value implied by A and B. It is allowed to return any lattice element
94/// which is at least as strong as *either* A or B (unless our facts
95/// conflict, see below).
96/// * Due to unreachable code, the intersection of two lattice values could be
97/// contradictory. If this happens, we return some valid lattice value so as
98/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
99/// we do not make this guarantee. TODO: This would be a useful enhancement.
101 const ValueLatticeElement &B) {
102 // Undefined is the strongest state. It means the value is known to be along
103 // an unreachable path.
104 if (A.isUnknown())
105 return A;
106 if (B.isUnknown())
107 return B;
108
109 // If we gave up for one, but got a useable fact from the other, use it.
110 if (A.isOverdefined())
111 return B;
112 if (B.isOverdefined())
113 return A;
114
115 // Can't get any more precise than constants.
116 if (hasSingleValue(A))
117 return A;
118 if (hasSingleValue(B))
119 return B;
120
121 // Could be either constant range or not constant here.
122 if (!A.isConstantRange() || !B.isConstantRange()) {
123 // TODO: Arbitrary choice, could be improved
124 return A;
125 }
126
127 // Intersect two constant ranges
129 A.getConstantRange().intersectWith(B.getConstantRange());
130 // Note: An empty range is implicitly converted to unknown or undef depending
131 // on MayIncludeUndef internally.
133 std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() ||
134 B.isConstantRangeIncludingUndef());
135}
136
137//===----------------------------------------------------------------------===//
138// LazyValueInfoCache Decl
139//===----------------------------------------------------------------------===//
140
141namespace {
142 /// A callback value handle updates the cache when values are erased.
143 class LazyValueInfoCache;
144 struct LVIValueHandle final : public CallbackVH {
145 LazyValueInfoCache *Parent;
146
147 LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
148 : CallbackVH(V), Parent(P) { }
149
150 void deleted() override;
151 void allUsesReplacedWith(Value *V) override {
152 deleted();
153 }
154 };
155} // end anonymous namespace
156
157namespace {
158using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
159
160/// This is the cache kept by LazyValueInfo which
161/// maintains information about queries across the clients' queries.
162class LazyValueInfoCache {
163 /// This is all of the cached information for one basic block. It contains
164 /// the per-value lattice elements, as well as a separate set for
165 /// overdefined values to reduce memory usage. Additionally pointers
166 /// dereferenced in the block are cached for nullability queries.
167 struct BlockCacheEntry {
169 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
170 // std::nullopt indicates that the nonnull pointers for this basic block
171 // block have not been computed yet.
172 std::optional<NonNullPointerSet> NonNullPointers;
173 };
174
175 /// Cached information per basic block.
176 DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
177 BlockCache;
178 /// Set of value handles used to erase values from the cache on deletion.
180
181 const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
182 auto It = BlockCache.find_as(BB);
183 if (It == BlockCache.end())
184 return nullptr;
185 return It->second.get();
186 }
187
188 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
189 auto It = BlockCache.find_as(BB);
190 if (It == BlockCache.end())
191 It = BlockCache.insert({BB, std::make_unique<BlockCacheEntry>()}).first;
192
193 return It->second.get();
194 }
195
196 void addValueHandle(Value *Val) {
197 auto HandleIt = ValueHandles.find_as(Val);
198 if (HandleIt == ValueHandles.end())
199 ValueHandles.insert({Val, this});
200 }
201
202public:
203 void insertResult(Value *Val, BasicBlock *BB,
204 const ValueLatticeElement &Result) {
205 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
206
207 // Insert over-defined values into their own cache to reduce memory
208 // overhead.
209 if (Result.isOverdefined())
210 Entry->OverDefined.insert(Val);
211 else
212 Entry->LatticeElements.insert({Val, Result});
213
214 addValueHandle(Val);
215 }
216
217 std::optional<ValueLatticeElement> getCachedValueInfo(Value *V,
218 BasicBlock *BB) const {
219 const BlockCacheEntry *Entry = getBlockEntry(BB);
220 if (!Entry)
221 return std::nullopt;
222
223 if (Entry->OverDefined.count(V))
225
226 auto LatticeIt = Entry->LatticeElements.find_as(V);
227 if (LatticeIt == Entry->LatticeElements.end())
228 return std::nullopt;
229
230 return LatticeIt->second;
231 }
232
233 bool
234 isNonNullAtEndOfBlock(Value *V, BasicBlock *BB,
235 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
236 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
237 if (!Entry->NonNullPointers) {
238 Entry->NonNullPointers = InitFn(BB);
239 for (Value *V : *Entry->NonNullPointers)
240 addValueHandle(V);
241 }
242
243 return Entry->NonNullPointers->count(V);
244 }
245
246 /// clear - Empty the cache.
247 void clear() {
248 BlockCache.clear();
249 ValueHandles.clear();
250 }
251
252 /// Inform the cache that a given value has been deleted.
253 void eraseValue(Value *V);
254
255 /// This is part of the update interface to inform the cache
256 /// that a block has been deleted.
257 void eraseBlock(BasicBlock *BB);
258
259 /// Updates the cache to remove any influence an overdefined value in
260 /// OldSucc might have (unless also overdefined in NewSucc). This just
261 /// flushes elements from the cache and does not add any.
262 void threadEdgeImpl(BasicBlock *OldSucc, BasicBlock *NewSucc);
263};
264} // namespace
265
266void LazyValueInfoCache::eraseValue(Value *V) {
267 for (auto &Pair : BlockCache) {
268 Pair.second->LatticeElements.erase(V);
269 Pair.second->OverDefined.erase(V);
270 if (Pair.second->NonNullPointers)
271 Pair.second->NonNullPointers->erase(V);
272 }
273
274 auto HandleIt = ValueHandles.find_as(V);
275 if (HandleIt != ValueHandles.end())
276 ValueHandles.erase(HandleIt);
277}
278
279void LVIValueHandle::deleted() {
280 // This erasure deallocates *this, so it MUST happen after we're done
281 // using any and all members of *this.
282 Parent->eraseValue(*this);
283}
284
285void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
286 BlockCache.erase(BB);
287}
288
289void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
290 BasicBlock *NewSucc) {
291 // When an edge in the graph has been threaded, values that we could not
292 // determine a value for before (i.e. were marked overdefined) may be
293 // possible to solve now. We do NOT try to proactively update these values.
294 // Instead, we clear their entries from the cache, and allow lazy updating to
295 // recompute them when needed.
296
297 // The updating process is fairly simple: we need to drop cached info
298 // for all values that were marked overdefined in OldSucc, and for those same
299 // values in any successor of OldSucc (except NewSucc) in which they were
300 // also marked overdefined.
301 std::vector<BasicBlock*> worklist;
302 worklist.push_back(OldSucc);
303
304 const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
305 if (!Entry || Entry->OverDefined.empty())
306 return; // Nothing to process here.
307 SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
308 Entry->OverDefined.end());
309
310 // Use a worklist to perform a depth-first search of OldSucc's successors.
311 // NOTE: We do not need a visited list since any blocks we have already
312 // visited will have had their overdefined markers cleared already, and we
313 // thus won't loop to their successors.
314 while (!worklist.empty()) {
315 BasicBlock *ToUpdate = worklist.back();
316 worklist.pop_back();
317
318 // Skip blocks only accessible through NewSucc.
319 if (ToUpdate == NewSucc) continue;
320
321 // If a value was marked overdefined in OldSucc, and is here too...
322 auto OI = BlockCache.find_as(ToUpdate);
323 if (OI == BlockCache.end() || OI->second->OverDefined.empty())
324 continue;
325 auto &ValueSet = OI->second->OverDefined;
326
327 bool changed = false;
328 for (Value *V : ValsToClear) {
329 if (!ValueSet.erase(V))
330 continue;
331
332 // If we removed anything, then we potentially need to update
333 // blocks successors too.
334 changed = true;
335 }
336
337 if (!changed) continue;
338
339 llvm::append_range(worklist, successors(ToUpdate));
340 }
341}
342
343namespace llvm {
344namespace {
345/// An assembly annotator class to print LazyValueCache information in
346/// comments.
347class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
348 LazyValueInfoImpl *LVIImpl;
349 // While analyzing which blocks we can solve values for, we need the dominator
350 // information.
351 DominatorTree &DT;
352
353public:
354 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
355 : LVIImpl(L), DT(DTree) {}
356
357 void emitBasicBlockStartAnnot(const BasicBlock *BB,
358 formatted_raw_ostream &OS) override;
359
360 void emitInstructionAnnot(const Instruction *I,
361 formatted_raw_ostream &OS) override;
362};
363} // namespace
364// The actual implementation of the lazy analysis and update.
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.
374
375 /// Keeps track of which block-value pairs are in BlockValueStack.
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 "
385 << BV.first->getName() << "\n");
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 std::optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
398 Instruction *CxtI);
399 std::optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
400 BasicBlock *T,
401 Instruction *CxtI = nullptr);
402
403 // These methods process one work item and may add more. A false value
404 // returned means that the work item was not completely processed and must
405 // be revisited after going through the new items.
406 bool solveBlockValue(Value *Val, BasicBlock *BB);
407 std::optional<ValueLatticeElement> solveBlockValueImpl(Value *Val,
408 BasicBlock *BB);
409 std::optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
410 BasicBlock *BB);
411 std::optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
412 BasicBlock *BB);
413 std::optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
414 BasicBlock *BB);
415 std::optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
416 BasicBlock *BB);
417 std::optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
419 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
420 OpFn);
421 std::optional<ValueLatticeElement>
422 solveBlockValueBinaryOp(BinaryOperator *BBI, BasicBlock *BB);
423 std::optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
424 BasicBlock *BB);
425 std::optional<ValueLatticeElement>
426 solveBlockValueOverflowIntrinsic(WithOverflowInst *WO, BasicBlock *BB);
427 std::optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
428 BasicBlock *BB);
429 std::optional<ValueLatticeElement>
430 solveBlockValueInsertElement(InsertElementInst *IEI, BasicBlock *BB);
431 std::optional<ValueLatticeElement>
432 solveBlockValueExtractValue(ExtractValueInst *EVI, BasicBlock *BB);
433 bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
434 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
436 Instruction *BBI);
437
438 void solve();
439
440 // For the following methods, if UseBlockValue is true, the function may
441 // push additional values to the worklist and return nullopt. If
442 // UseBlockValue is false, it will never return nullopt.
443
444 std::optional<ValueLatticeElement>
445 getValueFromSimpleICmpCondition(CmpInst::Predicate Pred, Value *RHS,
446 const APInt &Offset, Instruction *CxtI,
447 bool UseBlockValue);
448
449 std::optional<ValueLatticeElement>
450 getValueFromICmpCondition(Value *Val, ICmpInst *ICI, bool isTrueDest,
451 bool UseBlockValue);
452
453 std::optional<ValueLatticeElement>
454 getValueFromCondition(Value *Val, Value *Cond, bool IsTrueDest,
455 bool UseBlockValue, unsigned Depth = 0);
456
457 std::optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
458 BasicBlock *BBFrom,
459 BasicBlock *BBTo,
460 bool UseBlockValue);
461
462public:
463 /// This is the query interface to determine the lattice value for the
464 /// specified Value* at the context instruction (if specified) or at the
465 /// start of the block.
467 Instruction *CxtI = nullptr);
468
469 /// This is the query interface to determine the lattice value for the
470 /// specified Value* at the specified instruction using only information
471 /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
472 /// recursive query is performed.
474
475 /// This is the query interface to determine the lattice
476 /// value for the specified Value* that is true on the specified edge.
478 BasicBlock *ToBB,
479 Instruction *CxtI = nullptr);
480
482
483 /// Complete flush all previously computed values
484 void clear() {
485 TheCache.clear();
486 }
487
488 /// Printing the LazyValueInfo Analysis.
490 LazyValueInfoAnnotatedWriter Writer(this, DTree);
491 F.print(OS, &Writer);
492 }
493
494 /// This is part of the update interface to remove information related to this
495 /// value from the cache.
496 void forgetValue(Value *V) { TheCache.eraseValue(V); }
497
498 /// This is part of the update interface to inform the cache
499 /// that a block has been deleted.
501 TheCache.eraseBlock(BB);
502 }
503
504 /// This is the update interface to inform the cache that an edge from
505 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
506 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
507
509 Function *GuardDecl)
510 : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
511};
512} // namespace llvm
513
514void LazyValueInfoImpl::solve() {
516 BlockValueStack.begin(), BlockValueStack.end());
517
518 unsigned processedCount = 0;
519 while (!BlockValueStack.empty()) {
520 processedCount++;
521 // Abort if we have to process too many values to get a result for this one.
522 // Because of the design of the overdefined cache currently being per-block
523 // to avoid naming-related issues (IE it wants to try to give different
524 // results for the same name in different blocks), overdefined results don't
525 // get cached globally, which in turn means we will often try to rediscover
526 // the same overdefined result again and again. Once something like
527 // PredicateInfo is used in LVI or CVP, we should be able to make the
528 // overdefined cache global, and remove this throttle.
529 if (processedCount > MaxProcessedPerValue) {
531 dbgs() << "Giving up on stack because we are getting too deep\n");
532 // Fill in the original values
533 while (!StartingStack.empty()) {
534 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
535 TheCache.insertResult(e.second, e.first,
537 StartingStack.pop_back();
538 }
539 BlockValueSet.clear();
540 BlockValueStack.clear();
541 return;
542 }
543 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
544 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
545 unsigned StackSize = BlockValueStack.size();
546 (void) StackSize;
547
548 if (solveBlockValue(e.second, e.first)) {
549 // The work item was completely processed.
550 assert(BlockValueStack.size() == StackSize &&
551 BlockValueStack.back() == e && "Nothing should have been pushed!");
552#ifndef NDEBUG
553 std::optional<ValueLatticeElement> BBLV =
554 TheCache.getCachedValueInfo(e.second, e.first);
555 assert(BBLV && "Result should be in cache!");
557 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
558 << *BBLV << "\n");
559#endif
560
561 BlockValueStack.pop_back();
562 BlockValueSet.erase(e);
563 } else {
564 // More work needs to be done before revisiting.
565 assert(BlockValueStack.size() == StackSize + 1 &&
566 "Exactly one element should have been pushed!");
567 }
568 }
569}
570
571std::optional<ValueLatticeElement>
572LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB,
573 Instruction *CxtI) {
574 // If already a constant, there is nothing to compute.
575 if (Constant *VC = dyn_cast<Constant>(Val))
576 return ValueLatticeElement::get(VC);
577
578 if (std::optional<ValueLatticeElement> OptLatticeVal =
579 TheCache.getCachedValueInfo(Val, BB)) {
580 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
581 return OptLatticeVal;
582 }
583
584 // We have hit a cycle, assume overdefined.
585 if (!pushBlockValue({ BB, Val }))
587
588 // Yet to be resolved.
589 return std::nullopt;
590}
591
593 switch (BBI->getOpcode()) {
594 default:
595 break;
596 case Instruction::Call:
597 case Instruction::Invoke:
598 if (std::optional<ConstantRange> Range = cast<CallBase>(BBI)->getRange())
600 [[fallthrough]];
601 case Instruction::Load:
602 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
603 if (isa<IntegerType>(BBI->getType())) {
606 }
607 break;
608 };
609 // Nothing known - will be intersected with other facts
611}
612
613bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
614 assert(!isa<Constant>(Val) && "Value should not be constant");
615 assert(!TheCache.getCachedValueInfo(Val, BB) &&
616 "Value should not be in cache");
617
618 // Hold off inserting this value into the Cache in case we have to return
619 // false and come back later.
620 std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
621 if (!Res)
622 // Work pushed, will revisit
623 return false;
624
625 TheCache.insertResult(Val, BB, *Res);
626 return true;
627}
628
629std::optional<ValueLatticeElement>
630LazyValueInfoImpl::solveBlockValueImpl(Value *Val, BasicBlock *BB) {
631 Instruction *BBI = dyn_cast<Instruction>(Val);
632 if (!BBI || BBI->getParent() != BB)
633 return solveBlockValueNonLocal(Val, BB);
634
635 if (PHINode *PN = dyn_cast<PHINode>(BBI))
636 return solveBlockValuePHINode(PN, BB);
637
638 if (auto *SI = dyn_cast<SelectInst>(BBI))
639 return solveBlockValueSelect(SI, BB);
640
641 // If this value is a nonnull pointer, record it's range and bailout. Note
642 // that for all other pointer typed values, we terminate the search at the
643 // definition. We could easily extend this to look through geps, bitcasts,
644 // and the like to prove non-nullness, but it's not clear that's worth it
645 // compile time wise. The context-insensitive value walk done inside
646 // isKnownNonZero gets most of the profitable cases at much less expense.
647 // This does mean that we have a sensitivity to where the defining
648 // instruction is placed, even if it could legally be hoisted much higher.
649 // That is unfortunate.
650 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
651 if (PT && isKnownNonZero(BBI, DL))
653
654 if (BBI->getType()->isIntOrIntVectorTy()) {
655 if (auto *CI = dyn_cast<CastInst>(BBI))
656 return solveBlockValueCast(CI, BB);
657
658 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
659 return solveBlockValueBinaryOp(BO, BB);
660
661 if (auto *IEI = dyn_cast<InsertElementInst>(BBI))
662 return solveBlockValueInsertElement(IEI, BB);
663
664 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
665 return solveBlockValueExtractValue(EVI, BB);
666
667 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
668 return solveBlockValueIntrinsic(II, BB);
669 }
670
671 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
672 << "' - unknown inst def found.\n");
673 return getFromRangeMetadata(BBI);
674}
675
676static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
677 // TODO: Use NullPointerIsDefined instead.
678 if (Ptr->getType()->getPointerAddressSpace() == 0)
679 PtrSet.insert(getUnderlyingObject(Ptr));
680}
681
683 Instruction *I, NonNullPointerSet &PtrSet) {
684 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
685 AddNonNullPointer(L->getPointerOperand(), PtrSet);
686 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
687 AddNonNullPointer(S->getPointerOperand(), PtrSet);
688 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
689 if (MI->isVolatile()) return;
690
691 // FIXME: check whether it has a valuerange that excludes zero?
692 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
693 if (!Len || Len->isZero()) return;
694
695 AddNonNullPointer(MI->getRawDest(), PtrSet);
696 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
697 AddNonNullPointer(MTI->getRawSource(), PtrSet);
698 }
699}
700
701bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
704 return false;
705
706 Val = Val->stripInBoundsOffsets();
707 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
708 NonNullPointerSet NonNullPointers;
709 for (Instruction &I : *BB)
710 AddNonNullPointersByInstruction(&I, NonNullPointers);
711 return NonNullPointers;
712 });
713}
714
715std::optional<ValueLatticeElement>
716LazyValueInfoImpl::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
717 ValueLatticeElement Result; // Start Undefined.
718
719 // If this is the entry block, we must be asking about an argument.
720 if (BB->isEntryBlock()) {
721 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
722 if (std::optional<ConstantRange> Range = cast<Argument>(Val)->getRange())
725 }
726
727 // Loop over all of our predecessors, merging what we know from them into
728 // result. If we encounter an unexplored predecessor, we eagerly explore it
729 // in a depth first manner. In practice, this has the effect of discovering
730 // paths we can't analyze eagerly without spending compile times analyzing
731 // other paths. This heuristic benefits from the fact that predecessors are
732 // frequently arranged such that dominating ones come first and we quickly
733 // find a path to function entry. TODO: We should consider explicitly
734 // canonicalizing to make this true rather than relying on this happy
735 // accident.
736 for (BasicBlock *Pred : predecessors(BB)) {
737 std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
738 if (!EdgeResult)
739 // Explore that input, then return here
740 return std::nullopt;
741
742 Result.mergeIn(*EdgeResult);
743
744 // If we hit overdefined, exit early. The BlockVals entry is already set
745 // to overdefined.
746 if (Result.isOverdefined()) {
747 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
748 << "' - overdefined because of pred '"
749 << Pred->getName() << "' (non local).\n");
750 return Result;
751 }
752 }
753
754 // Return the merged value, which is more precise than 'overdefined'.
755 assert(!Result.isOverdefined());
756 return Result;
757}
758
759std::optional<ValueLatticeElement>
760LazyValueInfoImpl::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
761 ValueLatticeElement Result; // Start Undefined.
762
763 // Loop over all of our predecessors, merging what we know from them into
764 // result. See the comment about the chosen traversal order in
765 // solveBlockValueNonLocal; the same reasoning applies here.
766 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
767 BasicBlock *PhiBB = PN->getIncomingBlock(i);
768 Value *PhiVal = PN->getIncomingValue(i);
769 // Note that we can provide PN as the context value to getEdgeValue, even
770 // though the results will be cached, because PN is the value being used as
771 // the cache key in the caller.
772 std::optional<ValueLatticeElement> EdgeResult =
773 getEdgeValue(PhiVal, PhiBB, BB, PN);
774 if (!EdgeResult)
775 // Explore that input, then return here
776 return std::nullopt;
777
778 Result.mergeIn(*EdgeResult);
779
780 // If we hit overdefined, exit early. The BlockVals entry is already set
781 // to overdefined.
782 if (Result.isOverdefined()) {
783 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
784 << "' - overdefined because of pred (local).\n");
785
786 return Result;
787 }
788 }
789
790 // Return the merged value, which is more precise than 'overdefined'.
791 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
792 return Result;
793}
794
795// If we can determine a constraint on the value given conditions assumed by
796// the program, intersect those constraints with BBLV
797void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
798 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
799 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
800 if (!BBI)
801 return;
802
803 BasicBlock *BB = BBI->getParent();
804 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
805 if (!AssumeVH)
806 continue;
807
808 // Only check assumes in the block of the context instruction. Other
809 // assumes will have already been taken into account when the value was
810 // propagated from predecessor blocks.
811 auto *I = cast<CallInst>(AssumeVH);
812 if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
813 continue;
814
815 BBLV = intersect(BBLV, *getValueFromCondition(Val, I->getArgOperand(0),
816 /*IsTrueDest*/ true,
817 /*UseBlockValue*/ false));
818 }
819
820 // If guards are not used in the module, don't spend time looking for them
821 if (GuardDecl && !GuardDecl->use_empty() &&
822 BBI->getIterator() != BB->begin()) {
823 for (Instruction &I :
824 make_range(std::next(BBI->getIterator().getReverse()), BB->rend())) {
825 Value *Cond = nullptr;
826 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
827 BBLV = intersect(BBLV,
828 *getValueFromCondition(Val, Cond, /*IsTrueDest*/ true,
829 /*UseBlockValue*/ false));
830 }
831 }
832
833 if (BBLV.isOverdefined()) {
834 // Check whether we're checking at the terminator, and the pointer has
835 // been dereferenced in this block.
836 PointerType *PTy = dyn_cast<PointerType>(Val->getType());
837 if (PTy && BB->getTerminator() == BBI &&
838 isNonNullAtEndOfBlock(Val, BB))
840 }
841}
842
843std::optional<ValueLatticeElement>
844LazyValueInfoImpl::solveBlockValueSelect(SelectInst *SI, BasicBlock *BB) {
845 // Recurse on our inputs if needed
846 std::optional<ValueLatticeElement> OptTrueVal =
847 getBlockValue(SI->getTrueValue(), BB, SI);
848 if (!OptTrueVal)
849 return std::nullopt;
850 ValueLatticeElement &TrueVal = *OptTrueVal;
851
852 std::optional<ValueLatticeElement> OptFalseVal =
853 getBlockValue(SI->getFalseValue(), BB, SI);
854 if (!OptFalseVal)
855 return std::nullopt;
856 ValueLatticeElement &FalseVal = *OptFalseVal;
857
858 if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
859 const ConstantRange &TrueCR = TrueVal.asConstantRange(SI->getType());
860 const ConstantRange &FalseCR = FalseVal.asConstantRange(SI->getType());
861 Value *LHS = nullptr;
862 Value *RHS = nullptr;
863 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
864 // Is this a min specifically of our two inputs? (Avoid the risk of
865 // ValueTracking getting smarter looking back past our immediate inputs.)
867 ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
868 (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
869 ConstantRange ResultCR = [&]() {
870 switch (SPR.Flavor) {
871 default:
872 llvm_unreachable("unexpected minmax type!");
873 case SPF_SMIN: /// Signed minimum
874 return TrueCR.smin(FalseCR);
875 case SPF_UMIN: /// Unsigned minimum
876 return TrueCR.umin(FalseCR);
877 case SPF_SMAX: /// Signed maximum
878 return TrueCR.smax(FalseCR);
879 case SPF_UMAX: /// Unsigned maximum
880 return TrueCR.umax(FalseCR);
881 };
882 }();
884 ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
885 FalseVal.isConstantRangeIncludingUndef());
886 }
887
888 if (SPR.Flavor == SPF_ABS) {
889 if (LHS == SI->getTrueValue())
891 TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
892 if (LHS == SI->getFalseValue())
894 FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
895 }
896
897 if (SPR.Flavor == SPF_NABS) {
899 if (LHS == SI->getTrueValue())
901 Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
902 if (LHS == SI->getFalseValue())
904 Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
905 }
906 }
907
908 // Can we constrain the facts about the true and false values by using the
909 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
910 // TODO: We could potentially refine an overdefined true value above.
911 Value *Cond = SI->getCondition();
912 // If the value is undef, a different value may be chosen in
913 // the select condition.
915 TrueVal =
916 intersect(TrueVal, *getValueFromCondition(SI->getTrueValue(), Cond,
917 /*IsTrueDest*/ true,
918 /*UseBlockValue*/ false));
919 FalseVal =
920 intersect(FalseVal, *getValueFromCondition(SI->getFalseValue(), Cond,
921 /*IsTrueDest*/ false,
922 /*UseBlockValue*/ false));
923 }
924
926 Result.mergeIn(FalseVal);
927 return Result;
928}
929
930std::optional<ConstantRange>
931LazyValueInfoImpl::getRangeFor(Value *V, Instruction *CxtI, BasicBlock *BB) {
932 std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
933 if (!OptVal)
934 return std::nullopt;
935 return OptVal->asConstantRange(V->getType());
936}
937
938std::optional<ValueLatticeElement>
939LazyValueInfoImpl::solveBlockValueCast(CastInst *CI, BasicBlock *BB) {
940 // Filter out casts we don't know how to reason about before attempting to
941 // recurse on our operand. This can cut a long search short if we know we're
942 // not going to be able to get any useful information anways.
943 switch (CI->getOpcode()) {
944 case Instruction::Trunc:
945 case Instruction::SExt:
946 case Instruction::ZExt:
947 break;
948 default:
949 // Unhandled instructions are overdefined.
950 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
951 << "' - overdefined (unknown cast).\n");
953 }
954
955 // Figure out the range of the LHS. If that fails, we still apply the
956 // transfer rule on the full set since we may be able to locally infer
957 // interesting facts.
958 std::optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
959 if (!LHSRes)
960 // More work to do before applying this transfer rule.
961 return std::nullopt;
962 const ConstantRange &LHSRange = *LHSRes;
963
964 const unsigned ResultBitWidth = CI->getType()->getScalarSizeInBits();
965
966 // NOTE: We're currently limited by the set of operations that ConstantRange
967 // can evaluate symbolically. Enhancing that set will allows us to analyze
968 // more definitions.
969 return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
970 ResultBitWidth));
971}
972
973std::optional<ValueLatticeElement>
974LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
976 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
977 OpFn) {
978 // Figure out the ranges of the operands. If that fails, use a
979 // conservative range, but apply the transfer rule anyways. This
980 // lets us pick up facts from expressions like "and i32 (call i32
981 // @foo()), 32"
982 std::optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
983 if (!LHSRes)
984 return std::nullopt;
985
986 std::optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
987 if (!RHSRes)
988 return std::nullopt;
989
990 const ConstantRange &LHSRange = *LHSRes;
991 const ConstantRange &RHSRange = *RHSRes;
992 return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
993}
994
995std::optional<ValueLatticeElement>
996LazyValueInfoImpl::solveBlockValueBinaryOp(BinaryOperator *BO, BasicBlock *BB) {
997 assert(BO->getOperand(0)->getType()->isSized() &&
998 "all operands to binary operators are sized");
999 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
1000 unsigned NoWrapKind = OBO->getNoWrapKind();
1001 return solveBlockValueBinaryOpImpl(
1002 BO, BB,
1003 [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
1004 return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
1005 });
1006 }
1007
1008 return solveBlockValueBinaryOpImpl(
1009 BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1010 return CR1.binaryOp(BO->getOpcode(), CR2);
1011 });
1012}
1013
1014std::optional<ValueLatticeElement>
1015LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
1016 BasicBlock *BB) {
1017 return solveBlockValueBinaryOpImpl(
1018 WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1019 return CR1.binaryOp(WO->getBinaryOp(), CR2);
1020 });
1021}
1022
1023std::optional<ValueLatticeElement>
1024LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
1026 if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1027 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1028 << "' - unknown intrinsic.\n");
1029 return MetadataVal;
1030 }
1031
1033 for (Value *Op : II->args()) {
1034 std::optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1035 if (!Range)
1036 return std::nullopt;
1037 OpRanges.push_back(*Range);
1038 }
1039
1041 II->getIntrinsicID(), OpRanges)),
1042 MetadataVal);
1043}
1044
1045std::optional<ValueLatticeElement>
1046LazyValueInfoImpl::solveBlockValueInsertElement(InsertElementInst *IEI,
1047 BasicBlock *BB) {
1048 std::optional<ValueLatticeElement> OptEltVal =
1049 getBlockValue(IEI->getOperand(1), BB, IEI);
1050 if (!OptEltVal)
1051 return std::nullopt;
1052 ValueLatticeElement &Res = *OptEltVal;
1053
1054 std::optional<ValueLatticeElement> OptVecVal =
1055 getBlockValue(IEI->getOperand(0), BB, IEI);
1056 if (!OptVecVal)
1057 return std::nullopt;
1058
1059 Res.mergeIn(*OptVecVal);
1060 return Res;
1061}
1062
1063std::optional<ValueLatticeElement>
1064LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
1065 BasicBlock *BB) {
1066 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1067 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1068 return solveBlockValueOverflowIntrinsic(WO, BB);
1069
1070 // Handle extractvalue of insertvalue to allow further simplification
1071 // based on replaced with.overflow intrinsics.
1073 EVI->getAggregateOperand(), EVI->getIndices(),
1074 EVI->getDataLayout()))
1075 return getBlockValue(V, BB, EVI);
1076
1077 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1078 << "' - overdefined (unknown extractvalue).\n");
1080}
1081
1082static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
1083 ICmpInst::Predicate Pred) {
1084 if (LHS == Val)
1085 return true;
1086
1087 // Handle range checking idiom produced by InstCombine. We will subtract the
1088 // offset from the allowed range for RHS in this case.
1089 const APInt *C;
1090 if (match(LHS, m_AddLike(m_Specific(Val), m_APInt(C)))) {
1091 Offset = *C;
1092 return true;
1093 }
1094
1095 // Handle the symmetric case. This appears in saturation patterns like
1096 // (x == 16) ? 16 : (x + 1).
1097 if (match(Val, m_AddLike(m_Specific(LHS), m_APInt(C)))) {
1098 Offset = -*C;
1099 return true;
1100 }
1101
1102 // If (x | y) < C, then (x < C) && (y < C).
1103 if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1104 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
1105 return true;
1106
1107 // If (x & y) > C, then (x > C) && (y > C).
1108 if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1109 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
1110 return true;
1111
1112 return false;
1113}
1114
1115/// Get value range for a "(Val + Offset) Pred RHS" condition.
1116std::optional<ValueLatticeElement>
1117LazyValueInfoImpl::getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,
1118 Value *RHS,
1119 const APInt &Offset,
1120 Instruction *CxtI,
1121 bool UseBlockValue) {
1123 /*isFullSet=*/true);
1124 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1125 RHSRange = ConstantRange(CI->getValue());
1126 } else if (UseBlockValue) {
1127 std::optional<ValueLatticeElement> R =
1128 getBlockValue(RHS, CxtI->getParent(), CxtI);
1129 if (!R)
1130 return std::nullopt;
1131 RHSRange = R->asConstantRange(RHS->getType());
1132 }
1133
1134 ConstantRange TrueValues =
1136 return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1137}
1138
1139static std::optional<ConstantRange>
1141 function_ref<std::optional<ConstantRange>(const APInt &)> Fn) {
1142 bool Invert = false;
1143 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
1144 Pred = ICmpInst::getInversePredicate(Pred);
1145 Invert = true;
1146 }
1147 if (Pred == ICmpInst::ICMP_SLE) {
1148 Pred = ICmpInst::ICMP_SLT;
1149 if (RHS.isMaxSignedValue())
1150 return std::nullopt; // Could also return full/empty here, if we wanted.
1151 ++RHS;
1152 }
1153 assert(Pred == ICmpInst::ICMP_SLT && "Must be signed predicate");
1154 if (auto CR = Fn(RHS))
1155 return Invert ? CR->inverse() : CR;
1156 return std::nullopt;
1157}
1158
1159std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1160 Value *Val, ICmpInst *ICI, bool isTrueDest, bool UseBlockValue) {
1161 Value *LHS = ICI->getOperand(0);
1162 Value *RHS = ICI->getOperand(1);
1163
1164 // Get the predicate that must hold along the considered edge.
1165 CmpInst::Predicate EdgePred =
1166 isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1167
1168 if (isa<Constant>(RHS)) {
1169 if (ICI->isEquality() && LHS == Val) {
1170 if (EdgePred == ICmpInst::ICMP_EQ)
1171 return ValueLatticeElement::get(cast<Constant>(RHS));
1172 else if (!isa<UndefValue>(RHS))
1173 return ValueLatticeElement::getNot(cast<Constant>(RHS));
1174 }
1175 }
1176
1177 Type *Ty = Val->getType();
1178 if (!Ty->isIntegerTy())
1180
1181 unsigned BitWidth = Ty->getScalarSizeInBits();
1182 APInt Offset(BitWidth, 0);
1183 if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1184 return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset, ICI,
1185 UseBlockValue);
1186
1187 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1188 if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1189 return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset, ICI,
1190 UseBlockValue);
1191
1192 const APInt *Mask, *C;
1193 if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1194 match(RHS, m_APInt(C))) {
1195 // If (Val & Mask) == C then all the masked bits are known and we can
1196 // compute a value range based on that.
1197 if (EdgePred == ICmpInst::ICMP_EQ) {
1198 KnownBits Known;
1199 Known.Zero = ~*C & *Mask;
1200 Known.One = *C & *Mask;
1202 ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1203 }
1204
1205 if (EdgePred == ICmpInst::ICMP_NE)
1208 }
1209
1210 // If (X urem Modulus) >= C, then X >= C.
1211 // If trunc X >= C, then X >= C.
1212 // TODO: An upper bound could be computed as well.
1213 if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
1214 m_Trunc(m_Specific(Val)))) &&
1215 match(RHS, m_APInt(C))) {
1216 // Use the icmp region so we don't have to deal with different predicates.
1218 if (!CR.isEmptySet())
1221 }
1222
1223 // Recognize:
1224 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, C << ShAmtC
1225 // Preconditions: (C << ShAmtC) >> ShAmtC == C
1226 const APInt *ShAmtC;
1227 if (CmpInst::isSigned(EdgePred) &&
1228 match(LHS, m_AShr(m_Specific(Val), m_APInt(ShAmtC))) &&
1229 match(RHS, m_APInt(C))) {
1230 auto CR = getRangeViaSLT(
1231 EdgePred, *C, [&](const APInt &RHS) -> std::optional<ConstantRange> {
1232 APInt New = RHS << *ShAmtC;
1233 if ((New.ashr(*ShAmtC)) != RHS)
1234 return std::nullopt;
1236 APInt::getSignedMinValue(New.getBitWidth()), New);
1237 });
1238 if (CR)
1240 }
1241
1243}
1244
1245// Handle conditions of the form
1246// extractvalue(op.with.overflow(%x, C), 1).
1248 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1249 // TODO: This only works with a constant RHS for now. We could also compute
1250 // the range of the RHS, but this doesn't fit into the current structure of
1251 // the edge value calculation.
1252 const APInt *C;
1253 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1255
1256 // Calculate the possible values of %x for which no overflow occurs.
1258 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1259
1260 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1261 // constrained to it's inverse (all values that might cause overflow).
1262 if (IsTrueDest)
1263 NWR = NWR.inverse();
1265}
1266
1267std::optional<ValueLatticeElement>
1268LazyValueInfoImpl::getValueFromCondition(Value *Val, Value *Cond,
1269 bool IsTrueDest, bool UseBlockValue,
1270 unsigned Depth) {
1271 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1272 return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
1273
1274 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1275 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1276 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1277 return getValueFromOverflowCondition(Val, WO, IsTrueDest);
1278
1281
1282 Value *N;
1283 if (match(Cond, m_Not(m_Value(N))))
1284 return getValueFromCondition(Val, N, !IsTrueDest, UseBlockValue, Depth);
1285
1286 Value *L, *R;
1287 bool IsAnd;
1288 if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1289 IsAnd = true;
1290 else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1291 IsAnd = false;
1292 else
1294
1295 std::optional<ValueLatticeElement> LV =
1296 getValueFromCondition(Val, L, IsTrueDest, UseBlockValue, Depth);
1297 if (!LV)
1298 return std::nullopt;
1299 std::optional<ValueLatticeElement> RV =
1300 getValueFromCondition(Val, R, IsTrueDest, UseBlockValue, Depth);
1301 if (!RV)
1302 return std::nullopt;
1303
1304 // if (L && R) -> intersect L and R
1305 // if (!(L || R)) -> intersect !L and !R
1306 // if (L || R) -> union L and R
1307 // if (!(L && R)) -> union !L and !R
1308 if (IsTrueDest ^ IsAnd) {
1309 LV->mergeIn(*RV);
1310 return *LV;
1311 }
1312
1313 return intersect(*LV, *RV);
1314}
1315
1316// Return true if Usr has Op as an operand, otherwise false.
1317static bool usesOperand(User *Usr, Value *Op) {
1318 return is_contained(Usr->operands(), Op);
1319}
1320
1321// Return true if the instruction type of Val is supported by
1322// constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1323// Call this before calling constantFoldUser() to find out if it's even worth
1324// attempting to call it.
1325static bool isOperationFoldable(User *Usr) {
1326 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1327}
1328
1329// Check if Usr can be simplified to an integer constant when the value of one
1330// of its operands Op is an integer constant OpConstVal. If so, return it as an
1331// lattice value range with a single element or otherwise return an overdefined
1332// lattice value.
1334 const APInt &OpConstVal,
1335 const DataLayout &DL) {
1336 assert(isOperationFoldable(Usr) && "Precondition");
1337 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1338 // Check if Usr can be simplified to a constant.
1339 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1340 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1341 if (auto *C = dyn_cast_or_null<ConstantInt>(
1342 simplifyCastInst(CI->getOpcode(), OpConst,
1343 CI->getDestTy(), DL))) {
1344 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1345 }
1346 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1347 bool Op0Match = BO->getOperand(0) == Op;
1348 bool Op1Match = BO->getOperand(1) == Op;
1349 assert((Op0Match || Op1Match) &&
1350 "Operand 0 nor Operand 1 isn't a match");
1351 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1352 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1353 if (auto *C = dyn_cast_or_null<ConstantInt>(
1354 simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1355 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1356 }
1357 } else if (isa<FreezeInst>(Usr)) {
1358 assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1359 return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1360 }
1362}
1363
1364/// Compute the value of Val on the edge BBFrom -> BBTo.
1365std::optional<ValueLatticeElement>
1366LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1367 BasicBlock *BBTo, bool UseBlockValue) {
1368 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1369 // know that v != 0.
1370 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1371 // If this is a conditional branch and only one successor goes to BBTo, then
1372 // we may be able to infer something from the condition.
1373 if (BI->isConditional() &&
1374 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1375 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1376 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1377 "BBTo isn't a successor of BBFrom");
1378 Value *Condition = BI->getCondition();
1379
1380 // If V is the condition of the branch itself, then we know exactly what
1381 // it is.
1382 // NB: The condition on a `br` can't be a vector type.
1383 if (Condition == Val)
1384 return ValueLatticeElement::get(ConstantInt::get(
1385 Type::getInt1Ty(Val->getContext()), isTrueDest));
1386
1387 // If the condition of the branch is an equality comparison, we may be
1388 // able to infer the value.
1389 std::optional<ValueLatticeElement> Result =
1390 getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1391 if (!Result)
1392 return std::nullopt;
1393
1394 if (!Result->isOverdefined())
1395 return Result;
1396
1397 if (User *Usr = dyn_cast<User>(Val)) {
1398 assert(Result->isOverdefined() && "Result isn't overdefined");
1399 // Check with isOperationFoldable() first to avoid linearly iterating
1400 // over the operands unnecessarily which can be expensive for
1401 // instructions with many operands.
1402 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1403 const DataLayout &DL = BBTo->getDataLayout();
1404 if (usesOperand(Usr, Condition)) {
1405 // If Val has Condition as an operand and Val can be folded into a
1406 // constant with either Condition == true or Condition == false,
1407 // propagate the constant.
1408 // eg.
1409 // ; %Val is true on the edge to %then.
1410 // %Val = and i1 %Condition, true.
1411 // br %Condition, label %then, label %else
1412 APInt ConditionVal(1, isTrueDest ? 1 : 0);
1413 Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1414 } else {
1415 // If one of Val's operand has an inferred value, we may be able to
1416 // infer the value of Val.
1417 // eg.
1418 // ; %Val is 94 on the edge to %then.
1419 // %Val = add i8 %Op, 1
1420 // %Condition = icmp eq i8 %Op, 93
1421 // br i1 %Condition, label %then, label %else
1422 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1423 Value *Op = Usr->getOperand(i);
1424 ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1425 Op, Condition, isTrueDest, /*UseBlockValue*/ false);
1426 if (std::optional<APInt> OpConst =
1427 OpLatticeVal.asConstantInteger()) {
1428 Result = constantFoldUser(Usr, Op, *OpConst, DL);
1429 break;
1430 }
1431 }
1432 }
1433 }
1434 }
1435 if (!Result->isOverdefined())
1436 return Result;
1437 }
1438 }
1439
1440 // If the edge was formed by a switch on the value, then we may know exactly
1441 // what it is.
1442 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1443 Value *Condition = SI->getCondition();
1444 if (!isa<IntegerType>(Val->getType()))
1446 bool ValUsesConditionAndMayBeFoldable = false;
1447 if (Condition != Val) {
1448 // Check if Val has Condition as an operand.
1449 if (User *Usr = dyn_cast<User>(Val))
1450 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1451 usesOperand(Usr, Condition);
1452 if (!ValUsesConditionAndMayBeFoldable)
1454 }
1455 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1456 "Condition != Val nor Val doesn't use Condition");
1457
1458 bool DefaultCase = SI->getDefaultDest() == BBTo;
1459 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1460 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1461
1462 for (auto Case : SI->cases()) {
1463 APInt CaseValue = Case.getCaseValue()->getValue();
1464 ConstantRange EdgeVal(CaseValue);
1465 if (ValUsesConditionAndMayBeFoldable) {
1466 User *Usr = cast<User>(Val);
1467 const DataLayout &DL = BBTo->getDataLayout();
1468 ValueLatticeElement EdgeLatticeVal =
1469 constantFoldUser(Usr, Condition, CaseValue, DL);
1470 if (EdgeLatticeVal.isOverdefined())
1472 EdgeVal = EdgeLatticeVal.getConstantRange();
1473 }
1474 if (DefaultCase) {
1475 // It is possible that the default destination is the destination of
1476 // some cases. We cannot perform difference for those cases.
1477 // We know Condition != CaseValue in BBTo. In some cases we can use
1478 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1479 // only do this when f is identity (i.e. Val == Condition), but we
1480 // should be able to do this for any injective f.
1481 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1482 EdgesVals = EdgesVals.difference(EdgeVal);
1483 } else if (Case.getCaseSuccessor() == BBTo)
1484 EdgesVals = EdgesVals.unionWith(EdgeVal);
1485 }
1486 return ValueLatticeElement::getRange(std::move(EdgesVals));
1487 }
1489}
1490
1491/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1492/// the basic block if the edge does not constrain Val.
1493std::optional<ValueLatticeElement>
1494LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1495 BasicBlock *BBTo, Instruction *CxtI) {
1496 // If already a constant, there is nothing to compute.
1497 if (Constant *VC = dyn_cast<Constant>(Val))
1498 return ValueLatticeElement::get(VC);
1499
1500 std::optional<ValueLatticeElement> LocalResult =
1501 getEdgeValueLocal(Val, BBFrom, BBTo, /*UseBlockValue*/ true);
1502 if (!LocalResult)
1503 return std::nullopt;
1504
1505 if (hasSingleValue(*LocalResult))
1506 // Can't get any more precise here
1507 return LocalResult;
1508
1509 std::optional<ValueLatticeElement> OptInBlock =
1510 getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1511 if (!OptInBlock)
1512 return std::nullopt;
1513 ValueLatticeElement &InBlock = *OptInBlock;
1514
1515 // We can use the context instruction (generically the ultimate instruction
1516 // the calling pass is trying to simplify) here, even though the result of
1517 // this function is generally cached when called from the solve* functions
1518 // (and that cached result might be used with queries using a different
1519 // context instruction), because when this function is called from the solve*
1520 // functions, the context instruction is not provided. When called from
1521 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1522 // but then the result is not cached.
1523 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1524
1525 return intersect(*LocalResult, InBlock);
1526}
1527
1529 Instruction *CxtI) {
1530 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1531 << BB->getName() << "'\n");
1532
1533 assert(BlockValueStack.empty() && BlockValueSet.empty());
1534 std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1535 if (!OptResult) {
1536 solve();
1537 OptResult = getBlockValue(V, BB, CxtI);
1538 assert(OptResult && "Value not available after solving");
1539 }
1540
1541 ValueLatticeElement Result = *OptResult;
1542 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
1543 return Result;
1544}
1545
1547 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
1548 << "'\n");
1549
1550 if (auto *C = dyn_cast<Constant>(V))
1552
1554 if (auto *I = dyn_cast<Instruction>(V))
1555 Result = getFromRangeMetadata(I);
1556 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1557
1558 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
1559 return Result;
1560}
1561
1563getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1564 Instruction *CxtI) {
1565 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1566 << FromBB->getName() << "' to '" << ToBB->getName()
1567 << "'\n");
1568
1569 std::optional<ValueLatticeElement> Result =
1570 getEdgeValue(V, FromBB, ToBB, CxtI);
1571 while (!Result) {
1572 // As the worklist only explicitly tracks block values (but not edge values)
1573 // we may have to call solve() multiple times, as the edge value calculation
1574 // may request additional block values.
1575 solve();
1576 Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1577 }
1578
1579 LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n");
1580 return *Result;
1581}
1582
1584 Value *V = U.get();
1585 auto *CxtI = cast<Instruction>(U.getUser());
1586 ValueLatticeElement VL = getValueInBlock(V, CxtI->getParent(), CxtI);
1587
1588 // Check whether the only (possibly transitive) use of the value is in a
1589 // position where V can be constrained by a select or branch condition.
1590 const Use *CurrU = &U;
1591 // TODO: Increase limit?
1592 const unsigned MaxUsesToInspect = 3;
1593 for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
1594 std::optional<ValueLatticeElement> CondVal;
1595 auto *CurrI = cast<Instruction>(CurrU->getUser());
1596 if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
1597 // If the value is undef, a different value may be chosen in
1598 // the select condition and at use.
1599 if (!isGuaranteedNotToBeUndef(SI->getCondition(), AC))
1600 break;
1601 if (CurrU->getOperandNo() == 1)
1602 CondVal =
1603 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ true,
1604 /*UseBlockValue*/ false);
1605 else if (CurrU->getOperandNo() == 2)
1606 CondVal =
1607 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ false,
1608 /*UseBlockValue*/ false);
1609 } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
1610 // TODO: Use non-local query?
1611 CondVal = *getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU),
1612 PHI->getParent(), /*UseBlockValue*/ false);
1613 }
1614 if (CondVal)
1615 VL = intersect(VL, *CondVal);
1616
1617 // Only follow one-use chain, to allow direct intersection of conditions.
1618 // If there are multiple uses, we would have to intersect with the union of
1619 // all conditions at different uses.
1620 // Stop walking if we hit a non-speculatable instruction. Even if the
1621 // result is only used under a specific condition, executing the
1622 // instruction itself may cause side effects or UB already.
1623 // This also disallows looking through phi nodes: If the phi node is part
1624 // of a cycle, we might end up reasoning about values from different cycle
1625 // iterations (PR60629).
1626 if (!CurrI->hasOneUse() || !isSafeToSpeculativelyExecute(CurrI))
1627 break;
1628 CurrU = &*CurrI->use_begin();
1629 }
1630 return VL;
1631}
1632
1634 BasicBlock *NewSucc) {
1635 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// LazyValueInfo Impl
1640//===----------------------------------------------------------------------===//
1641
1643 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1644
1645 if (auto *Impl = Info.getImpl())
1646 Impl->clear();
1647
1648 // Fully lazy.
1649 return false;
1650}
1651
1653 AU.setPreservesAll();
1656}
1657
1659
1660/// This lazily constructs the LazyValueInfoImpl.
1661LazyValueInfoImpl &LazyValueInfo::getOrCreateImpl(const Module *M) {
1662 if (!PImpl) {
1663 assert(M && "getCache() called with a null Module");
1664 const DataLayout &DL = M->getDataLayout();
1665 Function *GuardDecl =
1666 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
1667 PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
1668 }
1669 return *static_cast<LazyValueInfoImpl *>(PImpl);
1670}
1671
1672LazyValueInfoImpl *LazyValueInfo::getImpl() {
1673 if (!PImpl)
1674 return nullptr;
1675 return static_cast<LazyValueInfoImpl *>(PImpl);
1676}
1677
1679
1681 // If the cache was allocated, free it.
1682 if (auto *Impl = getImpl()) {
1683 delete &*Impl;
1684 PImpl = nullptr;
1685 }
1686}
1687
1690 // We need to invalidate if we have either failed to preserve this analyses
1691 // result directly or if any of its dependencies have been invalidated.
1692 auto PAC = PA.getChecker<LazyValueAnalysis>();
1693 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1694 return true;
1695
1696 return false;
1697}
1698
1700
1703 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1704
1705 return LazyValueInfo(&AC, &F.getDataLayout());
1706}
1707
1708/// Returns true if we can statically tell that this value will never be a
1709/// "useful" constant. In practice, this means we've got something like an
1710/// alloca or a malloc call for which a comparison against a constant can
1711/// only be guarding dead code. Note that we are potentially giving up some
1712/// precision in dead code (a constant result) in favour of avoiding a
1713/// expensive search for a easily answered common query.
1714static bool isKnownNonConstant(Value *V) {
1715 V = V->stripPointerCasts();
1716 // The return val of alloc cannot be a Constant.
1717 if (isa<AllocaInst>(V))
1718 return true;
1719 return false;
1720}
1721
1723 // Bail out early if V is known not to be a Constant.
1724 if (isKnownNonConstant(V))
1725 return nullptr;
1726
1727 BasicBlock *BB = CxtI->getParent();
1728 ValueLatticeElement Result =
1729 getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
1730
1731 if (Result.isConstant())
1732 return Result.getConstant();
1733 if (Result.isConstantRange()) {
1734 const ConstantRange &CR = Result.getConstantRange();
1735 if (const APInt *SingleVal = CR.getSingleElement())
1736 return ConstantInt::get(V->getType(), *SingleVal);
1737 }
1738 return nullptr;
1739}
1740
1742 bool UndefAllowed) {
1743 BasicBlock *BB = CxtI->getParent();
1744 ValueLatticeElement Result =
1745 getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
1746 return Result.asConstantRange(V->getType(), UndefAllowed);
1747}
1748
1750 bool UndefAllowed) {
1751 auto *Inst = cast<Instruction>(U.getUser());
1752 ValueLatticeElement Result =
1753 getOrCreateImpl(Inst->getModule()).getValueAtUse(U);
1754 return Result.asConstantRange(U->getType(), UndefAllowed);
1755}
1756
1757/// Determine whether the specified value is known to be a
1758/// constant on the specified edge. Return null if not.
1760 BasicBlock *ToBB,
1761 Instruction *CxtI) {
1762 Module *M = FromBB->getModule();
1763 ValueLatticeElement Result =
1764 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1765
1766 if (Result.isConstant())
1767 return Result.getConstant();
1768 if (Result.isConstantRange()) {
1769 const ConstantRange &CR = Result.getConstantRange();
1770 if (const APInt *SingleVal = CR.getSingleElement())
1771 return ConstantInt::get(V->getType(), *SingleVal);
1772 }
1773 return nullptr;
1774}
1775
1777 BasicBlock *FromBB,
1778 BasicBlock *ToBB,
1779 Instruction *CxtI) {
1780 Module *M = FromBB->getModule();
1781 ValueLatticeElement Result =
1782 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1783 // TODO: Should undef be allowed here?
1784 return Result.asConstantRange(V->getType(), /*UndefAllowed*/ true);
1785}
1786
1788 const ValueLatticeElement &Val,
1789 const DataLayout &DL) {
1790 // If we know the value is a constant, evaluate the conditional.
1791 if (Val.isConstant())
1792 return ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL);
1793
1794 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
1795 if (Val.isConstantRange()) {
1796 const ConstantRange &CR = Val.getConstantRange();
1797 ConstantRange RHS = C->toConstantRange();
1798 if (CR.icmp(Pred, RHS))
1799 return ConstantInt::getTrue(ResTy);
1800 if (CR.icmp(CmpInst::getInversePredicate(Pred), RHS))
1801 return ConstantInt::getFalse(ResTy);
1802 return nullptr;
1803 }
1804
1805 if (Val.isNotConstant()) {
1806 // If this is an equality comparison, we can try to fold it knowing that
1807 // "V != C1".
1808 if (Pred == ICmpInst::ICMP_EQ) {
1809 // !C1 == C -> false iff C1 == C.
1812 if (Res && Res->isNullValue())
1813 return ConstantInt::getFalse(ResTy);
1814 } else if (Pred == ICmpInst::ICMP_NE) {
1815 // !C1 != C -> true iff C1 == C.
1818 if (Res && Res->isNullValue())
1819 return ConstantInt::getTrue(ResTy);
1820 }
1821 return nullptr;
1822 }
1823
1824 return nullptr;
1825}
1826
1827/// Determine whether the specified value comparison with a constant is known to
1828/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1830 Constant *C, BasicBlock *FromBB,
1831 BasicBlock *ToBB,
1832 Instruction *CxtI) {
1833 Module *M = FromBB->getModule();
1834 ValueLatticeElement Result =
1835 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1836
1837 return getPredicateResult(Pred, C, Result, M->getDataLayout());
1838}
1839
1841 Constant *C, Instruction *CxtI,
1842 bool UseBlockValue) {
1843 // Is or is not NonNull are common predicates being queried. If
1844 // isKnownNonZero can tell us the result of the predicate, we can
1845 // return it quickly. But this is only a fastpath, and falling
1846 // through would still be correct.
1847 Module *M = CxtI->getModule();
1848 const DataLayout &DL = M->getDataLayout();
1849 if (V->getType()->isPointerTy() && C->isNullValue() &&
1850 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1851 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
1852 if (Pred == ICmpInst::ICMP_EQ)
1853 return ConstantInt::getFalse(ResTy);
1854 else if (Pred == ICmpInst::ICMP_NE)
1855 return ConstantInt::getTrue(ResTy);
1856 }
1857
1858 auto &Impl = getOrCreateImpl(M);
1859 ValueLatticeElement Result =
1860 UseBlockValue ? Impl.getValueInBlock(V, CxtI->getParent(), CxtI)
1861 : Impl.getValueAt(V, CxtI);
1862 Constant *Ret = getPredicateResult(Pred, C, Result, DL);
1863 if (Ret)
1864 return Ret;
1865
1866 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1867 // LVI as a whole tries to compute a lattice value which is conservatively
1868 // correct at a given location. In this case, we have a predicate which we
1869 // weren't able to prove about the merged result, and we're pushing that
1870 // predicate back along each incoming edge to see if we can prove it
1871 // separately for each input. As a motivating example, consider:
1872 // bb1:
1873 // %v1 = ... ; constantrange<1, 5>
1874 // br label %merge
1875 // bb2:
1876 // %v2 = ... ; constantrange<10, 20>
1877 // br label %merge
1878 // merge:
1879 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1880 // %pred = icmp eq i32 %phi, 8
1881 // We can't tell from the lattice value for '%phi' that '%pred' is false
1882 // along each path, but by checking the predicate over each input separately,
1883 // we can.
1884 // We limit the search to one step backwards from the current BB and value.
1885 // We could consider extending this to search further backwards through the
1886 // CFG and/or value graph, but there are non-obvious compile time vs quality
1887 // tradeoffs.
1888 BasicBlock *BB = CxtI->getParent();
1889
1890 // Function entry or an unreachable block. Bail to avoid confusing
1891 // analysis below.
1892 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1893 if (PI == PE)
1894 return nullptr;
1895
1896 // If V is a PHI node in the same block as the context, we need to ask
1897 // questions about the predicate as applied to the incoming value along
1898 // each edge. This is useful for eliminating cases where the predicate is
1899 // known along all incoming edges.
1900 if (auto *PHI = dyn_cast<PHINode>(V))
1901 if (PHI->getParent() == BB) {
1902 Constant *Baseline = nullptr;
1903 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1904 Value *Incoming = PHI->getIncomingValue(i);
1905 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1906 // Note that PredBB may be BB itself.
1907 Constant *Result =
1908 getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
1909
1910 // Keep going as long as we've seen a consistent known result for
1911 // all inputs.
1912 Baseline = (i == 0) ? Result /* First iteration */
1913 : (Baseline == Result ? Baseline
1914 : nullptr); /* All others */
1915 if (!Baseline)
1916 break;
1917 }
1918 if (Baseline)
1919 return Baseline;
1920 }
1921
1922 // For a comparison where the V is outside this block, it's possible
1923 // that we've branched on it before. Look to see if the value is known
1924 // on all incoming edges.
1925 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
1926 // For predecessor edge, determine if the comparison is true or false
1927 // on that edge. If they're all true or all false, we can conclude
1928 // the value of the comparison in this block.
1929 Constant *Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1930 if (Baseline) {
1931 // Check that all remaining incoming values match the first one.
1932 while (++PI != PE) {
1933 Constant *Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1934 if (Ret != Baseline)
1935 break;
1936 }
1937 // If we terminated early, then one of the values didn't match.
1938 if (PI == PE) {
1939 return Baseline;
1940 }
1941 }
1942 }
1943
1944 return nullptr;
1945}
1946
1948 Value *RHS, Instruction *CxtI,
1949 bool UseBlockValue) {
1950 if (auto *C = dyn_cast<Constant>(RHS))
1951 return getPredicateAt(Pred, LHS, C, CxtI, UseBlockValue);
1952 if (auto *C = dyn_cast<Constant>(LHS))
1953 return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1954 UseBlockValue);
1955
1956 // Got two non-Constant values. Try to determine the comparison results based
1957 // on the block values of the two operands, e.g. because they have
1958 // non-overlapping ranges.
1959 if (UseBlockValue) {
1960 Module *M = CxtI->getModule();
1962 getOrCreateImpl(M).getValueInBlock(LHS, CxtI->getParent(), CxtI);
1963 if (L.isOverdefined())
1964 return nullptr;
1965
1967 getOrCreateImpl(M).getValueInBlock(RHS, CxtI->getParent(), CxtI);
1969 return L.getCompare(Pred, Ty, R, M->getDataLayout());
1970 }
1971 return nullptr;
1972}
1973
1975 BasicBlock *NewSucc) {
1976 if (auto *Impl = getImpl())
1977 Impl->threadEdge(PredBB, OldSucc, NewSucc);
1978}
1979
1981 if (auto *Impl = getImpl())
1982 Impl->forgetValue(V);
1983}
1984
1986 if (auto *Impl = getImpl())
1987 Impl->eraseBlock(BB);
1988}
1989
1991 if (auto *Impl = getImpl())
1992 Impl->clear();
1993}
1994
1996 if (auto *Impl = getImpl())
1997 Impl->printLVI(F, DTree, OS);
1998}
1999
2000// Print the LVI for the function arguments at the start of each basic block.
2001void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2002 const BasicBlock *BB, formatted_raw_ostream &OS) {
2003 // Find if there are latticevalues defined for arguments of the function.
2004 auto *F = BB->getParent();
2005 for (const auto &Arg : F->args()) {
2006 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2007 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2008 if (Result.isUnknown())
2009 continue;
2010 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
2011 }
2012}
2013
2014// This function prints the LVI analysis for the instruction I at the beginning
2015// of various basic blocks. It relies on calculated values that are stored in
2016// the LazyValueInfoCache, and in the absence of cached values, recalculate the
2017// LazyValueInfo for `I`, and print that info.
2018void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2020
2021 auto *ParentBB = I->getParent();
2022 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2023 // We can generate (solve) LVI values only for blocks that are dominated by
2024 // the I's parent. However, to avoid generating LVI for all dominating blocks,
2025 // that contain redundant/uninteresting information, we print LVI for
2026 // blocks that may use this LVI information (such as immediate successor
2027 // blocks, and blocks that contain uses of `I`).
2028 auto printResult = [&](const BasicBlock *BB) {
2029 if (!BlocksContainingLVI.insert(BB).second)
2030 return;
2031 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2032 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2033 OS << "; LatticeVal for: '" << *I << "' in BB: '";
2034 BB->printAsOperand(OS, false);
2035 OS << "' is: " << Result << "\n";
2036 };
2037
2038 printResult(ParentBB);
2039 // Print the LVI analysis results for the immediate successor blocks, that
2040 // are dominated by `ParentBB`.
2041 for (const auto *BBSucc : successors(ParentBB))
2042 if (DT.dominates(ParentBB, BBSucc))
2043 printResult(BBSucc);
2044
2045 // Print LVI in blocks where `I` is used.
2046 for (const auto *U : I->users())
2047 if (auto *UseI = dyn_cast<Instruction>(U))
2048 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2049 printResult(UseI->getParent());
2050
2051}
2052
2055 OS << "LVI for function '" << F.getName() << "':\n";
2056 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
2057 auto &DTree = AM.getResult<DominatorTreeAnalysis>(F);
2058 LVI.printLVI(F, DTree, OS);
2059 return PreservedAnalyses::all();
2060}
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
basic Basic Alias true
block Block Frequency Analysis
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:148
Given that RA is a live value
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseSet and SmallDenseSet classes.
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static std::optional< ConstantRange > getRange(Value *V, const InstrInfoQuery &IIQ)
Helper method to get range from metadata or attribute.
static bool isOperationFoldable(User *Usr)
static void AddNonNullPointersByInstruction(Instruction *I, NonNullPointerSet &PtrSet)
static std::optional< ConstantRange > getRangeViaSLT(CmpInst::Predicate Pred, APInt RHS, function_ref< std::optional< ConstantRange >(const APInt &)> Fn)
static bool hasSingleValue(const ValueLatticeElement &Val)
Returns true if this lattice value represents at most one possible value.
static const unsigned MaxProcessedPerValue
static bool usesOperand(User *Usr, Value *Op)
static ValueLatticeElement constantFoldUser(User *Usr, Value *Op, const APInt &OpConstVal, const DataLayout &DL)
static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet)
static ValueLatticeElement getFromRangeMetadata(Instruction *BBI)
static ValueLatticeElement intersect(const ValueLatticeElement &A, const ValueLatticeElement &B)
Combine two sets of facts about the same value into a single set of facts.
static Constant * getPredicateResult(CmpInst::Predicate Pred, Constant *C, const ValueLatticeElement &Val, const DataLayout &DL)
static ValueLatticeElement getValueFromOverflowCondition(Value *Val, WithOverflowInst *WO, bool IsTrueDest)
lazy value info
static bool isKnownNonConstant(Value *V)
Returns true if we can statically tell that this value will never be a "useful" constant.
static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val, ICmpInst::Predicate Pred)
Natural Loop Information
Definition: LoopInfo.cpp:1209
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
static bool InBlock(const Value *V, const BasicBlock *BB)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:981
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:199
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:180
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
Definition: Analysis.h:49
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:292
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
void clear()
Clear the cache of @llvm.assume intrinsics for a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition: BasicBlock.cpp:571
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition: BasicBlock.cpp:296
reverse_iterator rend()
Definition: BasicBlock.h:466
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
const Instruction & back() const
Definition: BasicBlock.h:473
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:292
Value * getRHS() const
unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
Value * getLHS() const
BinaryOps getOpcode() const
Definition: InstrTypes.h:442
Conditional or Unconditional Branch instruction.
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:383
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:530
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition: InstrTypes.h:694
Type * getDestTy() const
Return the destination type, as a convenience.
Definition: InstrTypes.h:701
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1104
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:786
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:787
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:781
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:780
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:784
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:782
@ ICMP_EQ
equal
Definition: InstrTypes.h:778
@ ICMP_NE
not equal
Definition: InstrTypes.h:779
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:785
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:783
bool isSigned() const
Definition: InstrTypes.h:1007
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:909
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:871
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:847
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:850
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:857
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1800
This class represents a range of values.
Definition: ConstantRange.h:47
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
static ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
static ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
bool isEmptySet() const
Return true if this set contains no members.
ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
static bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
ConstantRange overflowingBinaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind) const
Return a new range representing the possible values resulting from an application of the specified ov...
bool isSingleElement() const
Return true if this set contains exactly one member.
ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
static ConstantRange makeMaskNotEqualRange(const APInt &Mask, const APInt &C)
Initialize a range containing all values X that satisfy (X & Mask) != C.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
Definition: ConstantRange.h:84
ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
static ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:400
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition: DenseMap.h:176
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
idx_iterator idx_begin() const
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
This instruction inserts a single (scalar) element into a VectorType value.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:66
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:381
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Definition: Instruction.cpp:74
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
Analysis to compute lazy value information.
Result run(Function &F, FunctionAnalysisManager &FAM)
ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
This is the query interface to determine the lattice value for the specified Value* that is true on t...
ValueLatticeElement getValueAt(Value *V, Instruction *CxtI)
This is the query interface to determine the lattice value for the specified Value* at the specified ...
void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
This is the update interface to inform the cache that an edge from PredBB to OldSucc has been threade...
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Printing the LazyValueInfo Analysis.
void forgetValue(Value *V)
This is part of the update interface to remove information related to this value from the cache.
void eraseBlock(BasicBlock *BB)
This is part of the update interface to inform the cache that a block has been deleted.
void clear()
Complete flush all previously computed values.
LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL, Function *GuardDecl)
ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
This is the query interface to determine the lattice value for the specified Value* at the context in...
ValueLatticeElement getValueAtUse(const Use &U)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Wrapper around LazyValueInfo.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
This pass computes, caches, and vends lazy value constraint information.
Definition: LazyValueInfo.h:34
void eraseBlock(BasicBlock *BB)
Inform the analysis cache that we have erased a block.
ConstantRange getConstantRangeAtUse(const Use &U, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the value at a specific use-site.
ConstantRange getConstantRange(Value *V, Instruction *CxtI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
Inform the analysis cache that we have threaded an edge from PredBB to OldSucc to be from PredBB to N...
Constant * getPredicateOnEdge(CmpInst::Predicate Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
ConstantRange getConstantRangeOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Return the ConstantRage constraint that is known to hold for the specified value on the specified edg...
Constant * getConstant(Value *V, Instruction *CxtI)
Determine whether the specified value is known to be a constant at the specified instruction.
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Print the \LazyValueInfo Analysis.
void forgetValue(Value *V)
Remove information related to this value from the cache.
void clear()
Complete flush all previously computed values.
Constant * getPredicateAt(CmpInst::Predicate Pred, Value *V, Constant *C, Instruction *CxtI, bool UseBlockValue)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
An instruction for reading from memory.
Definition: Instructions.h:174
Metadata node.
Definition: Metadata.h:1069
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memcpy/memmove intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: Analysis.h:264
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:368
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:503
void push_back(const T &Elt)
Definition: SmallVector.h:427
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1210
An instruction for storing to memory.
Definition: Instructions.h:290
Multiway switch.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getIntegerBitWidth() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:230
static IntegerType * getInt1Ty(LLVMContext &C)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:298
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:224
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
Value * getOperand(unsigned i) const
Definition: User.h:169
This class represents lattice values for constants.
Definition: ValueLattice.h:29
static ValueLatticeElement getRange(ConstantRange CR, bool MayIncludeUndef=false)
Definition: ValueLattice.h:214
static ValueLatticeElement getNot(Constant *C)
Definition: ValueLattice.h:208
std::optional< APInt > asConstantInteger() const
Definition: ValueLattice.h:275
const ConstantRange & getConstantRange(bool UndefAllowed=true) const
Returns the constant range for this value.
Definition: ValueLattice.h:269
bool isConstantRange(bool UndefAllowed=true) const
Returns true if this value is a constant range.
Definition: ValueLattice.h:249
static ValueLatticeElement get(Constant *C)
Definition: ValueLattice.h:203
Constant * getNotConstant() const
Definition: ValueLattice.h:260
Constant * getConstant() const
Definition: ValueLattice.h:255
bool mergeIn(const ValueLatticeElement &RHS, MergeOptions Opts=MergeOptions())
Updates this object to approximate both this object and RHS.
Definition: ValueLattice.h:402
static ValueLatticeElement getOverdefined()
Definition: ValueLattice.h:231
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition: Value.cpp:786
use_iterator use_begin()
Definition: Value.h:360
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:5106
bool use_empty() const
Definition: Value.h:344
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
iterator find_as(const LookupKeyT &Val)
Alternative version of find() which allows a different, and possibly less expensive,...
Definition: DenseSet.h:195
bool erase(const ValueT &V)
Definition: DenseSet.h:101
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
@ Entry
Definition: COFF.h:826
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:1096
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:875
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
Definition: PatternMatch.h:239
constexpr double e
Definition: MathExtras.h:47
@ FalseVal
Definition: TGLexer.h:59
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
pred_iterator pred_end(BasicBlock *BB)
Definition: CFG.h:114
@ Offset
Definition: DWP.cpp:480
bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto successors(const MachineBasicBlock *BB)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2073
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
FunctionPass * createLazyValueInfoPass()
createLazyValueInfoPass - This creates an instance of the LazyValueInfo pass.
pred_iterator pred_begin(BasicBlock *BB)
Definition: CFG.h:110
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:48
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:2132
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
void initializeLazyValueInfoWrapperPassPass(PassRegistry &)
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:28
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?