LLVM 24.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 "AnalysisOptions.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
27#include "llvm/IR/CFG.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Dominators.h"
32#include "llvm/IR/InstrTypes.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Module.h"
39#include "llvm/IR/ValueHandle.h"
41#include "llvm/Support/Debug.h"
45#include <optional>
46using namespace llvm;
47using namespace PatternMatch;
48
49#define DEBUG_TYPE "lazy-value-info"
50
51// This is the number of worklist items we will process to try to discover an
52// answer for a given value.
53static const unsigned MaxProcessedPerValue = 500;
54
58 "Lazy Value Information Analysis", false, true)
62 "Lazy Value Information Analysis", false, true)
63
64namespace llvm {
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>;
108using BBLatticeElementMap =
110using PredecessorValueLatticeMap =
111 SmallDenseMap<AssertingVH<Value>, BBLatticeElementMap, 2>;
112
113/// This is the cache kept by LazyValueInfo which
114/// maintains information about queries across the clients' queries.
115class LazyValueInfoCache {
116 /// This is all of the cached information for one basic block. It contains
117 /// the per-value lattice elements, as well as a separate set for
118 /// overdefined values to reduce memory usage. Additionally pointers
119 /// dereferenced in the block are cached for nullability queries.
120 struct BlockCacheEntry {
121 SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
122 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
123 // std::nullopt indicates that the nonnull pointers for this basic block
124 // block have not been computed yet.
125 std::optional<NonNullPointerSet> NonNullPointers;
126 // This is an extension of the above LatticeElements, caching, for each
127 // Value, a ValueLatticeElement, for each predecessor of the BB tracked by
128 // this entry.
129 std::optional<PredecessorValueLatticeMap> PredecessorLatticeElements;
130 };
131
132 const bool PerPredRanges;
133
134 /// Cached information per basic block, indexed by block number.
136 /// Set of value handles used to erase values from the cache on deletion.
137 DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
138 /// Block number epoch on construction.
139 unsigned BlockNumberEpoch;
140
141 const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
142 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
143 if (BB->getNumber() < BlockCache.size())
144 return BlockCache[BB->getNumber()].get();
145 return nullptr;
146 }
147
148 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
149 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
150 unsigned Number = BB->getNumber();
151 if (Number >= BlockCache.size())
152 BlockCache.resize(BB->getParent()->getMaxBlockNumber());
153
154 if (BlockCacheEntry *Entry = BlockCache[Number].get())
155 return Entry;
156
157 BlockCache[Number] = std::make_unique<BlockCacheEntry>();
158 if (PerPredRanges)
159 BlockCache[Number]->PredecessorLatticeElements =
160 std::make_optional<PredecessorValueLatticeMap>();
161
162 return BlockCache[Number].get();
163 }
164
165 void addValueHandle(Value *Val) {
166 auto HandleIt = ValueHandles.find_as(Val);
167 if (HandleIt == ValueHandles.end())
168 ValueHandles.insert({Val, this});
169 }
170
171public:
172 LazyValueInfoCache(const Function *F, bool PerPredRanges)
173 : PerPredRanges(PerPredRanges),
174 BlockNumberEpoch(F->getBlockNumberEpoch()) {}
175
176 void insertResult(Value *Val, BasicBlock *BB,
177 const ValueLatticeElement &Result) {
178 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
179
180 // Insert over-defined values into their own cache to reduce memory
181 // overhead.
182 if (Result.isOverdefined())
183 Entry->OverDefined.insert(Val);
184 else
185 Entry->LatticeElements.insert({Val, Result});
186
187 addValueHandle(Val);
188 }
189
190 void insertPredecessorResults(Value *Val, BasicBlock *BB,
191 BBLatticeElementMap &PredLatticeElements) {
192 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
193
194 Entry->PredecessorLatticeElements->insert({Val, PredLatticeElements});
195
196 addValueHandle(Val);
197 }
198
199 std::optional<BBLatticeElementMap>
200 getCachedPredecessorInfo(Value *V, BasicBlock *BB) const {
201 const BlockCacheEntry *Entry = getBlockEntry(BB);
202 if (!Entry)
203 return std::nullopt;
204
205 auto LatticeIt = Entry->PredecessorLatticeElements->find_as(V);
206 if (LatticeIt == Entry->PredecessorLatticeElements->end())
207 return std::nullopt;
208
209 return LatticeIt->second;
210 }
211
212 std::optional<ValueLatticeElement> getCachedValueInfo(Value *V,
213 BasicBlock *BB) const {
214 const BlockCacheEntry *Entry = getBlockEntry(BB);
215 if (!Entry)
216 return std::nullopt;
217
218 if (Entry->OverDefined.count(V))
220
221 auto LatticeIt = Entry->LatticeElements.find_as(V);
222 if (LatticeIt == Entry->LatticeElements.end())
223 return std::nullopt;
224
225 return LatticeIt->second;
226 }
227
228 bool
229 isNonNullAtEndOfBlock(Value *V, BasicBlock *BB,
230 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
231 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
232 if (!Entry->NonNullPointers) {
233 Entry->NonNullPointers = InitFn(BB);
234 for (Value *V : *Entry->NonNullPointers)
235 addValueHandle(V);
236 }
237
238 return Entry->NonNullPointers->count(V);
239 }
240
241 /// clear - Empty the cache.
242 void clear() {
243 BlockCache.clear();
244 ValueHandles.clear();
245 }
246
247 /// Inform the cache that a given value has been deleted.
248 void eraseValue(Value *V);
249
250 /// This is part of the update interface to inform the cache
251 /// that a block has been deleted.
252 void eraseBlock(BasicBlock *BB);
253
254 /// Updates the cache to remove any influence an overdefined value in
255 /// OldSucc might have (unless also overdefined in NewSucc). This just
256 /// flushes elements from the cache and does not add any.
257 void threadEdgeImpl(BasicBlock *OldSucc, BasicBlock *NewSucc);
258};
259} // namespace
260
261void LazyValueInfoCache::eraseValue(Value *V) {
262 for (auto &Elem : BlockCache) {
263 if (!Elem)
264 continue;
265
266 Elem->LatticeElements.erase(V);
267 Elem->OverDefined.erase(V);
268 if (Elem->NonNullPointers)
269 Elem->NonNullPointers->erase(V);
270 if (PerPredRanges)
271 Elem->PredecessorLatticeElements->erase(V);
272 }
273
274 auto HandleIt = ValueHandles.find_as(V);
275 if (HandleIt != ValueHandles.end())
276 ValueHandles.erase(HandleIt);
277}
278
279void LVIValueHandle::deleted() {
280 // This erasure deallocates *this, so it MUST happen after we're done
281 // using any and all members of *this.
282 Parent->eraseValue(*this);
283}
284
285void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
286 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
287 // Clear all when a BB is removed.
288 if (PerPredRanges)
289 for (auto &Elem : BlockCache)
290 if (Elem)
291 Elem->PredecessorLatticeElements->clear();
292 if (BB->getNumber() < BlockCache.size())
293 BlockCache[BB->getNumber()].reset();
294}
295
296void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
297 BasicBlock *NewSucc) {
298 // When an edge in the graph has been threaded, values that we could not
299 // determine a value for before (i.e. were marked overdefined) may be
300 // possible to solve now. We do NOT try to proactively update these values.
301 // Instead, we clear their entries from the cache, and allow lazy updating to
302 // recompute them when needed.
303
304 // The updating process is fairly simple: we need to drop cached info
305 // for all values that were marked overdefined in OldSucc, and for those same
306 // values in any successor of OldSucc (except NewSucc) in which they were
307 // also marked overdefined.
308 std::vector<BasicBlock*> worklist;
309 worklist.push_back(OldSucc);
310
311 const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
312 if (!Entry || Entry->OverDefined.empty())
313 return; // Nothing to process here.
314 SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
315 Entry->OverDefined.end());
316
317 // Use a worklist to perform a depth-first search of OldSucc's successors.
318 // NOTE: We do not need a visited list since any blocks we have already
319 // visited will have had their overdefined markers cleared already, and we
320 // thus won't loop to their successors.
321 while (!worklist.empty()) {
322 BasicBlock *ToUpdate = worklist.back();
323 worklist.pop_back();
324
325 // Skip blocks only accessible through NewSucc.
326 if (ToUpdate == NewSucc) continue;
327
328 // If a value was marked overdefined in OldSucc, and is here too...
329 BlockCacheEntry *WorklistEntry =
330 ToUpdate->getNumber() < BlockCache.size()
331 ? BlockCache[ToUpdate->getNumber()].get()
332 : nullptr;
333 if (!WorklistEntry || WorklistEntry->OverDefined.empty())
334 continue;
335 auto &ValueSet = WorklistEntry->OverDefined;
336
337 bool changed = false;
338 for (Value *V : ValsToClear) {
339 if (!ValueSet.erase(V))
340 continue;
341
342 // If we removed anything, then we potentially need to update
343 // blocks successors too.
344 changed = true;
345 }
346
347 if (!changed) continue;
348
349 llvm::append_range(worklist, successors(ToUpdate));
350 }
351}
352
353namespace llvm {
354namespace {
355/// An assembly annotator class to print LazyValueCache information in
356/// comments.
357class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
358 LazyValueInfoImpl *LVIImpl;
359 // While analyzing which blocks we can solve values for, we need the dominator
360 // information.
361 DominatorTree &DT;
362
363public:
364 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
365 : LVIImpl(L), DT(DTree) {}
366
367 void emitBasicBlockStartAnnot(const BasicBlock *BB,
368 formatted_raw_ostream &OS) override;
369
370 void emitInstructionAnnot(const Instruction *I,
371 formatted_raw_ostream &OS) override;
372};
373} // namespace
374// The actual implementation of the lazy analysis and update.
376 const bool PerPredRanges;
377
378 /// Cached results from previous queries
379 LazyValueInfoCache TheCache;
380
381 /// This stack holds the state of the value solver during a query.
382 /// It basically emulates the callstack of the naive
383 /// recursive value lookup process.
385
386 /// Keeps track of which block-value pairs are in BlockValueStack.
388
389 /// Push BV onto BlockValueStack unless it's already in there.
390 /// Returns true on success.
391 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
392 if (!BlockValueSet.insert(BV).second)
393 return false; // It's already in the stack.
394
395 LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
396 << BV.first->getName() << "\n");
397 BlockValueStack.push_back(BV);
398 return true;
399 }
400
401 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
402 const DataLayout &DL; ///< A mandatory DataLayout
403
404 /// Declaration of the llvm.experimental.guard() intrinsic,
405 /// if it exists in the module.
406 Function *GuardDecl;
407
408 std::optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
409 Instruction *CtxI);
410 std::optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
411 BasicBlock *T,
412 Instruction *CtxI = nullptr);
413
414 // These methods process one work item and may add more. A false value
415 // returned means that the work item was not completely processed and must
416 // be revisited after going through the new items.
417 bool solveBlockValue(Value *Val, BasicBlock *BB);
418 std::optional<ValueLatticeElement> solveBlockValueImpl(Value *Val,
419 BasicBlock *BB);
420 std::optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
421 BasicBlock *BB);
422 std::optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
423 BasicBlock *BB);
424 std::optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
425 BasicBlock *BB);
426 std::optional<ConstantRange> getRangeFor(Value *V, Instruction *CtxI,
427 BasicBlock *BB);
428 std::optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
430 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
431 OpFn);
432 std::optional<ValueLatticeElement>
433 solveBlockValueBinaryOp(BinaryOperator *BBI, BasicBlock *BB);
434 std::optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
435 BasicBlock *BB);
436 std::optional<ValueLatticeElement>
437 solveBlockValueOverflowIntrinsic(WithOverflowInst *WO, BasicBlock *BB);
438 std::optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
439 BasicBlock *BB);
440 std::optional<ValueLatticeElement>
441 solveBlockValueInsertElement(InsertElementInst *IEI, BasicBlock *BB);
442 std::optional<ValueLatticeElement>
443 solveBlockValueExtractValue(ExtractValueInst *EVI, BasicBlock *BB);
444 bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
445 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
447 Instruction *BBI);
448
449 void solve();
450
451 // For the following methods, if UseBlockValue is true, the function may
452 // push additional values to the worklist and return nullopt. If
453 // UseBlockValue is false, it will never return nullopt.
454
455 std::optional<ValueLatticeElement>
456 getValueFromSimpleICmpCondition(CmpInst::Predicate Pred, Value *RHS,
457 const APInt &Offset, Instruction *CtxI,
458 bool UseBlockValue);
459
460 std::optional<ValueLatticeElement>
461 getValueFromICmpCondition(Value *Val, ICmpInst *ICI, bool isTrueDest,
462 bool UseBlockValue);
463 ValueLatticeElement getValueFromTrunc(Value *Val, TruncInst *Trunc,
464 bool IsTrueDest);
465
466 std::optional<ValueLatticeElement>
467 getValueFromCondition(Value *Val, Value *Cond, bool IsTrueDest,
468 bool UseBlockValue, unsigned Depth = 0);
469
470 std::optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
471 BasicBlock *BBFrom,
472 BasicBlock *BBTo,
473 bool UseBlockValue);
474
475public:
476 /// This is the query interface to determine the lattice value for the
477 /// specified Value* at the context instruction (if specified) or at the
478 /// start of the block.
480 Instruction *CtxI = nullptr);
481
482 /// This is the query interface to determine the lattice value for the
483 /// specified Value* at the specified instruction using only information
484 /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
485 /// recursive query is performed.
487
488 /// This is the query interface to determine the lattice
489 /// value for the specified Value* that is true on the specified edge.
491 BasicBlock *ToBB,
492 Instruction *CtxI = nullptr);
493
495
496 /// Complete flush all previously computed values
497 void clear() {
498 TheCache.clear();
499 }
500
501 /// Printing the LazyValueInfo Analysis.
503 LazyValueInfoAnnotatedWriter Writer(this, DTree);
504 F.print(OS, &Writer);
505 }
506
507 /// This is part of the update interface to remove information related to this
508 /// value from the cache.
509 void forgetValue(Value *V) { TheCache.eraseValue(V); }
510
511 /// This is part of the update interface to inform the cache
512 /// that a block has been deleted.
514 TheCache.eraseBlock(BB);
515 }
516
517 /// This is the update interface to inform the cache that an edge from
518 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
519 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
520
522 Function *GuardDecl)
523 : PerPredRanges(getAnalysisOptions(*F).lvi_per_pred_ranges),
524 TheCache(F, PerPredRanges), AC(AC), DL(DL), GuardDecl(GuardDecl) {}
525};
526} // namespace llvm
527
528void LazyValueInfoImpl::solve() {
530 BlockValueStack;
531
532 unsigned processedCount = 0;
533 while (!BlockValueStack.empty()) {
534 processedCount++;
535 // Abort if we have to process too many values to get a result for this one.
536 // Because of the design of the overdefined cache currently being per-block
537 // to avoid naming-related issues (IE it wants to try to give different
538 // results for the same name in different blocks), overdefined results don't
539 // get cached globally, which in turn means we will often try to rediscover
540 // the same overdefined result again and again. Once something like
541 // PredicateInfo is used in LVI or CVP, we should be able to make the
542 // overdefined cache global, and remove this throttle.
543 if (processedCount > MaxProcessedPerValue) {
545 dbgs() << "Giving up on stack because we are getting too deep\n");
546 // Fill in the original values
547 while (!StartingStack.empty()) {
548 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
549 TheCache.insertResult(e.second, e.first,
551 StartingStack.pop_back();
552 }
553 BlockValueSet.clear();
554 BlockValueStack.clear();
555 return;
556 }
557 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
558 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
559 unsigned StackSize = BlockValueStack.size();
560 (void) StackSize;
561
562 if (solveBlockValue(e.second, e.first)) {
563 // The work item was completely processed.
564 assert(BlockValueStack.size() == StackSize &&
565 BlockValueStack.back() == e && "Nothing should have been pushed!");
566#ifndef NDEBUG
567 std::optional<ValueLatticeElement> BBLV =
568 TheCache.getCachedValueInfo(e.second, e.first);
569 assert(BBLV && "Result should be in cache!");
571 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
572 << *BBLV << "\n");
573#endif
574
575 BlockValueStack.pop_back();
576 BlockValueSet.erase(e);
577 } else {
578 // More work needs to be done before revisiting.
579 assert(BlockValueStack.size() == StackSize + 1 &&
580 "Exactly one element should have been pushed!");
581 }
582 }
583}
584
585std::optional<ValueLatticeElement>
586LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB,
587 Instruction *CtxI) {
588 // If already a constant, there is nothing to compute.
589 if (Constant *VC = dyn_cast<Constant>(Val))
590 return ValueLatticeElement::get(VC);
591
592 if (std::optional<ValueLatticeElement> OptLatticeVal =
593 TheCache.getCachedValueInfo(Val, BB)) {
594 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CtxI);
595 return OptLatticeVal;
596 }
597
598 // We have hit a cycle, assume overdefined.
599 if (!pushBlockValue({ BB, Val }))
601
602 // Yet to be resolved.
603 return std::nullopt;
604}
605
607 switch (BBI->getOpcode()) {
608 default:
609 break;
610 case Instruction::Call:
611 case Instruction::Invoke:
612 if (std::optional<ConstantRange> Range = cast<CallBase>(BBI)->getRange())
614 [[fallthrough]];
615 case Instruction::Load:
616 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
617 if (isa<IntegerType>(BBI->getType())) {
620 }
621 break;
622 };
623 // Nothing known - will be intersected with other facts
625}
626
627bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
628 assert(!isa<Constant>(Val) && "Value should not be constant");
629 assert(!TheCache.getCachedValueInfo(Val, BB) &&
630 "Value should not be in cache");
631
632 // Hold off inserting this value into the Cache in case we have to return
633 // false and come back later.
634 std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
635 if (!Res)
636 // Work pushed, will revisit
637 return false;
638
639 TheCache.insertResult(Val, BB, *Res);
640 return true;
641}
642
643std::optional<ValueLatticeElement>
644LazyValueInfoImpl::solveBlockValueImpl(Value *Val, BasicBlock *BB) {
646 if (!BBI || BBI->getParent() != BB)
647 return solveBlockValueNonLocal(Val, BB);
648
649 if (PHINode *PN = dyn_cast<PHINode>(BBI))
650 return solveBlockValuePHINode(PN, BB);
651
652 if (auto *SI = dyn_cast<SelectInst>(BBI))
653 return solveBlockValueSelect(SI, BB);
654
655 // If this value is a nonnull pointer, record it's range and bailout. Note
656 // that for all other pointer typed values, we terminate the search at the
657 // definition. We could easily extend this to look through geps, bitcasts,
658 // and the like to prove non-nullness, but it's not clear that's worth it
659 // compile time wise. The context-insensitive value walk done inside
660 // isKnownNonZero gets most of the profitable cases at much less expense.
661 // This does mean that we have a sensitivity to where the defining
662 // instruction is placed, even if it could legally be hoisted much higher.
663 // That is unfortunate.
665 if (PT && isKnownNonZero(BBI, DL))
667
668 if (BBI->getType()->isIntOrIntVectorTy()) {
669 if (auto *CI = dyn_cast<CastInst>(BBI))
670 return solveBlockValueCast(CI, BB);
671
672 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
673 return solveBlockValueBinaryOp(BO, BB);
674
675 if (auto *IEI = dyn_cast<InsertElementInst>(BBI))
676 return solveBlockValueInsertElement(IEI, BB);
677
678 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
679 return solveBlockValueExtractValue(EVI, BB);
680
681 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
682 return solveBlockValueIntrinsic(II, BB);
683 }
684
685 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
686 << "' - unknown inst def found.\n");
687 return getFromRangeMetadata(BBI);
688}
689
690static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet,
691 bool IsDereferenced = true) {
692 // TODO: Use NullPointerIsDefined instead.
693 if (Ptr->getType()->getPointerAddressSpace() == 0)
694 PtrSet.insert(IsDereferenced ? getUnderlyingObject(Ptr)
695 : Ptr->stripInBoundsOffsets());
696}
697
699 Instruction *I, NonNullPointerSet &PtrSet) {
700 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
701 AddNonNullPointer(L->getPointerOperand(), PtrSet);
702 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
703 AddNonNullPointer(S->getPointerOperand(), PtrSet);
704 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
705 if (MI->isVolatile()) return;
706
707 // FIXME: check whether it has a valuerange that excludes zero?
708 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
709 if (!Len || Len->isZero()) return;
710
711 AddNonNullPointer(MI->getRawDest(), PtrSet);
713 AddNonNullPointer(MTI->getRawSource(), PtrSet);
714 } else if (auto *CB = dyn_cast<CallBase>(I)) {
715 for (auto &U : CB->args()) {
716 if (U->getType()->isPointerTy() &&
717 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
718 /*AllowUndefOrPoison=*/false))
719 AddNonNullPointer(U.get(), PtrSet, /*IsDereferenced=*/false);
720 }
721 }
722}
723
724bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
727 return false;
728
729 Val = Val->stripInBoundsOffsets();
730 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
731 NonNullPointerSet NonNullPointers;
732 for (Instruction &I : *BB)
733 AddNonNullPointersByInstruction(&I, NonNullPointers);
734 return NonNullPointers;
735 });
736}
737
738std::optional<ValueLatticeElement>
739LazyValueInfoImpl::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
740 ValueLatticeElement Result; // Start Undefined.
741
742 // If this is the entry block, we must be asking about an argument.
743 if (BB->isEntryBlock()) {
744 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
745 if (std::optional<ConstantRange> Range = cast<Argument>(Val)->getRange())
748 }
749
750 // Loop over all of our predecessors, merging what we know from them into
751 // result. If we encounter an unexplored predecessor, we eagerly explore it
752 // in a depth first manner. In practice, this has the effect of discovering
753 // paths we can't analyze eagerly without spending compile times analyzing
754 // other paths. This heuristic benefits from the fact that predecessors are
755 // frequently arranged such that dominating ones come first and we quickly
756 // find a path to function entry. TODO: We should consider explicitly
757 // canonicalizing to make this true rather than relying on this happy
758 // accident.
759 std::optional<BBLatticeElementMap> PredLatticeElements;
760 if (PerPredRanges)
761 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
762 for (BasicBlock *Pred : predecessors(BB)) {
763 // Skip self loops.
764 if (Pred == BB)
765 continue;
766 std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
767 if (!EdgeResult)
768 // Explore that input, then return here
769 return std::nullopt;
770
771 Result.mergeIn(*EdgeResult);
772
773 // If we hit overdefined, exit early. The BlockVals entry is already set
774 // to overdefined.
775 if (Result.isOverdefined()) {
776 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
777 << "' - overdefined because of pred '"
778 << Pred->getName() << "' (non local).\n");
779 return Result;
780 }
781 if (PerPredRanges)
782 PredLatticeElements->insert({Pred, *EdgeResult});
783 }
784
785 if (PerPredRanges)
786 TheCache.insertPredecessorResults(Val, BB, *PredLatticeElements);
787
788 // Return the merged value, which is more precise than 'overdefined'.
789 assert(!Result.isOverdefined());
790 return Result;
791}
792
793std::optional<ValueLatticeElement>
794LazyValueInfoImpl::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
795 ValueLatticeElement Result; // Start Undefined.
796
797 // Loop over all of our predecessors, merging what we know from them into
798 // result. See the comment about the chosen traversal order in
799 // solveBlockValueNonLocal; the same reasoning applies here.
800 std::optional<BBLatticeElementMap> PredLatticeElements;
801 if (PerPredRanges)
802 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
803 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
804 BasicBlock *PhiBB = PN->getIncomingBlock(i);
805 Value *PhiVal = PN->getIncomingValue(i);
806 // Note that we can provide PN as the context value to getEdgeValue, even
807 // though the results will be cached, because PN is the value being used as
808 // the cache key in the caller.
809 std::optional<ValueLatticeElement> EdgeResult =
810 getEdgeValue(PhiVal, PhiBB, BB, PN);
811 if (!EdgeResult)
812 // Explore that input, then return here
813 return std::nullopt;
814
815 Result.mergeIn(*EdgeResult);
816
817 // If we hit overdefined, exit early. The BlockVals entry is already set
818 // to overdefined.
819 if (Result.isOverdefined()) {
820 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
821 << "' - overdefined because of pred (local).\n");
822
823 return Result;
824 }
825
826 if (PerPredRanges)
827 PredLatticeElements->insert({PhiBB, *EdgeResult});
828 }
829
830 if (PerPredRanges)
831 TheCache.insertPredecessorResults(PN, BB, *PredLatticeElements);
832
833 // Return the merged value, which is more precise than 'overdefined'.
834 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
835 return Result;
836}
837
838// If we can determine a constraint on the value given conditions assumed by
839// the program, intersect those constraints with BBLV
840void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
841 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
842 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
843 if (!BBI)
844 return;
845
846 BasicBlock *BB = BBI->getParent();
847 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
848 if (!AssumeVH)
849 continue;
850
851 // Only check assumes in the block of the context instruction. Other
852 // assumes will have already been taken into account when the value was
853 // propagated from predecessor blocks.
854 auto *I = cast<AssumeInst>(AssumeVH);
855
856 if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
857 continue;
858
859 if (AssumeVH.Index != AssumptionCache::ExprResultIdx) {
860 auto OBU = I->getOperandBundleAt(AssumeVH.Index);
861 switch (getBundleAttrFromOBU(OBU)) {
862 case BundleAttr::Range: {
863 auto [V, Range] = getAssumeRangeInfo(OBU);
864 if (Val == V) {
865 BBLV =
867 }
868 } break;
869 default:
871 I->getOperandBundleAt(AssumeVH.Index)))
874 }
875 } else {
876 BBLV = BBLV.intersect(*getValueFromCondition(Val, I->getArgOperand(0),
877 /*IsTrueDest*/ true,
878 /*UseBlockValue*/ false));
879 }
880 }
881
882 // If guards are not used in the module, don't spend time looking for them
883 if (GuardDecl && !GuardDecl->use_empty() &&
884 BBI->getIterator() != BB->begin()) {
885 for (Instruction &I :
886 make_range(std::next(BBI->getIterator().getReverse()), BB->rend())) {
887 Value *Cond = nullptr;
889 BBLV = BBLV.intersect(*getValueFromCondition(Val, Cond,
890 /*IsTrueDest*/ true,
891 /*UseBlockValue*/ false));
892 }
893 }
894
895 if (BBLV.isOverdefined()) {
896 // Check whether we're checking at the terminator, and the pointer has
897 // been dereferenced in this block.
899 if (PTy && BB->getTerminator() == BBI &&
900 isNonNullAtEndOfBlock(Val, BB))
902 }
903}
904
905std::optional<ValueLatticeElement>
906LazyValueInfoImpl::solveBlockValueSelect(SelectInst *SI, BasicBlock *BB) {
907 // Recurse on our inputs if needed
908 std::optional<ValueLatticeElement> OptTrueVal =
909 getBlockValue(SI->getTrueValue(), BB, SI);
910 if (!OptTrueVal)
911 return std::nullopt;
912 ValueLatticeElement &TrueVal = *OptTrueVal;
913
914 std::optional<ValueLatticeElement> OptFalseVal =
915 getBlockValue(SI->getFalseValue(), BB, SI);
916 if (!OptFalseVal)
917 return std::nullopt;
918 ValueLatticeElement &FalseVal = *OptFalseVal;
919
920 if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
921 const ConstantRange &TrueCR = TrueVal.asConstantRange(SI->getType());
922 const ConstantRange &FalseCR = FalseVal.asConstantRange(SI->getType());
923 Value *LHS = nullptr;
924 Value *RHS = nullptr;
925 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
926 // Is this a min specifically of our two inputs? (Avoid the risk of
927 // ValueTracking getting smarter looking back past our immediate inputs.)
929 ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
930 (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
931 ConstantRange ResultCR = [&]() {
932 switch (SPR.Flavor) {
933 default:
934 llvm_unreachable("unexpected minmax type!");
935 case SPF_SMIN: /// Signed minimum
936 return TrueCR.smin(FalseCR);
937 case SPF_UMIN: /// Unsigned minimum
938 return TrueCR.umin(FalseCR);
939 case SPF_SMAX: /// Signed maximum
940 return TrueCR.smax(FalseCR);
941 case SPF_UMAX: /// Unsigned maximum
942 return TrueCR.umax(FalseCR);
943 };
944 }();
946 ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
947 FalseVal.isConstantRangeIncludingUndef());
948 }
949
950 if (SPR.Flavor == SPF_ABS) {
951 if (LHS == SI->getTrueValue())
953 TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
954 if (LHS == SI->getFalseValue())
956 FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
957 }
958
959 if (SPR.Flavor == SPF_NABS) {
960 ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
961 if (LHS == SI->getTrueValue())
963 Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
964 if (LHS == SI->getFalseValue())
966 Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
967 }
968 }
969
970 // Can we constrain the facts about the true and false values by using the
971 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
972 // TODO: We could potentially refine an overdefined true value above.
973 Value *Cond = SI->getCondition();
974 // If the value is undef, a different value may be chosen in
975 // the select condition.
977 TrueVal =
978 TrueVal.intersect(*getValueFromCondition(SI->getTrueValue(), Cond,
979 /*IsTrueDest*/ true,
980 /*UseBlockValue*/ false));
981 FalseVal =
982 FalseVal.intersect(*getValueFromCondition(SI->getFalseValue(), Cond,
983 /*IsTrueDest*/ false,
984 /*UseBlockValue*/ false));
985 }
986
987 TrueVal.mergeIn(FalseVal);
988 return TrueVal;
989}
990
991std::optional<ConstantRange>
992LazyValueInfoImpl::getRangeFor(Value *V, Instruction *CtxI, BasicBlock *BB) {
993 std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CtxI);
994 if (!OptVal)
995 return std::nullopt;
996 return OptVal->asConstantRange(V->getType());
997}
998
999std::optional<ValueLatticeElement>
1000LazyValueInfoImpl::solveBlockValueCast(CastInst *CI, BasicBlock *BB) {
1001 // Filter out casts we don't know how to reason about before attempting to
1002 // recurse on our operand. This can cut a long search short if we know we're
1003 // not going to be able to get any useful information anways.
1004 switch (CI->getOpcode()) {
1005 case Instruction::Trunc:
1006 case Instruction::SExt:
1007 case Instruction::ZExt:
1008 break;
1009 default:
1010 // Unhandled instructions are overdefined.
1011 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1012 << "' - overdefined (unknown cast).\n");
1014 }
1015
1016 // Figure out the range of the LHS. If that fails, we still apply the
1017 // transfer rule on the full set since we may be able to locally infer
1018 // interesting facts.
1019 std::optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
1020 if (!LHSRes)
1021 // More work to do before applying this transfer rule.
1022 return std::nullopt;
1023 const ConstantRange &LHSRange = *LHSRes;
1024
1025 const unsigned ResultBitWidth = CI->getType()->getScalarSizeInBits();
1026
1027 // NOTE: We're currently limited by the set of operations that ConstantRange
1028 // can evaluate symbolically. Enhancing that set will allows us to analyze
1029 // more definitions.
1030 ConstantRange Res = ConstantRange::getEmpty(ResultBitWidth);
1031 if (auto *Trunc = dyn_cast<TruncInst>(CI))
1032 Res = LHSRange.truncate(ResultBitWidth, Trunc->getNoWrapKind());
1033 else
1034 Res = LHSRange.castOp(CI->getOpcode(), ResultBitWidth);
1035
1037}
1038
1039std::optional<ValueLatticeElement>
1040LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
1041 Instruction *I, BasicBlock *BB,
1042 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
1043 OpFn) {
1044 Value *LHS = I->getOperand(0);
1045 Value *RHS = I->getOperand(1);
1046
1047 auto ThreadBinOpOverSelect =
1048 [&](Value *X, const ConstantRange &CRX, SelectInst *Y,
1049 bool XIsLHS) -> std::optional<ValueLatticeElement> {
1050 Value *Cond = Y->getCondition();
1051 // Only handle selects with constant values.
1052 Constant *TrueC = dyn_cast<Constant>(Y->getTrueValue());
1053 if (!TrueC)
1054 return std::nullopt;
1055 Constant *FalseC = dyn_cast<Constant>(Y->getFalseValue());
1056 if (!FalseC)
1057 return std::nullopt;
1059 return std::nullopt;
1060
1061 ConstantRange TrueX =
1062 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/true,
1063 /*UseBlockValue=*/false)
1064 ->asConstantRange(X->getType()));
1065 ConstantRange FalseX =
1066 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/false,
1067 /*UseBlockValue=*/false)
1068 ->asConstantRange(X->getType()));
1069 ConstantRange TrueY = TrueC->toConstantRange();
1070 ConstantRange FalseY = FalseC->toConstantRange();
1071
1072 if (XIsLHS)
1074 OpFn(TrueX, TrueY).unionWith(OpFn(FalseX, FalseY)));
1076 OpFn(TrueY, TrueX).unionWith(OpFn(FalseY, FalseX)));
1077 };
1078
1079 // Figure out the ranges of the operands. If that fails, use a
1080 // conservative range, but apply the transfer rule anyways. This
1081 // lets us pick up facts from expressions like "and i32 (call i32
1082 // @foo()), 32"
1083 std::optional<ConstantRange> LHSRes = getRangeFor(LHS, I, BB);
1084 if (!LHSRes)
1085 return std::nullopt;
1086
1087 // Try to thread binop over rhs select
1088 if (auto *SI = dyn_cast<SelectInst>(RHS)) {
1089 if (auto Res = ThreadBinOpOverSelect(LHS, *LHSRes, SI, /*XIsLHS=*/true))
1090 return *Res;
1091 }
1092
1093 std::optional<ConstantRange> RHSRes = getRangeFor(RHS, I, BB);
1094 if (!RHSRes)
1095 return std::nullopt;
1096
1097 // Try to thread binop over lhs select
1098 if (auto *SI = dyn_cast<SelectInst>(LHS)) {
1099 if (auto Res = ThreadBinOpOverSelect(RHS, *RHSRes, SI, /*XIsLHS=*/false))
1100 return *Res;
1101 }
1102
1103 const ConstantRange &LHSRange = *LHSRes;
1104 const ConstantRange &RHSRange = *RHSRes;
1105
1106 std::optional<ValueLatticeElement> MergedResult =
1107 ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
1108
1109 if (!PerPredRanges)
1110 return MergedResult;
1111
1112 std::optional<BBLatticeElementMap> PredLHS =
1113 TheCache.getCachedPredecessorInfo(LHS, BB);
1114 if (!PredLHS)
1115 return MergedResult;
1116 std::optional<BBLatticeElementMap> PredRHS =
1117 TheCache.getCachedPredecessorInfo(RHS, BB);
1118 if (!PredRHS)
1119 return MergedResult;
1120
1121 const BBLatticeElementMap &LHSPredMap = *PredLHS;
1122 const BBLatticeElementMap &RHSPredMap = *PredRHS;
1123
1124 BBLatticeElementMap PredLatticeElements;
1125 ValueLatticeElement OverallPredResult;
1126 for (auto *Pred : predecessors(BB)) {
1127 auto LHSIt = LHSPredMap.find_as(Pred);
1128 if (LHSIt == LHSPredMap.end())
1129 return MergedResult;
1130 const ValueLatticeElement &LHSFromPred = LHSIt->second;
1131 std::optional<ConstantRange> LHSFromPredRes =
1132 LHSFromPred.asConstantRange(LHS->getType());
1133 if (!LHSFromPredRes)
1134 return MergedResult;
1135
1136 auto RHSIt = RHSPredMap.find_as(Pred);
1137 if (RHSIt == RHSPredMap.end())
1138 return MergedResult;
1139 const ValueLatticeElement &RHSFromPred = RHSIt->second;
1140 std::optional<ConstantRange> RHSFromPredRes =
1141 RHSFromPred.asConstantRange(RHS->getType());
1142 if (!RHSFromPredRes)
1143 return MergedResult;
1144
1145 const ConstantRange &LHSFromPredRange = *LHSFromPredRes;
1146 const ConstantRange &RHSFromPredRange = *RHSFromPredRes;
1147 std::optional<ValueLatticeElement> PredResult =
1148 ValueLatticeElement::getRange(OpFn(LHSFromPredRange, RHSFromPredRange));
1149 if (!PredResult)
1150 return MergedResult;
1151 if (PredResult->isOverdefined()) {
1152 LLVM_DEBUG(
1153 dbgs() << " pred BB '" << Pred->getName() << "' for BB '"
1154 << BB->getName()
1155 << "' overdefined. Discarding all predecessor intervals.\n");
1156 return MergedResult;
1157 }
1158 PredLatticeElements.insert({Pred, *PredResult});
1159 OverallPredResult.mergeIn(*PredResult);
1160 }
1161
1162 // If this point is reached, all predecessors for both LHS and RHS have
1163 // constant ranges previously computed. Can cache result and use the
1164 // OverallPredResult;
1165 TheCache.insertPredecessorResults(I, BB, PredLatticeElements);
1166
1167 LLVM_DEBUG(dbgs() << " Using predecessor intervals, evaluated " << *I
1168 << " to: " << OverallPredResult << ".\n");
1169
1170 if (!MergedResult)
1171 return OverallPredResult;
1172
1173 LLVM_DEBUG(dbgs() << " Intersecting intervals for " << *I << ": "
1174 << OverallPredResult << " and " << MergedResult << ".\n");
1175 return MergedResult->intersect(OverallPredResult);
1176}
1177
1178std::optional<ValueLatticeElement>
1179LazyValueInfoImpl::solveBlockValueBinaryOp(BinaryOperator *BO, BasicBlock *BB) {
1180 assert(BO->getOperand(0)->getType()->isSized() &&
1181 "all operands to binary operators are sized");
1182
1183 return solveBlockValueBinaryOpImpl(
1184 BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1185 return CR1.binaryOp(*BO, CR2);
1186 });
1187}
1188
1189std::optional<ValueLatticeElement>
1190LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
1191 BasicBlock *BB) {
1192 return solveBlockValueBinaryOpImpl(
1193 WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1194 return CR1.binaryOp(WO->getBinaryOp(), CR2);
1195 });
1196}
1197
1198std::optional<ValueLatticeElement>
1199LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
1200 ValueLatticeElement MetadataVal = getFromRangeMetadata(II);
1201 if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1202 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1203 << "' - unknown intrinsic.\n");
1204 return MetadataVal;
1205 }
1206
1208 for (Value *Op : II->args()) {
1209 std::optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1210 if (!Range)
1211 return std::nullopt;
1212 OpRanges.push_back(*Range);
1213 }
1214
1216 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges))
1217 .intersect(MetadataVal);
1218}
1219
1220std::optional<ValueLatticeElement>
1221LazyValueInfoImpl::solveBlockValueInsertElement(InsertElementInst *IEI,
1222 BasicBlock *BB) {
1223 std::optional<ValueLatticeElement> OptEltVal =
1224 getBlockValue(IEI->getOperand(1), BB, IEI);
1225 if (!OptEltVal)
1226 return std::nullopt;
1227 ValueLatticeElement &Res = *OptEltVal;
1228
1229 std::optional<ValueLatticeElement> OptVecVal =
1230 getBlockValue(IEI->getOperand(0), BB, IEI);
1231 if (!OptVecVal)
1232 return std::nullopt;
1233
1234 // Bail out if the inserted element is a constant expression. Unlike other
1235 // ValueLattice types, these are not considered an implicit splat when a
1236 // vector type is used.
1237 // We could call ConstantFoldInsertElementInstruction here to handle these.
1238 if (OptEltVal->isConstant())
1240
1241 Res.mergeIn(*OptVecVal);
1242 return Res;
1243}
1244
1245std::optional<ValueLatticeElement>
1246LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
1247 BasicBlock *BB) {
1248 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1249 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1250 return solveBlockValueOverflowIntrinsic(WO, BB);
1251
1252 // Handle extractvalue of insertvalue to allow further simplification
1253 // based on replaced with.overflow intrinsics.
1255 EVI->getAggregateOperand(), EVI->getIndices(),
1256 EVI->getDataLayout()))
1257 return getBlockValue(V, BB, EVI);
1258
1259 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1260 << "' - overdefined (unknown extractvalue).\n");
1262}
1263
1266 if (LHS == Val)
1267 return true;
1268
1269 // Handle range checking idiom produced by InstCombine. We will subtract the
1270 // offset from the allowed range for RHS in this case.
1271 const APInt *C;
1272 if (match(LHS, m_AddLike(m_Specific(Val), m_APInt(C)))) {
1273 Offset = *C;
1274 return true;
1275 }
1276
1277 // Handle the symmetric case. This appears in saturation patterns like
1278 // (x == 16) ? 16 : (x + 1).
1279 if (match(Val, m_AddLike(m_Specific(LHS), m_APInt(C)))) {
1280 Offset = -*C;
1281 return true;
1282 }
1283
1284 // If (x | y) < C, then (x < C) && (y < C).
1285 if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1287 return true;
1288
1289 // If (x & y) > C, then (x > C) && (y > C).
1290 if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1292 return true;
1293
1294 return false;
1295}
1296
1297/// Get value range for a "(Val + Offset) Pred RHS" condition.
1298std::optional<ValueLatticeElement>
1299LazyValueInfoImpl::getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,
1300 Value *RHS,
1301 const APInt &Offset,
1302 Instruction *CtxI,
1303 bool UseBlockValue) {
1304 ConstantRange RHSRange(RHS->getType()->getScalarSizeInBits(),
1305 /*isFullSet=*/true);
1306 if (auto *C = dyn_cast<Constant>(RHS)) {
1307 RHSRange = C->toConstantRange();
1308 } else if (UseBlockValue) {
1309 std::optional<ValueLatticeElement> R =
1310 getBlockValue(RHS, CtxI->getParent(), CtxI);
1311 if (!R)
1312 return std::nullopt;
1313 RHSRange = R->asConstantRange(RHS->getType());
1314 }
1315
1316 ConstantRange TrueValues =
1318 return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1319}
1320
1321static std::optional<ConstantRange>
1323 function_ref<std::optional<ConstantRange>(const APInt &)> Fn) {
1324 bool Invert = false;
1327 Invert = true;
1328 }
1329 if (Pred == ICmpInst::ICMP_SLE) {
1331 if (RHS.isMaxSignedValue())
1332 return std::nullopt; // Could also return full/empty here, if we wanted.
1333 ++RHS;
1334 }
1335 assert(Pred == ICmpInst::ICMP_SLT && "Must be signed predicate");
1336 if (auto CR = Fn(RHS))
1337 return Invert ? CR->inverse() : CR;
1338 return std::nullopt;
1339}
1340
1341/// Get value range for a "ctpop(Val) Pred RHS" condition.
1343 Value *RHS) {
1344 unsigned BitWidth = RHS->getType()->getScalarSizeInBits();
1345
1346 auto *RHSConst = dyn_cast<ConstantInt>(RHS);
1347 if (!RHSConst)
1349
1350 ConstantRange ResValRange =
1351 ConstantRange::makeExactICmpRegion(Pred, RHSConst->getValue());
1352
1353 unsigned ResMin = ResValRange.getUnsignedMin().getLimitedValue(BitWidth);
1354 unsigned ResMax = ResValRange.getUnsignedMax().getLimitedValue(BitWidth);
1355
1356 APInt ValMin = APInt::getLowBitsSet(BitWidth, ResMin);
1357 APInt ValMax = APInt::getHighBitsSet(BitWidth, ResMax);
1359 ConstantRange::getNonEmpty(std::move(ValMin), ValMax + 1));
1360}
1361
1362/// Get the unsigned range for \p V from a `mul nuw V, V` comparison.
1363static std::optional<ConstantRange>
1365 const Value *LHS, const Value *RHS) {
1366 if (!V->getType()->isIntegerTy())
1367 return std::nullopt;
1368
1369 if (!match(LHS, m_NUWMul(m_Specific(V), m_Specific(V)))) {
1371 return std::nullopt;
1372
1374 RHS = LHS;
1375 }
1376
1377 ConstantRange MulCR =
1378 ConstantRange::getFull(V->getType()->getScalarSizeInBits());
1379 const APInt *C;
1380 if (match(RHS, m_APInt(C)))
1382
1383 ConstantRange Res = MulCR.sqrtFloor();
1384 if (Res.isFullSet())
1385 return std::nullopt;
1386 return Res;
1387}
1388
1389std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1390 Value *Val, ICmpInst *ICI, bool isTrueDest, bool UseBlockValue) {
1391 Value *LHS = ICI->getOperand(0);
1392 Value *RHS = ICI->getOperand(1);
1393
1394 // Get the predicate that must hold along the considered edge.
1395 CmpInst::Predicate EdgePred =
1396 isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1397
1398 if (isa<Constant>(RHS)) {
1399 if (ICI->isEquality() && LHS == Val) {
1400 if (EdgePred == ICmpInst::ICMP_EQ)
1402 else if (!isa<UndefValue>(RHS))
1404 }
1405 }
1406
1407 Type *Ty = Val->getType();
1408 if (!Ty->isIntOrIntVectorTy())
1410
1411 unsigned BitWidth = Ty->getScalarSizeInBits();
1412 if (auto Range = getRangeForNUWMulSquare(Val, EdgePred, LHS, RHS))
1414
1415 APInt Offset(BitWidth, 0);
1416 if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1417 return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset, ICI,
1418 UseBlockValue);
1419
1420 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1421 if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1422 return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset, ICI,
1423 UseBlockValue);
1424
1425 if (match(LHS, m_Ctpop(m_Specific(Val))))
1426 return getValueFromICmpCtpop(EdgePred, RHS);
1427
1428 const APInt *Mask, *C;
1429 if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1430 match(RHS, m_APInt(C))) {
1431 // If (Val & Mask) == C then all the masked bits are known and we can
1432 // compute a value range based on that.
1433 if (EdgePred == ICmpInst::ICMP_EQ) {
1434 KnownBits Known;
1435 Known.Zero = ~*C & *Mask;
1436 Known.One = *C & *Mask;
1438 ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1439 }
1440
1441 if (EdgePred == ICmpInst::ICMP_NE)
1444 }
1445
1446 // If (X urem Modulus) >= C, then X >= C.
1447 // If trunc X >= C, then X >= C.
1448 // TODO: An upper bound could be computed as well.
1450 m_Trunc(m_Specific(Val)))) &&
1451 match(RHS, m_APInt(C))) {
1452 // Use the icmp region so we don't have to deal with different predicates.
1453 ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
1454 if (!CR.isEmptySet())
1456 CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
1457 }
1458
1459 // Recognize:
1460 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, C << ShAmtC
1461 // Preconditions: (C << ShAmtC) >> ShAmtC == C
1462 const APInt *ShAmtC;
1463 if (CmpInst::isSigned(EdgePred) &&
1464 match(LHS, m_AShr(m_Specific(Val), m_APInt(ShAmtC))) &&
1465 match(RHS, m_APInt(C))) {
1466 auto CR = getRangeViaSLT(
1467 EdgePred, *C, [&](const APInt &RHS) -> std::optional<ConstantRange> {
1468 APInt New = RHS << *ShAmtC;
1469 if ((New.ashr(*ShAmtC)) != RHS)
1470 return std::nullopt;
1472 APInt::getSignedMinValue(New.getBitWidth()), New);
1473 });
1474 if (CR)
1476 }
1477
1478 // a - b or ptrtoint(a) - ptrtoint(b) ==/!= 0 if a ==/!= b
1479 Value *X, *Y;
1480 if (ICI->isEquality() && match(Val, m_Sub(m_Value(X), m_Value(Y)))) {
1481 // Peek through ptrtoints
1484 if ((X == LHS && Y == RHS) || (X == RHS && Y == LHS)) {
1485 Constant *NullVal = Constant::getNullValue(Val->getType());
1486 if (EdgePred == ICmpInst::ICMP_EQ)
1487 return ValueLatticeElement::get(NullVal);
1488 return ValueLatticeElement::getNot(NullVal);
1489 }
1490 }
1491
1493}
1494
1495ValueLatticeElement LazyValueInfoImpl::getValueFromTrunc(Value *Val,
1496 TruncInst *Trunc,
1497 bool IsTrueDest) {
1498 assert(Trunc->getType()->isIntOrIntVectorTy(1));
1499
1500 if (Trunc->getOperand(0) != Val)
1502
1503 Type *Ty = Val->getType();
1504
1505 if (Trunc->hasNoUnsignedWrap()) {
1506 if (IsTrueDest)
1507 return ValueLatticeElement::get(ConstantInt::get(Ty, 1));
1509 }
1510
1511 if (IsTrueDest)
1514}
1515
1516// Handle conditions of the form
1517// extractvalue(op.with.overflow(%x, C), 1).
1519 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1520 // TODO: This only works with a constant RHS for now. We could also compute
1521 // the range of the RHS, but this doesn't fit into the current structure of
1522 // the edge value calculation.
1523 const APInt *C;
1524 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1526
1527 // Calculate the possible values of %x for which no overflow occurs.
1529 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1530
1531 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1532 // constrained to it's inverse (all values that might cause overflow).
1533 if (IsTrueDest)
1534 NWR = NWR.inverse();
1536}
1537
1538std::optional<ValueLatticeElement>
1539LazyValueInfoImpl::getValueFromCondition(Value *Val, Value *Cond,
1540 bool IsTrueDest, bool UseBlockValue,
1541 unsigned Depth) {
1542 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1543 return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
1544
1545 if (auto *Trunc = dyn_cast<TruncInst>(Cond))
1546 return getValueFromTrunc(Val, Trunc, IsTrueDest);
1547
1548 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1549 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1550 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1551 return getValueFromOverflowCondition(Val, WO, IsTrueDest);
1552
1555
1556 Value *N;
1557 if (match(Cond, m_Not(m_Value(N))))
1558 return getValueFromCondition(Val, N, !IsTrueDest, UseBlockValue, Depth);
1559
1560 Value *L, *R;
1561 bool IsAnd;
1562 if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1563 IsAnd = true;
1564 else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1565 IsAnd = false;
1566 else
1568
1569 std::optional<ValueLatticeElement> LV =
1570 getValueFromCondition(Val, L, IsTrueDest, UseBlockValue, Depth);
1571 if (!LV)
1572 return std::nullopt;
1573 std::optional<ValueLatticeElement> RV =
1574 getValueFromCondition(Val, R, IsTrueDest, UseBlockValue, Depth);
1575 if (!RV)
1576 return std::nullopt;
1577
1578 // if (L && R) -> intersect L and R
1579 // if (!(L || R)) -> intersect !L and !R
1580 // if (L || R) -> union L and R
1581 // if (!(L && R)) -> union !L and !R
1582 if (IsTrueDest ^ IsAnd) {
1583 LV->mergeIn(*RV);
1584 return *LV;
1585 }
1586
1587 return LV->intersect(*RV);
1588}
1589
1590// Return true if Usr has Op as an operand, otherwise false.
1591static bool usesOperand(User *Usr, Value *Op) {
1592 return is_contained(Usr->operands(), Op);
1593}
1594
1595// Return true if the instruction type of Val is supported by
1596// constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1597// Call this before calling constantFoldUser() to find out if it's even worth
1598// attempting to call it.
1599static bool isOperationFoldable(User *Usr) {
1600 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1601}
1602
1603// Check if Usr can be simplified to an integer constant when the value of one
1604// of its operands Op is an integer constant OpConstVal. If so, return it as an
1605// lattice value range with a single element or otherwise return an overdefined
1606// lattice value.
1608 const APInt &OpConstVal,
1609 const DataLayout &DL) {
1610 assert(isOperationFoldable(Usr) && "Precondition");
1611 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1612 // Check if Usr can be simplified to a constant.
1613 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1614 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1615 if (auto *C = dyn_cast_or_null<ConstantInt>(
1616 simplifyCastInst(CI->getOpcode(), OpConst,
1617 CI->getDestTy(), DL))) {
1618 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1619 }
1620 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1621 bool Op0Match = BO->getOperand(0) == Op;
1622 bool Op1Match = BO->getOperand(1) == Op;
1623 assert((Op0Match || Op1Match) &&
1624 "Operand 0 nor Operand 1 isn't a match");
1625 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1626 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1627 if (auto *C = dyn_cast_or_null<ConstantInt>(
1628 simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1629 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1630 }
1631 } else if (isa<FreezeInst>(Usr)) {
1632 assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1633 return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1634 }
1636}
1637
1638/// Compute the value of Val on the edge BBFrom -> BBTo.
1639std::optional<ValueLatticeElement>
1640LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1641 BasicBlock *BBTo, bool UseBlockValue) {
1642 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1643 // know that v != 0.
1644 if (CondBrInst *BI = dyn_cast<CondBrInst>(BBFrom->getTerminator())) {
1645 // If this is a conditional branch and only one successor goes to BBTo, then
1646 // we may be able to infer something from the condition.
1647 if (BI->getSuccessor(0) != BI->getSuccessor(1)) {
1648 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1649 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1650 "BBTo isn't a successor of BBFrom");
1651 Value *Condition = BI->getCondition();
1652
1653 // If V is the condition of the branch itself, then we know exactly what
1654 // it is.
1655 // NB: The condition on a `br` can't be a vector type.
1656 if (Condition == Val)
1657 return ValueLatticeElement::get(ConstantInt::get(
1658 Type::getInt1Ty(Val->getContext()), isTrueDest));
1659
1660 // If the condition of the branch is an equality comparison, we may be
1661 // able to infer the value.
1662 std::optional<ValueLatticeElement> Result =
1663 getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1664 if (!Result)
1665 return std::nullopt;
1666
1667 if (!Result->isOverdefined())
1668 return Result;
1669
1670 if (User *Usr = dyn_cast<User>(Val)) {
1671 assert(Result->isOverdefined() && "Result isn't overdefined");
1672 // Check with isOperationFoldable() first to avoid linearly iterating
1673 // over the operands unnecessarily which can be expensive for
1674 // instructions with many operands.
1675 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1676 const DataLayout &DL = BBTo->getDataLayout();
1677 Value *TempCond = Condition;
1678 if (usesOperand(Usr, Condition) ||
1679 (match(Condition, m_Not(m_Value(TempCond))) &&
1680 usesOperand(Usr, TempCond))) {
1681 // If Val has Condition as an operand and Val can be folded into a
1682 // constant with either Condition == true or Condition == false,
1683 // propagate the constant.
1684 // eg.
1685 // ; %Val is true on the edge to %then.
1686 // %Val = and i1 %Condition, true.
1687 // br %Condition, label %then, label %else
1688 APInt ConditionVal(1, isTrueDest ^ (TempCond != Condition) ? 1 : 0);
1689 Result = constantFoldUser(Usr, TempCond, ConditionVal, DL);
1690 } else if (isa<TruncInst, ZExtInst, SExtInst>(Usr)) {
1691 ValueLatticeElement OpLatticeVal =
1692 *getValueFromCondition(Usr->getOperand(0), Condition,
1693 isTrueDest, /*UseBlockValue*/ false);
1694
1695 if (OpLatticeVal.isConstantRange()) {
1696 const unsigned ResultBitWidth =
1697 Usr->getType()->getScalarSizeInBits();
1698 if (auto *Trunc = dyn_cast<TruncInst>(Usr))
1700 OpLatticeVal.getConstantRange().truncate(
1701 ResultBitWidth, Trunc->getNoWrapKind()));
1702
1704 OpLatticeVal.getConstantRange().castOp(
1705 cast<CastInst>(Usr)->getOpcode(), ResultBitWidth));
1706 }
1707 if (OpLatticeVal.isConstant()) {
1708 Constant *C = OpLatticeVal.getConstant();
1709 if (auto *CastC = ConstantFoldCastOperand(
1710 cast<CastInst>(Usr)->getOpcode(), C, Usr->getType(), DL))
1711 return ValueLatticeElement::get(CastC);
1712 }
1714 } else {
1715 // If one of Val's operand has an inferred value, we may be able to
1716 // infer the value of Val.
1717 // eg.
1718 // ; %Val is 94 on the edge to %then.
1719 // %Val = add i8 %Op, 1
1720 // %Condition = icmp eq i8 %Op, 93
1721 // br i1 %Condition, label %then, label %else
1722 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1723 Value *Op = Usr->getOperand(i);
1724 ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1725 Op, Condition, isTrueDest, /*UseBlockValue*/ false);
1726 if (std::optional<APInt> OpConst =
1727 OpLatticeVal.asConstantInteger()) {
1728 Result = constantFoldUser(Usr, Op, *OpConst, DL);
1729 break;
1730 }
1731 }
1732 }
1733 }
1734 }
1735 if (!Result->isOverdefined())
1736 return Result;
1737 }
1738 }
1739
1740 // If the edge was formed by a switch on the value, then we may know exactly
1741 // what it is.
1742 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1743 Value *Condition = SI->getCondition();
1744 if (!isa<IntegerType>(Val->getType()))
1746 bool ValUsesConditionAndMayBeFoldable = false;
1747 if (Condition != Val) {
1748 // Check if Val has Condition as an operand.
1749 if (User *Usr = dyn_cast<User>(Val))
1750 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1751 usesOperand(Usr, Condition);
1752 if (!ValUsesConditionAndMayBeFoldable)
1754 }
1755 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1756 "Condition != Val nor Val doesn't use Condition");
1757
1758 bool DefaultCase = SI->getDefaultDest() == BBTo;
1759 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1760 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1761
1762 for (auto Case : SI->cases()) {
1763 APInt CaseValue = Case.getCaseValue()->getValue();
1764 ConstantRange EdgeVal(CaseValue);
1765 if (ValUsesConditionAndMayBeFoldable) {
1766 User *Usr = cast<User>(Val);
1767 const DataLayout &DL = BBTo->getDataLayout();
1768 ValueLatticeElement EdgeLatticeVal =
1769 constantFoldUser(Usr, Condition, CaseValue, DL);
1770 if (EdgeLatticeVal.isOverdefined())
1772 EdgeVal = EdgeLatticeVal.getConstantRange();
1773 }
1774 if (DefaultCase) {
1775 // It is possible that the default destination is the destination of
1776 // some cases. We cannot perform difference for those cases.
1777 // We know Condition != CaseValue in BBTo. In some cases we can use
1778 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1779 // only do this when f is identity (i.e. Val == Condition), but we
1780 // should be able to do this for any injective f.
1781 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1782 EdgesVals = EdgesVals.difference(EdgeVal);
1783 } else if (Case.getCaseSuccessor() == BBTo)
1784 EdgesVals = EdgesVals.unionWith(EdgeVal);
1785 }
1786 return ValueLatticeElement::getRange(std::move(EdgesVals));
1787 }
1789}
1790
1791/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1792/// the basic block if the edge does not constrain Val.
1793std::optional<ValueLatticeElement>
1794LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1795 BasicBlock *BBTo, Instruction *CtxI) {
1796 // If already a constant, there is nothing to compute.
1797 if (Constant *VC = dyn_cast<Constant>(Val))
1798 return ValueLatticeElement::get(VC);
1799
1800 std::optional<ValueLatticeElement> LocalResult =
1801 getEdgeValueLocal(Val, BBFrom, BBTo, /*UseBlockValue*/ true);
1802 if (!LocalResult)
1803 return std::nullopt;
1804
1805 if (hasSingleValue(*LocalResult))
1806 // Can't get any more precise here
1807 return LocalResult;
1808
1809 std::optional<ValueLatticeElement> OptInBlock =
1810 getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1811 if (!OptInBlock)
1812 return std::nullopt;
1813 ValueLatticeElement &InBlock = *OptInBlock;
1814
1815 // We can use the context instruction (generically the ultimate instruction
1816 // the calling pass is trying to simplify) here, even though the result of
1817 // this function is generally cached when called from the solve* functions
1818 // (and that cached result might be used with queries using a different
1819 // context instruction), because when this function is called from the solve*
1820 // functions, the context instruction is not provided. When called from
1821 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1822 // but then the result is not cached.
1823 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CtxI);
1824
1825 return LocalResult->intersect(InBlock);
1826}
1827
1829 Instruction *CtxI) {
1830 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1831 << BB->getName() << "'\n");
1832
1833 assert(BlockValueStack.empty() && BlockValueSet.empty());
1834 std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CtxI);
1835 if (!OptResult) {
1836 solve();
1837 OptResult = getBlockValue(V, BB, CtxI);
1838 assert(OptResult && "Value not available after solving");
1839 }
1840
1841 LLVM_DEBUG(dbgs() << " Result = " << *OptResult << "\n");
1842 return *OptResult;
1843}
1844
1846 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CtxI->getName()
1847 << "'\n");
1848
1849 if (auto *C = dyn_cast<Constant>(V))
1851
1853 if (auto *I = dyn_cast<Instruction>(V))
1854 Result = getFromRangeMetadata(I);
1855 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CtxI);
1856
1857 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
1858 return Result;
1859}
1860
1862getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1863 Instruction *CtxI) {
1864 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1865 << FromBB->getName() << "' to '" << ToBB->getName()
1866 << "'\n");
1867
1868 std::optional<ValueLatticeElement> Result =
1869 getEdgeValue(V, FromBB, ToBB, CtxI);
1870 while (!Result) {
1871 // As the worklist only explicitly tracks block values (but not edge values)
1872 // we may have to call solve() multiple times, as the edge value calculation
1873 // may request additional block values.
1874 solve();
1875 Result = getEdgeValue(V, FromBB, ToBB, CtxI);
1876 }
1877
1878 LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n");
1879 return *Result;
1880}
1881
1883 Value *V = U.get();
1884 auto *CtxI = cast<Instruction>(U.getUser());
1885 ValueLatticeElement VL = getValueInBlock(V, CtxI->getParent(), CtxI);
1886 BasicBlock *LastQueriedBB = CtxI->getParent();
1887
1888 // Check whether the only (possibly transitive) use of the value is in a
1889 // position where V can be constrained by a select or branch condition.
1890 const Use *CurrU = &U;
1891 // TODO: Increase limit?
1892 const unsigned MaxUsesToInspect = 3;
1893 for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
1894 std::optional<ValueLatticeElement> CondVal;
1895 auto *CurrI = cast<Instruction>(CurrU->getUser());
1896
1897 // All instructions on the one-use chain between the original use and CurrI
1898 // are speculatable and have a single user each, so they could be sunk to
1899 // CurrI. This means information that holds at CurrI also holds for the
1900 // original use and can be used to refine it. Skip phis, as V may not
1901 // dominate their block.
1902 if (I != 0 && !isa<PHINode>(CurrI) && CurrI->getParent() != LastQueriedBB) {
1903 LastQueriedBB = CurrI->getParent();
1904 VL = VL.intersect(getValueInBlock(V, LastQueriedBB, CurrI));
1905 }
1906
1907 if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
1908 // If the value is undef, a different value may be chosen in
1909 // the select condition and at use.
1910 if (!isGuaranteedNotToBeUndef(SI->getCondition(), AC))
1911 break;
1912 if (CurrU->getOperandNo() == 1)
1913 CondVal =
1914 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ true,
1915 /*UseBlockValue*/ false);
1916 else if (CurrU->getOperandNo() == 2)
1917 CondVal =
1918 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ false,
1919 /*UseBlockValue*/ false);
1920 } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
1921 // TODO: Use non-local query?
1922 CondVal = *getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU),
1923 PHI->getParent(), /*UseBlockValue*/ false);
1924 }
1925 if (CondVal)
1926 VL = VL.intersect(*CondVal);
1927
1928 // Only follow one-use chain, to allow direct intersection of conditions.
1929 // If there are multiple uses, we would have to intersect with the union of
1930 // all conditions at different uses.
1931 // Stop walking if we hit a non-speculatable instruction. Even if the
1932 // result is only used under a specific condition, executing the
1933 // instruction itself may cause side effects or UB already.
1934 // This also disallows looking through phi nodes: If the phi node is part
1935 // of a cycle, we might end up reasoning about values from different cycle
1936 // iterations (PR60629).
1937 if (!CurrI->hasOneUse() ||
1939 CurrI, /*IgnoreUBImplyingAttrs=*/false))
1940 break;
1941 // Also stop walking at cross-lane operations, since they may rearrange
1942 // lanes so that a later select per-lane condition might no longer
1943 // correspond to the original value's lanes.
1944 if (V->getType()->isVectorTy() && !isNotCrossLaneOperation(CurrI))
1945 break;
1946 CurrU = &*CurrI->use_begin();
1947 }
1948 return VL;
1949}
1950
1952 BasicBlock *NewSucc) {
1953 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1954}
1955
1956//===----------------------------------------------------------------------===//
1957// LazyValueInfo Impl
1958//===----------------------------------------------------------------------===//
1959
1961 Info.F = &F;
1962 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1963
1964 if (auto *Impl = Info.getImpl())
1965 Impl->clear();
1966
1967 // Fully lazy.
1968 return false;
1969}
1970
1976
1978
1979/// This lazily constructs the LazyValueInfoImpl.
1980LazyValueInfoImpl &LazyValueInfo::getOrCreateImpl() {
1981 if (!PImpl) {
1982 const DataLayout &DL = F->getDataLayout();
1984 F->getParent(), Intrinsic::experimental_guard);
1985 PImpl = new LazyValueInfoImpl(F, AC, DL, GuardDecl);
1986 }
1987 return *PImpl;
1988}
1989
1990LazyValueInfoImpl *LazyValueInfo::getImpl() { return PImpl; }
1991
1993
1995 // If the cache was allocated, free it.
1996 if (auto *Impl = getImpl()) {
1997 delete &*Impl;
1998 PImpl = nullptr;
1999 }
2000}
2001
2003 FunctionAnalysisManager::Invalidator &Inv) {
2004 // We need to invalidate if we have either failed to preserve this analyses
2005 // result directly or if any of its dependencies have been invalidated.
2006 auto PAC = PA.getChecker<LazyValueAnalysis>();
2007 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
2008 return true;
2009
2010 return false;
2011}
2012
2013void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
2014
2017 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
2018
2019 return LazyValueInfo(&F, &AC);
2020}
2021
2022/// Returns true if we can statically tell that this value will never be a
2023/// "useful" constant. In practice, this means we've got something like an
2024/// alloca or a malloc call for which a comparison against a constant can
2025/// only be guarding dead code. Note that we are potentially giving up some
2026/// precision in dead code (a constant result) in favour of avoiding a
2027/// expensive search for a easily answered common query.
2029 V = V->stripPointerCasts();
2030 // The return val of alloc cannot be a Constant.
2031 if (isa<AllocaInst>(V))
2032 return true;
2033 return false;
2034}
2035
2037 // Bail out early if V is known not to be a Constant.
2038 if (isKnownNonConstant(V))
2039 return nullptr;
2040
2041 BasicBlock *BB = CtxI->getParent();
2042 ValueLatticeElement Result = getOrCreateImpl().getValueInBlock(V, BB, CtxI);
2043
2044 if (Result.isConstant())
2045 return Result.getConstant();
2046 if (Result.isConstantRange()) {
2047 const ConstantRange &CR = Result.getConstantRange();
2048 if (const APInt *SingleVal = CR.getSingleElement())
2049 return ConstantInt::get(V->getType(), *SingleVal);
2050 }
2051 return nullptr;
2052}
2053
2055 bool UndefAllowed) {
2056 BasicBlock *BB = CtxI->getParent();
2057 ValueLatticeElement Result = getOrCreateImpl().getValueInBlock(V, BB, CtxI);
2058 return Result.asConstantRange(V->getType(), UndefAllowed);
2059}
2060
2062 bool UndefAllowed) {
2063 ValueLatticeElement Result = getOrCreateImpl().getValueAtUse(U);
2064 return Result.asConstantRange(U->getType(), UndefAllowed);
2065}
2066
2067/// Determine whether the specified value is known to be a
2068/// constant on the specified edge. Return null if not.
2070 BasicBlock *ToBB,
2071 Instruction *CtxI) {
2072 ValueLatticeElement Result =
2073 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CtxI);
2074
2075 if (Result.isConstant())
2076 return Result.getConstant();
2077 if (Result.isConstantRange()) {
2078 const ConstantRange &CR = Result.getConstantRange();
2079 if (const APInt *SingleVal = CR.getSingleElement())
2080 return ConstantInt::get(V->getType(), *SingleVal);
2081 }
2082 return nullptr;
2083}
2084
2086 BasicBlock *FromBB,
2087 BasicBlock *ToBB,
2088 Instruction *CtxI) {
2089 ValueLatticeElement Result =
2090 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CtxI);
2091 // TODO: Should undef be allowed here?
2092 return Result.asConstantRange(V->getType(), /*UndefAllowed*/ true);
2093}
2094
2096 const ValueLatticeElement &Val,
2097 const DataLayout &DL) {
2098 // If we know the value is a constant, evaluate the conditional.
2099 if (Val.isConstant())
2101
2102 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
2103 if (Val.isConstantRange()) {
2104 const ConstantRange &CR = Val.getConstantRange();
2105 ConstantRange RHS = C->toConstantRange();
2106 if (CR.icmp(Pred, RHS))
2107 return ConstantInt::getTrue(ResTy);
2109 return ConstantInt::getFalse(ResTy);
2110 return nullptr;
2111 }
2112
2113 if (Val.isNotConstant()) {
2114 // If this is an equality comparison, we can try to fold it knowing that
2115 // "V != C1".
2116 if (Pred == ICmpInst::ICMP_EQ) {
2117 // !C1 == C -> false iff C1 == C.
2120 if (Res && Res->isNullValue())
2121 return ConstantInt::getFalse(ResTy);
2122 } else if (Pred == ICmpInst::ICMP_NE) {
2123 // !C1 != C -> true iff C1 == C.
2126 if (Res && Res->isNullValue())
2127 return ConstantInt::getTrue(ResTy);
2128 }
2129 return nullptr;
2130 }
2131
2132 return nullptr;
2133}
2134
2135/// Determine whether the specified value comparison with a constant is known to
2136/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
2138 Constant *C, BasicBlock *FromBB,
2139 BasicBlock *ToBB,
2140 Instruction *CtxI) {
2141 ValueLatticeElement Result =
2142 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CtxI);
2143
2144 return getPredicateResult(Pred, C, Result, FromBB->getDataLayout());
2145}
2146
2148 Constant *C, Instruction *CtxI,
2149 bool UseBlockValue) {
2150 // Is or is not NonNull are common predicates being queried. If
2151 // isKnownNonZero can tell us the result of the predicate, we can
2152 // return it quickly. But this is only a fastpath, and falling
2153 // through would still be correct.
2154 const DataLayout &DL = CtxI->getDataLayout();
2155 // NOTE: This check is meant to determine whether a pointer is semantically a
2156 // null pointer, not just whether its value equals ConstantPointerNull. If the
2157 // semantics of ConstantPointerNull change in the future, this should be
2158 // updated to use a semantic check (e.g. isKnownNonNull).
2159 if (V->getType()->isPointerTy() && C->isNullValue() &&
2160 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
2161 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
2162 if (Pred == ICmpInst::ICMP_EQ)
2163 return ConstantInt::getFalse(ResTy);
2164 else if (Pred == ICmpInst::ICMP_NE)
2165 return ConstantInt::getTrue(ResTy);
2166 }
2167
2168 auto &Impl = getOrCreateImpl();
2169 ValueLatticeElement Result =
2170 UseBlockValue ? Impl.getValueInBlock(V, CtxI->getParent(), CtxI)
2171 : Impl.getValueAt(V, CtxI);
2172 Constant *Ret = getPredicateResult(Pred, C, Result, DL);
2173 if (Ret)
2174 return Ret;
2175
2176 // Note: The following bit of code is somewhat distinct from the rest of LVI;
2177 // LVI as a whole tries to compute a lattice value which is conservatively
2178 // correct at a given location. In this case, we have a predicate which we
2179 // weren't able to prove about the merged result, and we're pushing that
2180 // predicate back along each incoming edge to see if we can prove it
2181 // separately for each input. As a motivating example, consider:
2182 // bb1:
2183 // %v1 = ... ; constantrange<1, 5>
2184 // br label %merge
2185 // bb2:
2186 // %v2 = ... ; constantrange<10, 20>
2187 // br label %merge
2188 // merge:
2189 // %phi = phi [%v1, %v2] ; constantrange<1,20>
2190 // %pred = icmp eq i32 %phi, 8
2191 // We can't tell from the lattice value for '%phi' that '%pred' is false
2192 // along each path, but by checking the predicate over each input separately,
2193 // we can.
2194 // We limit the search to one step backwards from the current BB and value.
2195 // We could consider extending this to search further backwards through the
2196 // CFG and/or value graph, but there are non-obvious compile time vs quality
2197 // tradeoffs.
2198 BasicBlock *BB = CtxI->getParent();
2199
2200 // Function entry or an unreachable block. Bail to avoid confusing
2201 // analysis below.
2202 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2203 if (PI == PE)
2204 return nullptr;
2205
2206 // If V is a PHI node in the same block as the context, we need to ask
2207 // questions about the predicate as applied to the incoming value along
2208 // each edge. This is useful for eliminating cases where the predicate is
2209 // known along all incoming edges.
2210 if (auto *PHI = dyn_cast<PHINode>(V))
2211 if (PHI->getParent() == BB) {
2212 Constant *Baseline = nullptr;
2213 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
2214 Value *Incoming = PHI->getIncomingValue(i);
2215 BasicBlock *PredBB = PHI->getIncomingBlock(i);
2216 // Note that PredBB may be BB itself.
2217 Constant *Result =
2218 getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CtxI);
2219
2220 // Keep going as long as we've seen a consistent known result for
2221 // all inputs.
2222 Baseline = (i == 0) ? Result /* First iteration */
2223 : (Baseline == Result ? Baseline
2224 : nullptr); /* All others */
2225 if (!Baseline)
2226 break;
2227 }
2228 if (Baseline)
2229 return Baseline;
2230 }
2231
2232 // For a comparison where the V is outside this block, it's possible
2233 // that we've branched on it before. Look to see if the value is known
2234 // on all incoming edges.
2235 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
2236 // For predecessor edge, determine if the comparison is true or false
2237 // on that edge. If they're all true or all false, we can conclude
2238 // the value of the comparison in this block.
2239 Constant *Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CtxI);
2240 if (Baseline) {
2241 // Check that all remaining incoming values match the first one.
2242 while (++PI != PE) {
2243 Constant *Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CtxI);
2244 if (Ret != Baseline)
2245 break;
2246 }
2247 // If we terminated early, then one of the values didn't match.
2248 if (PI == PE) {
2249 return Baseline;
2250 }
2251 }
2252 }
2253
2254 return nullptr;
2255}
2256
2258 Value *RHS, Instruction *CtxI,
2259 bool UseBlockValue) {
2260 if (auto *C = dyn_cast<Constant>(RHS))
2261 return getPredicateAt(Pred, LHS, C, CtxI, UseBlockValue);
2262 if (auto *C = dyn_cast<Constant>(LHS))
2263 return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CtxI,
2264 UseBlockValue);
2265
2266 // Got two non-Constant values. Try to determine the comparison results based
2267 // on the block values of the two operands, e.g. because they have
2268 // non-overlapping ranges.
2269 if (UseBlockValue) {
2271 getOrCreateImpl().getValueInBlock(LHS, CtxI->getParent(), CtxI);
2272 if (L.isOverdefined())
2273 return nullptr;
2274
2276 getOrCreateImpl().getValueInBlock(RHS, CtxI->getParent(), CtxI);
2277 Type *Ty = CmpInst::makeCmpResultType(LHS->getType());
2278 return L.getCompare(Pred, Ty, R, CtxI->getDataLayout());
2279 }
2280 return nullptr;
2281}
2282
2284 BasicBlock *NewSucc) {
2285 if (auto *Impl = getImpl())
2286 Impl->threadEdge(PredBB, OldSucc, NewSucc);
2287}
2288
2290 if (auto *Impl = getImpl())
2291 Impl->forgetValue(V);
2292}
2293
2295 if (auto *Impl = getImpl())
2296 Impl->eraseBlock(BB);
2297}
2298
2300 if (auto *Impl = getImpl())
2301 Impl->clear();
2302}
2303
2305 if (auto *Impl = getImpl())
2306 Impl->printLVI(F, DTree, OS);
2307}
2308
2309// Print the LVI for the function arguments at the start of each basic block.
2310void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2311 const BasicBlock *BB, formatted_raw_ostream &OS) {
2312 // Find if there are latticevalues defined for arguments of the function.
2313 auto *F = BB->getParent();
2314 for (const auto &Arg : F->args()) {
2315 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2316 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2317 if (Result.isUnknown())
2318 continue;
2319 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
2320 }
2321}
2322
2323// This function prints the LVI analysis for the instruction I at the beginning
2324// of various basic blocks. It relies on calculated values that are stored in
2325// the LazyValueInfoCache, and in the absence of cached values, recalculate the
2326// LazyValueInfo for `I`, and print that info.
2327void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2328 const Instruction *I, formatted_raw_ostream &OS) {
2329
2330 auto *ParentBB = I->getParent();
2331 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2332 // We can generate (solve) LVI values only for blocks that are dominated by
2333 // the I's parent. However, to avoid generating LVI for all dominating blocks,
2334 // that contain redundant/uninteresting information, we print LVI for
2335 // blocks that may use this LVI information (such as immediate successor
2336 // blocks, and blocks that contain uses of `I`).
2337 auto printResult = [&](const BasicBlock *BB) {
2338 if (!BlocksContainingLVI.insert(BB).second)
2339 return;
2340 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2341 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2342 OS << "; LatticeVal for: '" << *I << "' in BB: '";
2343 BB->printAsOperand(OS, false);
2344 OS << "' is: " << Result << "\n";
2345 };
2346
2347 printResult(ParentBB);
2348 // Print the LVI analysis results for the immediate successor blocks, that
2349 // are dominated by `ParentBB`.
2350 for (const auto *BBSucc : successors(ParentBB))
2351 if (DT.dominates(ParentBB, BBSucc))
2352 printResult(BBSucc);
2353
2354 // Print LVI in blocks where `I` is used.
2355 for (const auto *U : I->users())
2356 if (auto *UseI = dyn_cast<Instruction>(U))
2357 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2358 printResult(UseI->getParent());
2359
2360}
2361
2364 OS << "LVI for function '" << F.getName() << "':\n";
2365 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
2366 auto &DTree = AM.getResult<DominatorTreeAnalysis>(F);
2367 LVI.printLVI(F, DTree, OS);
2368 return PreservedAnalyses::all();
2369}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static bool isOperationFoldable(User *Usr)
static std::optional< ConstantRange > getRangeForNUWMulSquare(const Value *V, CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Get the unsigned range for V from a mul nuw V, V comparison.
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)
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)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static void eraseBlock(MachineBasicBlock *MBB, LiveIntervals &LIS, MachineDomTreeUpdater &MDTU)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SmallVector< MachineOperand, 4 > Cond
This file contains some templates that are useful if you are working with the STL at all.
static bool InBlock(const Value *V, const BasicBlock *BB)
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
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:471
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
reverse_iterator rend()
Definition BasicBlock.h:458
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Value handle with callbacks on RAUW and destruction.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
Type * getDestTy() const
Return the destination type, as a convenience.
Definition InstrTypes.h:681
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI ConstantRange sqrtFloor() const
Calculate sqrtFloor range. See APInt::sqrtFloor().
LLVM_ABI ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
LLVM_ABI ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
static LLVM_ABI ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
static LLVM_ABI bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static LLVM_ABI ConstantRange makeMaskNotEqualRange(const APInt &Mask, const APInt &C)
Initialize a range containing all values X that satisfy (X & Mask) / != C.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
LLVM_ABI ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
LLVM_ABI ConstantRange toConstantRange() const
Convert constant to an approximate constant range.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
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:312
FunctionPass(char &pid)
Definition Pass.h:314
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:813
unsigned getBlockNumberEpoch() const
Return the "epoch" of current block numbers.
Definition Function.h:827
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
This instruction inserts a single (scalar) element into a VectorType value.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
Analysis to compute lazy value information.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &FAM)
LazyValueInfoImpl(Function *F, AssumptionCache *AC, const DataLayout &DL, Function *GuardDecl)
ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=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 *CtxI)
This is the query interface to determine the lattice value for the specified Value* at the specified ...
ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB, Instruction *CtxI=nullptr)
This is the query interface to determine the lattice value for the specified Value* at the context in...
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.
ValueLatticeElement getValueAtUse(const Use &U)
LLVM_ABI 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.
LLVM_ABI void eraseBlock(BasicBlock *BB)
Inform the analysis cache that we have erased a block.
LLVM_ABI ConstantRange getConstantRangeAtUse(const Use &U, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the value at a specific use-site.
LLVM_ABI Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
LLVM_ABI 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...
LLVM_ABI void releaseMemory()
LLVM_ABI Constant * getConstant(Value *V, Instruction *CtxI)
Determine whether the specified value is known to be a constant at the specified instruction.
LLVM_ABI void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Print the \LazyValueInfo Analysis.
LLVM_ABI Constant * getPredicateAt(CmpInst::Predicate Pred, Value *V, Constant *C, Instruction *CtxI, bool UseBlockValue)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
LLVM_ABI void forgetValue(Value *V)
Remove information related to this value from the cache.
LLVM_ABI ConstantRange getConstantRange(Value *V, Instruction *CtxI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
LLVM_ABI void clear()
Complete flush all previously computed values.
LLVM_ABI ConstantRange getConstantRangeOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr)
Return the ConstantRage constraint that is known to hold for the specified value on the specified edg...
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
LLVM_ABI Constant * getPredicateOnEdge(CmpInst::Predicate Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1081
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memcpy/memmove intrinsics.
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.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class represents a truncation of integer types.
unsigned getNoWrapKind() const
Returns the no-wrap kind of the operation.
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:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
This class represents lattice values for constants.
static ValueLatticeElement getRange(ConstantRange CR, bool MayIncludeUndef=false)
static ValueLatticeElement getNot(Constant *C)
ConstantRange asConstantRange(unsigned BW, bool UndefAllowed=false) const
std::optional< APInt > asConstantInteger() const
const ConstantRange & getConstantRange(bool UndefAllowed=true) const
Returns the constant range for this value.
bool isConstantRange(bool UndefAllowed=true) const
Returns true if this value is a constant range.
static ValueLatticeElement get(Constant *C)
Constant * getNotConstant() const
LLVM_ABI ValueLatticeElement intersect(const ValueLatticeElement &Other) const
Combine two sets of facts about the same value into a single set of facts.
Constant * getConstant() const
bool mergeIn(const ValueLatticeElement &RHS, MergeOptions Opts=MergeOptions())
Updates this object to approximate both this object and RHS.
static ValueLatticeElement getOverdefined()
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:824
use_iterator use_begin()
Definition Value.h:366
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool erase(const ValueT &V)
Definition DenseSet.h:97
iterator find_as(const LookupKeyT &Val)
Alternative version of find() which allows a different, and possibly less expensive,...
Definition DenseSet.h:197
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
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)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
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)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
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".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
constexpr double e
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
@ Known
Known to have no common set bits.
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
static ConstantRange getRange(Value *Op, SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues)
Helper for getting ranges from Solver.
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:2224
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
LLVM_ABI FunctionPass * createLazyValueInfoPass()
createLazyValueInfoPass - This creates an instance of the LazyValueInfo pass.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr unsigned MaxAnalysisRecursionDepth
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
static bool hasSingleValue(const ValueLatticeElement &Val)
constexpr unsigned BitWidth
auto pred_begin(const MachineBasicBlock *BB)
LLVM_ABI AssumeRangeInfo getAssumeRangeInfo(OperandBundleUse)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?