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