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