LLVM 23.0.0git
LazyValueInfo.cpp
Go to the documentation of this file.
1//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interface for lazy computation of value constraint
10// information.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/STLExtras.h"
26#include "llvm/IR/CFG.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
38#include "llvm/IR/ValueHandle.h"
40#include "llvm/Support/Debug.h"
44#include <optional>
45using namespace llvm;
46using namespace PatternMatch;
47
48#define DEBUG_TYPE "lazy-value-info"
49
50// This is the number of worklist items we will process to try to discover an
51// answer for a given value.
52static const unsigned MaxProcessedPerValue = 500;
53
57 "Lazy Value Information Analysis", false, true)
61 "Lazy Value Information Analysis", false, true)
62
63static cl::opt<bool> PerPredRanges(
64 "lvi-per-pred-ranges", cl::Hidden, cl::init(false),
65 cl::desc("Enable tracking of ranges for a value in a block for"
66 "each block predecessor (default = false)"));
67
68namespace llvm {
72} // namespace llvm
73
74AnalysisKey LazyValueAnalysis::Key;
75
76/// Returns true if this lattice value represents at most one possible value.
77/// This is as precise as any lattice value can get while still representing
78/// reachable code.
79static bool hasSingleValue(const ValueLatticeElement &Val) {
80 if (Val.isConstantRange() &&
82 // Integer constants are single element ranges
83 return true;
84 if (Val.isConstant())
85 // Non integer constants
86 return true;
87 return false;
88}
89
90//===----------------------------------------------------------------------===//
91// LazyValueInfoCache Decl
92//===----------------------------------------------------------------------===//
93
94namespace {
95 /// A callback value handle updates the cache when values are erased.
96 class LazyValueInfoCache;
97 struct LVIValueHandle final : public CallbackVH {
98 LazyValueInfoCache *Parent;
99
100 LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
101 : CallbackVH(V), Parent(P) { }
102
103 void deleted() override;
104 void allUsesReplacedWith(Value *V) override {
105 deleted();
106 }
107 };
108} // end anonymous namespace
109
110namespace {
111using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
112using BBLatticeElementMap =
114using PredecessorValueLatticeMap =
115 SmallDenseMap<AssertingVH<Value>, BBLatticeElementMap, 2>;
116
117/// This is the cache kept by LazyValueInfo which
118/// maintains information about queries across the clients' queries.
119class LazyValueInfoCache {
120 /// This is all of the cached information for one basic block. It contains
121 /// the per-value lattice elements, as well as a separate set for
122 /// overdefined values to reduce memory usage. Additionally pointers
123 /// dereferenced in the block are cached for nullability queries.
124 struct BlockCacheEntry {
125 SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
126 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
127 // std::nullopt indicates that the nonnull pointers for this basic block
128 // block have not been computed yet.
129 std::optional<NonNullPointerSet> NonNullPointers;
130 // This is an extension of the above LatticeElements, caching, for each
131 // Value, a ValueLatticeElement, for each predecessor of the BB tracked by
132 // this entry.
133 std::optional<PredecessorValueLatticeMap> PredecessorLatticeElements;
134 };
135
136 /// Cached information per basic block, indexed by block number.
138 /// Set of value handles used to erase values from the cache on deletion.
139 DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
140 /// Block number epoch on construction.
141 unsigned BlockNumberEpoch;
142
143 const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
144 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
145 if (BB->getNumber() < BlockCache.size())
146 return BlockCache[BB->getNumber()].get();
147 return nullptr;
148 }
149
150 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
151 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
152 unsigned Number = BB->getNumber();
153 if (Number >= BlockCache.size())
154 BlockCache.resize(BB->getParent()->getMaxBlockNumber());
155
156 if (BlockCacheEntry *Entry = BlockCache[Number].get())
157 return Entry;
158
159 BlockCache[Number] = std::make_unique<BlockCacheEntry>();
160 if (PerPredRanges)
161 BlockCache[Number]->PredecessorLatticeElements =
162 std::make_optional<PredecessorValueLatticeMap>();
163
164 return BlockCache[Number].get();
165 }
166
167 void addValueHandle(Value *Val) {
168 auto HandleIt = ValueHandles.find_as(Val);
169 if (HandleIt == ValueHandles.end())
170 ValueHandles.insert({Val, this});
171 }
172
173public:
174 LazyValueInfoCache(const Function *F)
175 : BlockNumberEpoch(F->getBlockNumberEpoch()) {}
176
177 void insertResult(Value *Val, BasicBlock *BB,
178 const ValueLatticeElement &Result) {
179 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
180
181 // Insert over-defined values into their own cache to reduce memory
182 // overhead.
183 if (Result.isOverdefined())
184 Entry->OverDefined.insert(Val);
185 else
186 Entry->LatticeElements.insert({Val, Result});
187
188 addValueHandle(Val);
189 }
190
191 void insertPredecessorResults(Value *Val, BasicBlock *BB,
192 BBLatticeElementMap &PredLatticeElements) {
193 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
194
195 Entry->PredecessorLatticeElements->insert({Val, PredLatticeElements});
196
197 addValueHandle(Val);
198 }
199
200 std::optional<BBLatticeElementMap>
201 getCachedPredecessorInfo(Value *V, BasicBlock *BB) const {
202 const BlockCacheEntry *Entry = getBlockEntry(BB);
203 if (!Entry)
204 return std::nullopt;
205
206 auto LatticeIt = Entry->PredecessorLatticeElements->find_as(V);
207 if (LatticeIt == Entry->PredecessorLatticeElements->end())
208 return std::nullopt;
209
210 return LatticeIt->second;
211 }
212
213 std::optional<ValueLatticeElement> getCachedValueInfo(Value *V,
214 BasicBlock *BB) const {
215 const BlockCacheEntry *Entry = getBlockEntry(BB);
216 if (!Entry)
217 return std::nullopt;
218
219 if (Entry->OverDefined.count(V))
221
222 auto LatticeIt = Entry->LatticeElements.find_as(V);
223 if (LatticeIt == Entry->LatticeElements.end())
224 return std::nullopt;
225
226 return LatticeIt->second;
227 }
228
229 bool
230 isNonNullAtEndOfBlock(Value *V, BasicBlock *BB,
231 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
232 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
233 if (!Entry->NonNullPointers) {
234 Entry->NonNullPointers = InitFn(BB);
235 for (Value *V : *Entry->NonNullPointers)
236 addValueHandle(V);
237 }
238
239 return Entry->NonNullPointers->count(V);
240 }
241
242 /// clear - Empty the cache.
243 void clear() {
244 BlockCache.clear();
245 ValueHandles.clear();
246 }
247
248 /// Inform the cache that a given value has been deleted.
249 void eraseValue(Value *V);
250
251 /// This is part of the update interface to inform the cache
252 /// that a block has been deleted.
253 void eraseBlock(BasicBlock *BB);
254
255 /// Updates the cache to remove any influence an overdefined value in
256 /// OldSucc might have (unless also overdefined in NewSucc). This just
257 /// flushes elements from the cache and does not add any.
258 void threadEdgeImpl(BasicBlock *OldSucc, BasicBlock *NewSucc);
259};
260} // namespace
261
262void LazyValueInfoCache::eraseValue(Value *V) {
263 for (auto &Elem : BlockCache) {
264 if (!Elem)
265 continue;
266
267 Elem->LatticeElements.erase(V);
268 Elem->OverDefined.erase(V);
269 if (Elem->NonNullPointers)
270 Elem->NonNullPointers->erase(V);
271 if (PerPredRanges)
272 Elem->PredecessorLatticeElements->erase(V);
273 }
274
275 auto HandleIt = ValueHandles.find_as(V);
276 if (HandleIt != ValueHandles.end())
277 ValueHandles.erase(HandleIt);
278}
279
280void LVIValueHandle::deleted() {
281 // This erasure deallocates *this, so it MUST happen after we're done
282 // using any and all members of *this.
283 Parent->eraseValue(*this);
284}
285
286void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
287 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
288 // Clear all when a BB is removed.
289 if (PerPredRanges)
290 for (auto &Elem : BlockCache)
291 if (Elem)
292 Elem->PredecessorLatticeElements->clear();
293 if (BB->getNumber() < BlockCache.size())
294 BlockCache[BB->getNumber()].reset();
295}
296
297void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
298 BasicBlock *NewSucc) {
299 // When an edge in the graph has been threaded, values that we could not
300 // determine a value for before (i.e. were marked overdefined) may be
301 // possible to solve now. We do NOT try to proactively update these values.
302 // Instead, we clear their entries from the cache, and allow lazy updating to
303 // recompute them when needed.
304
305 // The updating process is fairly simple: we need to drop cached info
306 // for all values that were marked overdefined in OldSucc, and for those same
307 // values in any successor of OldSucc (except NewSucc) in which they were
308 // also marked overdefined.
309 std::vector<BasicBlock*> worklist;
310 worklist.push_back(OldSucc);
311
312 const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
313 if (!Entry || Entry->OverDefined.empty())
314 return; // Nothing to process here.
315 SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
316 Entry->OverDefined.end());
317
318 // Use a worklist to perform a depth-first search of OldSucc's successors.
319 // NOTE: We do not need a visited list since any blocks we have already
320 // visited will have had their overdefined markers cleared already, and we
321 // thus won't loop to their successors.
322 while (!worklist.empty()) {
323 BasicBlock *ToUpdate = worklist.back();
324 worklist.pop_back();
325
326 // Skip blocks only accessible through NewSucc.
327 if (ToUpdate == NewSucc) continue;
328
329 // If a value was marked overdefined in OldSucc, and is here too...
330 BlockCacheEntry *WorklistEntry =
331 ToUpdate->getNumber() < BlockCache.size()
332 ? BlockCache[ToUpdate->getNumber()].get()
333 : nullptr;
334 if (!WorklistEntry || WorklistEntry->OverDefined.empty())
335 continue;
336 auto &ValueSet = WorklistEntry->OverDefined;
337
338 bool changed = false;
339 for (Value *V : ValsToClear) {
340 if (!ValueSet.erase(V))
341 continue;
342
343 // If we removed anything, then we potentially need to update
344 // blocks successors too.
345 changed = true;
346 }
347
348 if (!changed) continue;
349
350 llvm::append_range(worklist, successors(ToUpdate));
351 }
352}
353
354namespace llvm {
355namespace {
356/// An assembly annotator class to print LazyValueCache information in
357/// comments.
358class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
359 LazyValueInfoImpl *LVIImpl;
360 // While analyzing which blocks we can solve values for, we need the dominator
361 // information.
362 DominatorTree &DT;
363
364public:
365 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
366 : LVIImpl(L), DT(DTree) {}
367
368 void emitBasicBlockStartAnnot(const BasicBlock *BB,
369 formatted_raw_ostream &OS) override;
370
371 void emitInstructionAnnot(const Instruction *I,
372 formatted_raw_ostream &OS) override;
373};
374} // namespace
375// The actual implementation of the lazy analysis and update.
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 *CxtI);
410 std::optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
411 BasicBlock *T,
412 Instruction *CxtI = 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 *CxtI,
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 *CxtI,
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 *CxtI = 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 *CxtI = 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 : TheCache(F), AC(AC), DL(DL), GuardDecl(GuardDecl) {}
524};
525} // namespace llvm
526
527void LazyValueInfoImpl::solve() {
529 BlockValueStack;
530
531 unsigned processedCount = 0;
532 while (!BlockValueStack.empty()) {
533 processedCount++;
534 // Abort if we have to process too many values to get a result for this one.
535 // Because of the design of the overdefined cache currently being per-block
536 // to avoid naming-related issues (IE it wants to try to give different
537 // results for the same name in different blocks), overdefined results don't
538 // get cached globally, which in turn means we will often try to rediscover
539 // the same overdefined result again and again. Once something like
540 // PredicateInfo is used in LVI or CVP, we should be able to make the
541 // overdefined cache global, and remove this throttle.
542 if (processedCount > MaxProcessedPerValue) {
544 dbgs() << "Giving up on stack because we are getting too deep\n");
545 // Fill in the original values
546 while (!StartingStack.empty()) {
547 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
548 TheCache.insertResult(e.second, e.first,
550 StartingStack.pop_back();
551 }
552 BlockValueSet.clear();
553 BlockValueStack.clear();
554 return;
555 }
556 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
557 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
558 unsigned StackSize = BlockValueStack.size();
559 (void) StackSize;
560
561 if (solveBlockValue(e.second, e.first)) {
562 // The work item was completely processed.
563 assert(BlockValueStack.size() == StackSize &&
564 BlockValueStack.back() == e && "Nothing should have been pushed!");
565#ifndef NDEBUG
566 std::optional<ValueLatticeElement> BBLV =
567 TheCache.getCachedValueInfo(e.second, e.first);
568 assert(BBLV && "Result should be in cache!");
570 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
571 << *BBLV << "\n");
572#endif
573
574 BlockValueStack.pop_back();
575 BlockValueSet.erase(e);
576 } else {
577 // More work needs to be done before revisiting.
578 assert(BlockValueStack.size() == StackSize + 1 &&
579 "Exactly one element should have been pushed!");
580 }
581 }
582}
583
584std::optional<ValueLatticeElement>
585LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB,
586 Instruction *CxtI) {
587 // If already a constant, there is nothing to compute.
588 if (Constant *VC = dyn_cast<Constant>(Val))
589 return ValueLatticeElement::get(VC);
590
591 if (std::optional<ValueLatticeElement> OptLatticeVal =
592 TheCache.getCachedValueInfo(Val, BB)) {
593 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
594 return OptLatticeVal;
595 }
596
597 // We have hit a cycle, assume overdefined.
598 if (!pushBlockValue({ BB, Val }))
600
601 // Yet to be resolved.
602 return std::nullopt;
603}
604
606 switch (BBI->getOpcode()) {
607 default:
608 break;
609 case Instruction::Call:
610 case Instruction::Invoke:
611 if (std::optional<ConstantRange> Range = cast<CallBase>(BBI)->getRange())
613 [[fallthrough]];
614 case Instruction::Load:
615 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
616 if (isa<IntegerType>(BBI->getType())) {
619 }
620 break;
621 };
622 // Nothing known - will be intersected with other facts
624}
625
626bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
627 assert(!isa<Constant>(Val) && "Value should not be constant");
628 assert(!TheCache.getCachedValueInfo(Val, BB) &&
629 "Value should not be in cache");
630
631 // Hold off inserting this value into the Cache in case we have to return
632 // false and come back later.
633 std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
634 if (!Res)
635 // Work pushed, will revisit
636 return false;
637
638 TheCache.insertResult(Val, BB, *Res);
639 return true;
640}
641
642std::optional<ValueLatticeElement>
643LazyValueInfoImpl::solveBlockValueImpl(Value *Val, BasicBlock *BB) {
645 if (!BBI || BBI->getParent() != BB)
646 return solveBlockValueNonLocal(Val, BB);
647
648 if (PHINode *PN = dyn_cast<PHINode>(BBI))
649 return solveBlockValuePHINode(PN, BB);
650
651 if (auto *SI = dyn_cast<SelectInst>(BBI))
652 return solveBlockValueSelect(SI, BB);
653
654 // If this value is a nonnull pointer, record it's range and bailout. Note
655 // that for all other pointer typed values, we terminate the search at the
656 // definition. We could easily extend this to look through geps, bitcasts,
657 // and the like to prove non-nullness, but it's not clear that's worth it
658 // compile time wise. The context-insensitive value walk done inside
659 // isKnownNonZero gets most of the profitable cases at much less expense.
660 // This does mean that we have a sensitivity to where the defining
661 // instruction is placed, even if it could legally be hoisted much higher.
662 // That is unfortunate.
664 if (PT && isKnownNonZero(BBI, DL))
666
667 if (BBI->getType()->isIntOrIntVectorTy()) {
668 if (auto *CI = dyn_cast<CastInst>(BBI))
669 return solveBlockValueCast(CI, BB);
670
671 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
672 return solveBlockValueBinaryOp(BO, BB);
673
674 if (auto *IEI = dyn_cast<InsertElementInst>(BBI))
675 return solveBlockValueInsertElement(IEI, BB);
676
677 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
678 return solveBlockValueExtractValue(EVI, BB);
679
680 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
681 return solveBlockValueIntrinsic(II, BB);
682 }
683
684 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
685 << "' - unknown inst def found.\n");
686 return getFromRangeMetadata(BBI);
687}
688
689static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet,
690 bool IsDereferenced = true) {
691 // TODO: Use NullPointerIsDefined instead.
692 if (Ptr->getType()->getPointerAddressSpace() == 0)
693 PtrSet.insert(IsDereferenced ? getUnderlyingObject(Ptr)
694 : Ptr->stripInBoundsOffsets());
695}
696
698 Instruction *I, NonNullPointerSet &PtrSet) {
699 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
700 AddNonNullPointer(L->getPointerOperand(), PtrSet);
701 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
702 AddNonNullPointer(S->getPointerOperand(), PtrSet);
703 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
704 if (MI->isVolatile()) return;
705
706 // FIXME: check whether it has a valuerange that excludes zero?
707 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
708 if (!Len || Len->isZero()) return;
709
710 AddNonNullPointer(MI->getRawDest(), PtrSet);
712 AddNonNullPointer(MTI->getRawSource(), PtrSet);
713 } else if (auto *CB = dyn_cast<CallBase>(I)) {
714 for (auto &U : CB->args()) {
715 if (U->getType()->isPointerTy() &&
716 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
717 /*AllowUndefOrPoison=*/false))
718 AddNonNullPointer(U.get(), PtrSet, /*IsDereferenced=*/false);
719 }
720 }
721}
722
723bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
726 return false;
727
728 Val = Val->stripInBoundsOffsets();
729 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
730 NonNullPointerSet NonNullPointers;
731 for (Instruction &I : *BB)
732 AddNonNullPointersByInstruction(&I, NonNullPointers);
733 return NonNullPointers;
734 });
735}
736
737std::optional<ValueLatticeElement>
738LazyValueInfoImpl::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
739 ValueLatticeElement Result; // Start Undefined.
740
741 // If this is the entry block, we must be asking about an argument.
742 if (BB->isEntryBlock()) {
743 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
744 if (std::optional<ConstantRange> Range = cast<Argument>(Val)->getRange())
747 }
748
749 // Loop over all of our predecessors, merging what we know from them into
750 // result. If we encounter an unexplored predecessor, we eagerly explore it
751 // in a depth first manner. In practice, this has the effect of discovering
752 // paths we can't analyze eagerly without spending compile times analyzing
753 // other paths. This heuristic benefits from the fact that predecessors are
754 // frequently arranged such that dominating ones come first and we quickly
755 // find a path to function entry. TODO: We should consider explicitly
756 // canonicalizing to make this true rather than relying on this happy
757 // accident.
758 std::optional<BBLatticeElementMap> PredLatticeElements;
759 if (PerPredRanges)
760 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
761 for (BasicBlock *Pred : predecessors(BB)) {
762 // Skip self loops.
763 if (Pred == BB)
764 continue;
765 std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
766 if (!EdgeResult)
767 // Explore that input, then return here
768 return std::nullopt;
769
770 Result.mergeIn(*EdgeResult);
771
772 // If we hit overdefined, exit early. The BlockVals entry is already set
773 // to overdefined.
774 if (Result.isOverdefined()) {
775 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
776 << "' - overdefined because of pred '"
777 << Pred->getName() << "' (non local).\n");
778 return Result;
779 }
780 if (PerPredRanges)
781 PredLatticeElements->insert({Pred, *EdgeResult});
782 }
783
784 if (PerPredRanges)
785 TheCache.insertPredecessorResults(Val, BB, *PredLatticeElements);
786
787 // Return the merged value, which is more precise than 'overdefined'.
788 assert(!Result.isOverdefined());
789 return Result;
790}
791
792std::optional<ValueLatticeElement>
793LazyValueInfoImpl::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
794 ValueLatticeElement Result; // Start Undefined.
795
796 // Loop over all of our predecessors, merging what we know from them into
797 // result. See the comment about the chosen traversal order in
798 // solveBlockValueNonLocal; the same reasoning applies here.
799 std::optional<BBLatticeElementMap> PredLatticeElements;
800 if (PerPredRanges)
801 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
802 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
803 BasicBlock *PhiBB = PN->getIncomingBlock(i);
804 Value *PhiVal = PN->getIncomingValue(i);
805 // Note that we can provide PN as the context value to getEdgeValue, even
806 // though the results will be cached, because PN is the value being used as
807 // the cache key in the caller.
808 std::optional<ValueLatticeElement> EdgeResult =
809 getEdgeValue(PhiVal, PhiBB, BB, PN);
810 if (!EdgeResult)
811 // Explore that input, then return here
812 return std::nullopt;
813
814 Result.mergeIn(*EdgeResult);
815
816 // If we hit overdefined, exit early. The BlockVals entry is already set
817 // to overdefined.
818 if (Result.isOverdefined()) {
819 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
820 << "' - overdefined because of pred (local).\n");
821
822 return Result;
823 }
824
825 if (PerPredRanges)
826 PredLatticeElements->insert({PhiBB, *EdgeResult});
827 }
828
829 if (PerPredRanges)
830 TheCache.insertPredecessorResults(PN, BB, *PredLatticeElements);
831
832 // Return the merged value, which is more precise than 'overdefined'.
833 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
834 return Result;
835}
836
837// If we can determine a constraint on the value given conditions assumed by
838// the program, intersect those constraints with BBLV
839void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
840 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
841 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
842 if (!BBI)
843 return;
844
845 BasicBlock *BB = BBI->getParent();
846 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
847 if (!AssumeVH)
848 continue;
849
850 // Only check assumes in the block of the context instruction. Other
851 // assumes will have already been taken into account when the value was
852 // propagated from predecessor blocks.
853 auto *I = cast<AssumeInst>(AssumeVH);
854
855 if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
856 continue;
857
858 if (AssumeVH.Index != AssumptionCache::ExprResultIdx) {
859 auto OBU = I->getOperandBundleAt(AssumeVH.Index);
860 switch (getBundleAttrFromOBU(OBU)) {
861 case BundleAttr::NonNull:
862 if (getAssumeNonNullInfo(OBU).Ptr != Val)
863 break;
866 break;
867
868 case BundleAttr::Dereferenceable: {
869 auto [Ptr, _, Count] = getAssumeDereferenceableInfo(OBU);
870 if (Ptr != Val || !Count || *Count == 0)
871 break;
874 } break;
875
876 default:
877 break;
878 }
879 } else {
880 BBLV = BBLV.intersect(*getValueFromCondition(Val, I->getArgOperand(0),
881 /*IsTrueDest*/ true,
882 /*UseBlockValue*/ false));
883 }
884 }
885
886 // If guards are not used in the module, don't spend time looking for them
887 if (GuardDecl && !GuardDecl->use_empty() &&
888 BBI->getIterator() != BB->begin()) {
889 for (Instruction &I :
890 make_range(std::next(BBI->getIterator().getReverse()), BB->rend())) {
891 Value *Cond = nullptr;
893 BBLV = BBLV.intersect(*getValueFromCondition(Val, Cond,
894 /*IsTrueDest*/ true,
895 /*UseBlockValue*/ false));
896 }
897 }
898
899 if (BBLV.isOverdefined()) {
900 // Check whether we're checking at the terminator, and the pointer has
901 // been dereferenced in this block.
903 if (PTy && BB->getTerminator() == BBI &&
904 isNonNullAtEndOfBlock(Val, BB))
906 }
907}
908
909std::optional<ValueLatticeElement>
910LazyValueInfoImpl::solveBlockValueSelect(SelectInst *SI, BasicBlock *BB) {
911 // Recurse on our inputs if needed
912 std::optional<ValueLatticeElement> OptTrueVal =
913 getBlockValue(SI->getTrueValue(), BB, SI);
914 if (!OptTrueVal)
915 return std::nullopt;
916 ValueLatticeElement &TrueVal = *OptTrueVal;
917
918 std::optional<ValueLatticeElement> OptFalseVal =
919 getBlockValue(SI->getFalseValue(), BB, SI);
920 if (!OptFalseVal)
921 return std::nullopt;
922 ValueLatticeElement &FalseVal = *OptFalseVal;
923
924 if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
925 const ConstantRange &TrueCR = TrueVal.asConstantRange(SI->getType());
926 const ConstantRange &FalseCR = FalseVal.asConstantRange(SI->getType());
927 Value *LHS = nullptr;
928 Value *RHS = nullptr;
929 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
930 // Is this a min specifically of our two inputs? (Avoid the risk of
931 // ValueTracking getting smarter looking back past our immediate inputs.)
933 ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
934 (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
935 ConstantRange ResultCR = [&]() {
936 switch (SPR.Flavor) {
937 default:
938 llvm_unreachable("unexpected minmax type!");
939 case SPF_SMIN: /// Signed minimum
940 return TrueCR.smin(FalseCR);
941 case SPF_UMIN: /// Unsigned minimum
942 return TrueCR.umin(FalseCR);
943 case SPF_SMAX: /// Signed maximum
944 return TrueCR.smax(FalseCR);
945 case SPF_UMAX: /// Unsigned maximum
946 return TrueCR.umax(FalseCR);
947 };
948 }();
950 ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
951 FalseVal.isConstantRangeIncludingUndef());
952 }
953
954 if (SPR.Flavor == SPF_ABS) {
955 if (LHS == SI->getTrueValue())
957 TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
958 if (LHS == SI->getFalseValue())
960 FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
961 }
962
963 if (SPR.Flavor == SPF_NABS) {
964 ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
965 if (LHS == SI->getTrueValue())
967 Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
968 if (LHS == SI->getFalseValue())
970 Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
971 }
972 }
973
974 // Can we constrain the facts about the true and false values by using the
975 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
976 // TODO: We could potentially refine an overdefined true value above.
977 Value *Cond = SI->getCondition();
978 // If the value is undef, a different value may be chosen in
979 // the select condition.
981 TrueVal =
982 TrueVal.intersect(*getValueFromCondition(SI->getTrueValue(), Cond,
983 /*IsTrueDest*/ true,
984 /*UseBlockValue*/ false));
985 FalseVal =
986 FalseVal.intersect(*getValueFromCondition(SI->getFalseValue(), Cond,
987 /*IsTrueDest*/ false,
988 /*UseBlockValue*/ false));
989 }
990
991 TrueVal.mergeIn(FalseVal);
992 return TrueVal;
993}
994
995std::optional<ConstantRange>
996LazyValueInfoImpl::getRangeFor(Value *V, Instruction *CxtI, BasicBlock *BB) {
997 std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
998 if (!OptVal)
999 return std::nullopt;
1000 return OptVal->asConstantRange(V->getType());
1001}
1002
1003std::optional<ValueLatticeElement>
1004LazyValueInfoImpl::solveBlockValueCast(CastInst *CI, BasicBlock *BB) {
1005 // Filter out casts we don't know how to reason about before attempting to
1006 // recurse on our operand. This can cut a long search short if we know we're
1007 // not going to be able to get any useful information anways.
1008 switch (CI->getOpcode()) {
1009 case Instruction::Trunc:
1010 case Instruction::SExt:
1011 case Instruction::ZExt:
1012 break;
1013 default:
1014 // Unhandled instructions are overdefined.
1015 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1016 << "' - overdefined (unknown cast).\n");
1018 }
1019
1020 // Figure out the range of the LHS. If that fails, we still apply the
1021 // transfer rule on the full set since we may be able to locally infer
1022 // interesting facts.
1023 std::optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
1024 if (!LHSRes)
1025 // More work to do before applying this transfer rule.
1026 return std::nullopt;
1027 const ConstantRange &LHSRange = *LHSRes;
1028
1029 const unsigned ResultBitWidth = CI->getType()->getScalarSizeInBits();
1030
1031 // NOTE: We're currently limited by the set of operations that ConstantRange
1032 // can evaluate symbolically. Enhancing that set will allows us to analyze
1033 // more definitions.
1034 ConstantRange Res = ConstantRange::getEmpty(ResultBitWidth);
1035 if (auto *Trunc = dyn_cast<TruncInst>(CI))
1036 Res = LHSRange.truncate(ResultBitWidth, Trunc->getNoWrapKind());
1037 else
1038 Res = LHSRange.castOp(CI->getOpcode(), ResultBitWidth);
1039
1041}
1042
1043std::optional<ValueLatticeElement>
1044LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
1045 Instruction *I, BasicBlock *BB,
1046 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
1047 OpFn) {
1048 Value *LHS = I->getOperand(0);
1049 Value *RHS = I->getOperand(1);
1050
1051 auto ThreadBinOpOverSelect =
1052 [&](Value *X, const ConstantRange &CRX, SelectInst *Y,
1053 bool XIsLHS) -> std::optional<ValueLatticeElement> {
1054 Value *Cond = Y->getCondition();
1055 // Only handle selects with constant values.
1056 Constant *TrueC = dyn_cast<Constant>(Y->getTrueValue());
1057 if (!TrueC)
1058 return std::nullopt;
1059 Constant *FalseC = dyn_cast<Constant>(Y->getFalseValue());
1060 if (!FalseC)
1061 return std::nullopt;
1063 return std::nullopt;
1064
1065 ConstantRange TrueX =
1066 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/true,
1067 /*UseBlockValue=*/false)
1068 ->asConstantRange(X->getType()));
1069 ConstantRange FalseX =
1070 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/false,
1071 /*UseBlockValue=*/false)
1072 ->asConstantRange(X->getType()));
1073 ConstantRange TrueY = TrueC->toConstantRange();
1074 ConstantRange FalseY = FalseC->toConstantRange();
1075
1076 if (XIsLHS)
1078 OpFn(TrueX, TrueY).unionWith(OpFn(FalseX, FalseY)));
1080 OpFn(TrueY, TrueX).unionWith(OpFn(FalseY, FalseX)));
1081 };
1082
1083 // Figure out the ranges of the operands. If that fails, use a
1084 // conservative range, but apply the transfer rule anyways. This
1085 // lets us pick up facts from expressions like "and i32 (call i32
1086 // @foo()), 32"
1087 std::optional<ConstantRange> LHSRes = getRangeFor(LHS, I, BB);
1088 if (!LHSRes)
1089 return std::nullopt;
1090
1091 // Try to thread binop over rhs select
1092 if (auto *SI = dyn_cast<SelectInst>(RHS)) {
1093 if (auto Res = ThreadBinOpOverSelect(LHS, *LHSRes, SI, /*XIsLHS=*/true))
1094 return *Res;
1095 }
1096
1097 std::optional<ConstantRange> RHSRes = getRangeFor(RHS, I, BB);
1098 if (!RHSRes)
1099 return std::nullopt;
1100
1101 // Try to thread binop over lhs select
1102 if (auto *SI = dyn_cast<SelectInst>(LHS)) {
1103 if (auto Res = ThreadBinOpOverSelect(RHS, *RHSRes, SI, /*XIsLHS=*/false))
1104 return *Res;
1105 }
1106
1107 const ConstantRange &LHSRange = *LHSRes;
1108 const ConstantRange &RHSRange = *RHSRes;
1109
1110 std::optional<ValueLatticeElement> MergedResult =
1111 ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
1112
1113 if (!PerPredRanges)
1114 return MergedResult;
1115
1116 std::optional<BBLatticeElementMap> PredLHS =
1117 TheCache.getCachedPredecessorInfo(LHS, BB);
1118 if (!PredLHS)
1119 return MergedResult;
1120 std::optional<BBLatticeElementMap> PredRHS =
1121 TheCache.getCachedPredecessorInfo(RHS, BB);
1122 if (!PredRHS)
1123 return MergedResult;
1124
1125 const BBLatticeElementMap &LHSPredMap = *PredLHS;
1126 const BBLatticeElementMap &RHSPredMap = *PredRHS;
1127
1128 BBLatticeElementMap PredLatticeElements;
1129 ValueLatticeElement OverallPredResult;
1130 for (auto *Pred : predecessors(BB)) {
1131 auto LHSIt = LHSPredMap.find_as(Pred);
1132 if (LHSIt == LHSPredMap.end())
1133 return MergedResult;
1134 const ValueLatticeElement &LHSFromPred = LHSIt->second;
1135 std::optional<ConstantRange> LHSFromPredRes =
1136 LHSFromPred.asConstantRange(LHS->getType());
1137 if (!LHSFromPredRes)
1138 return MergedResult;
1139
1140 auto RHSIt = RHSPredMap.find_as(Pred);
1141 if (RHSIt == RHSPredMap.end())
1142 return MergedResult;
1143 const ValueLatticeElement &RHSFromPred = RHSIt->second;
1144 std::optional<ConstantRange> RHSFromPredRes =
1145 RHSFromPred.asConstantRange(RHS->getType());
1146 if (!RHSFromPredRes)
1147 return MergedResult;
1148
1149 const ConstantRange &LHSFromPredRange = *LHSFromPredRes;
1150 const ConstantRange &RHSFromPredRange = *RHSFromPredRes;
1151 std::optional<ValueLatticeElement> PredResult =
1152 ValueLatticeElement::getRange(OpFn(LHSFromPredRange, RHSFromPredRange));
1153 if (!PredResult)
1154 return MergedResult;
1155 if (PredResult->isOverdefined()) {
1156 LLVM_DEBUG(
1157 dbgs() << " pred BB '" << Pred->getName() << "' for BB '"
1158 << BB->getName()
1159 << "' overdefined. Discarding all predecessor intervals.\n");
1160 return MergedResult;
1161 }
1162 PredLatticeElements.insert({Pred, *PredResult});
1163 OverallPredResult.mergeIn(*PredResult);
1164 }
1165
1166 // If this point is reached, all predecessors for both LHS and RHS have
1167 // constant ranges previously computed. Can cache result and use the
1168 // OverallPredResult;
1169 TheCache.insertPredecessorResults(I, BB, PredLatticeElements);
1170
1171 LLVM_DEBUG(dbgs() << " Using predecessor intervals, evaluated " << *I
1172 << " to: " << OverallPredResult << ".\n");
1173
1174 if (!MergedResult)
1175 return OverallPredResult;
1176
1177 LLVM_DEBUG(dbgs() << " Intersecting intervals for " << *I << ": "
1178 << OverallPredResult << " and " << MergedResult << ".\n");
1179 return MergedResult->intersect(OverallPredResult);
1180}
1181
1182std::optional<ValueLatticeElement>
1183LazyValueInfoImpl::solveBlockValueBinaryOp(BinaryOperator *BO, BasicBlock *BB) {
1184 assert(BO->getOperand(0)->getType()->isSized() &&
1185 "all operands to binary operators are sized");
1186 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
1187 unsigned NoWrapKind = OBO->getNoWrapKind();
1188 return solveBlockValueBinaryOpImpl(
1189 BO, BB,
1190 [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
1191 return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
1192 });
1193 }
1194
1195 return solveBlockValueBinaryOpImpl(
1196 BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1197 return CR1.binaryOp(BO->getOpcode(), CR2);
1198 });
1199}
1200
1201std::optional<ValueLatticeElement>
1202LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
1203 BasicBlock *BB) {
1204 return solveBlockValueBinaryOpImpl(
1205 WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1206 return CR1.binaryOp(WO->getBinaryOp(), CR2);
1207 });
1208}
1209
1210std::optional<ValueLatticeElement>
1211LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
1212 ValueLatticeElement MetadataVal = getFromRangeMetadata(II);
1213 if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1214 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1215 << "' - unknown intrinsic.\n");
1216 return MetadataVal;
1217 }
1218
1220 for (Value *Op : II->args()) {
1221 std::optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1222 if (!Range)
1223 return std::nullopt;
1224 OpRanges.push_back(*Range);
1225 }
1226
1228 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges))
1229 .intersect(MetadataVal);
1230}
1231
1232std::optional<ValueLatticeElement>
1233LazyValueInfoImpl::solveBlockValueInsertElement(InsertElementInst *IEI,
1234 BasicBlock *BB) {
1235 std::optional<ValueLatticeElement> OptEltVal =
1236 getBlockValue(IEI->getOperand(1), BB, IEI);
1237 if (!OptEltVal)
1238 return std::nullopt;
1239 ValueLatticeElement &Res = *OptEltVal;
1240
1241 std::optional<ValueLatticeElement> OptVecVal =
1242 getBlockValue(IEI->getOperand(0), BB, IEI);
1243 if (!OptVecVal)
1244 return std::nullopt;
1245
1246 // Bail out if the inserted element is a constant expression. Unlike other
1247 // ValueLattice types, these are not considered an implicit splat when a
1248 // vector type is used.
1249 // We could call ConstantFoldInsertElementInstruction here to handle these.
1250 if (OptEltVal->isConstant())
1252
1253 Res.mergeIn(*OptVecVal);
1254 return Res;
1255}
1256
1257std::optional<ValueLatticeElement>
1258LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
1259 BasicBlock *BB) {
1260 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1261 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1262 return solveBlockValueOverflowIntrinsic(WO, BB);
1263
1264 // Handle extractvalue of insertvalue to allow further simplification
1265 // based on replaced with.overflow intrinsics.
1267 EVI->getAggregateOperand(), EVI->getIndices(),
1268 EVI->getDataLayout()))
1269 return getBlockValue(V, BB, EVI);
1270
1271 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1272 << "' - overdefined (unknown extractvalue).\n");
1274}
1275
1277 ICmpInst::Predicate Pred) {
1278 if (LHS == Val)
1279 return true;
1280
1281 // Handle range checking idiom produced by InstCombine. We will subtract the
1282 // offset from the allowed range for RHS in this case.
1283 const APInt *C;
1284 if (match(LHS, m_AddLike(m_Specific(Val), m_APInt(C)))) {
1285 Offset = *C;
1286 return true;
1287 }
1288
1289 // Handle the symmetric case. This appears in saturation patterns like
1290 // (x == 16) ? 16 : (x + 1).
1291 if (match(Val, m_AddLike(m_Specific(LHS), m_APInt(C)))) {
1292 Offset = -*C;
1293 return true;
1294 }
1295
1296 // If (x | y) < C, then (x < C) && (y < C).
1297 if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1298 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
1299 return true;
1300
1301 // If (x & y) > C, then (x > C) && (y > C).
1302 if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1303 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
1304 return true;
1305
1306 return false;
1307}
1308
1309/// Get value range for a "(Val + Offset) Pred RHS" condition.
1310std::optional<ValueLatticeElement>
1311LazyValueInfoImpl::getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,
1312 Value *RHS,
1313 const APInt &Offset,
1314 Instruction *CxtI,
1315 bool UseBlockValue) {
1316 ConstantRange RHSRange(RHS->getType()->getScalarSizeInBits(),
1317 /*isFullSet=*/true);
1318 if (auto *C = dyn_cast<Constant>(RHS)) {
1319 RHSRange = C->toConstantRange();
1320 } else if (UseBlockValue) {
1321 std::optional<ValueLatticeElement> R =
1322 getBlockValue(RHS, CxtI->getParent(), CxtI);
1323 if (!R)
1324 return std::nullopt;
1325 RHSRange = R->asConstantRange(RHS->getType());
1326 }
1327
1328 ConstantRange TrueValues =
1330 return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1331}
1332
1333static std::optional<ConstantRange>
1335 function_ref<std::optional<ConstantRange>(const APInt &)> Fn) {
1336 bool Invert = false;
1337 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
1338 Pred = ICmpInst::getInversePredicate(Pred);
1339 Invert = true;
1340 }
1341 if (Pred == ICmpInst::ICMP_SLE) {
1342 Pred = ICmpInst::ICMP_SLT;
1343 if (RHS.isMaxSignedValue())
1344 return std::nullopt; // Could also return full/empty here, if we wanted.
1345 ++RHS;
1346 }
1347 assert(Pred == ICmpInst::ICMP_SLT && "Must be signed predicate");
1348 if (auto CR = Fn(RHS))
1349 return Invert ? CR->inverse() : CR;
1350 return std::nullopt;
1351}
1352
1353/// Get value range for a "ctpop(Val) Pred RHS" condition.
1355 Value *RHS) {
1356 unsigned BitWidth = RHS->getType()->getScalarSizeInBits();
1357
1358 auto *RHSConst = dyn_cast<ConstantInt>(RHS);
1359 if (!RHSConst)
1361
1362 ConstantRange ResValRange =
1363 ConstantRange::makeExactICmpRegion(Pred, RHSConst->getValue());
1364
1365 unsigned ResMin = ResValRange.getUnsignedMin().getLimitedValue(BitWidth);
1366 unsigned ResMax = ResValRange.getUnsignedMax().getLimitedValue(BitWidth);
1367
1368 APInt ValMin = APInt::getLowBitsSet(BitWidth, ResMin);
1369 APInt ValMax = APInt::getHighBitsSet(BitWidth, ResMax);
1371 ConstantRange::getNonEmpty(std::move(ValMin), ValMax + 1));
1372}
1373
1374std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1375 Value *Val, ICmpInst *ICI, bool isTrueDest, bool UseBlockValue) {
1376 Value *LHS = ICI->getOperand(0);
1377 Value *RHS = ICI->getOperand(1);
1378
1379 // Get the predicate that must hold along the considered edge.
1380 CmpInst::Predicate EdgePred =
1381 isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1382
1383 if (isa<Constant>(RHS)) {
1384 if (ICI->isEquality() && LHS == Val) {
1385 if (EdgePred == ICmpInst::ICMP_EQ)
1387 else if (!isa<UndefValue>(RHS))
1389 }
1390 }
1391
1392 Type *Ty = Val->getType();
1393 if (!Ty->isIntOrIntVectorTy())
1395
1396 unsigned BitWidth = Ty->getScalarSizeInBits();
1397 APInt Offset(BitWidth, 0);
1398 if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1399 return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset, ICI,
1400 UseBlockValue);
1401
1402 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1403 if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1404 return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset, ICI,
1405 UseBlockValue);
1406
1407 if (match(LHS, m_Ctpop(m_Specific(Val))))
1408 return getValueFromICmpCtpop(EdgePred, RHS);
1409
1410 const APInt *Mask, *C;
1411 if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1412 match(RHS, m_APInt(C))) {
1413 // If (Val & Mask) == C then all the masked bits are known and we can
1414 // compute a value range based on that.
1415 if (EdgePred == ICmpInst::ICMP_EQ) {
1416 KnownBits Known;
1417 Known.Zero = ~*C & *Mask;
1418 Known.One = *C & *Mask;
1420 ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1421 }
1422
1423 if (EdgePred == ICmpInst::ICMP_NE)
1426 }
1427
1428 // If (X urem Modulus) >= C, then X >= C.
1429 // If trunc X >= C, then X >= C.
1430 // TODO: An upper bound could be computed as well.
1432 m_Trunc(m_Specific(Val)))) &&
1433 match(RHS, m_APInt(C))) {
1434 // Use the icmp region so we don't have to deal with different predicates.
1435 ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
1436 if (!CR.isEmptySet())
1438 CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
1439 }
1440
1441 // Recognize:
1442 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, C << ShAmtC
1443 // Preconditions: (C << ShAmtC) >> ShAmtC == C
1444 const APInt *ShAmtC;
1445 if (CmpInst::isSigned(EdgePred) &&
1446 match(LHS, m_AShr(m_Specific(Val), m_APInt(ShAmtC))) &&
1447 match(RHS, m_APInt(C))) {
1448 auto CR = getRangeViaSLT(
1449 EdgePred, *C, [&](const APInt &RHS) -> std::optional<ConstantRange> {
1450 APInt New = RHS << *ShAmtC;
1451 if ((New.ashr(*ShAmtC)) != RHS)
1452 return std::nullopt;
1454 APInt::getSignedMinValue(New.getBitWidth()), New);
1455 });
1456 if (CR)
1458 }
1459
1460 // a - b or ptrtoint(a) - ptrtoint(b) ==/!= 0 if a ==/!= b
1461 Value *X, *Y;
1462 if (ICI->isEquality() && match(Val, m_Sub(m_Value(X), m_Value(Y)))) {
1463 // Peek through ptrtoints
1466 if ((X == LHS && Y == RHS) || (X == RHS && Y == LHS)) {
1467 Constant *NullVal = Constant::getNullValue(Val->getType());
1468 if (EdgePred == ICmpInst::ICMP_EQ)
1469 return ValueLatticeElement::get(NullVal);
1470 return ValueLatticeElement::getNot(NullVal);
1471 }
1472 }
1473
1475}
1476
1477ValueLatticeElement LazyValueInfoImpl::getValueFromTrunc(Value *Val,
1478 TruncInst *Trunc,
1479 bool IsTrueDest) {
1480 assert(Trunc->getType()->isIntOrIntVectorTy(1));
1481
1482 if (Trunc->getOperand(0) != Val)
1484
1485 Type *Ty = Val->getType();
1486
1487 if (Trunc->hasNoUnsignedWrap()) {
1488 if (IsTrueDest)
1489 return ValueLatticeElement::get(ConstantInt::get(Ty, 1));
1491 }
1492
1493 if (IsTrueDest)
1496}
1497
1498// Handle conditions of the form
1499// extractvalue(op.with.overflow(%x, C), 1).
1501 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1502 // TODO: This only works with a constant RHS for now. We could also compute
1503 // the range of the RHS, but this doesn't fit into the current structure of
1504 // the edge value calculation.
1505 const APInt *C;
1506 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1508
1509 // Calculate the possible values of %x for which no overflow occurs.
1511 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1512
1513 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1514 // constrained to it's inverse (all values that might cause overflow).
1515 if (IsTrueDest)
1516 NWR = NWR.inverse();
1518}
1519
1520std::optional<ValueLatticeElement>
1521LazyValueInfoImpl::getValueFromCondition(Value *Val, Value *Cond,
1522 bool IsTrueDest, bool UseBlockValue,
1523 unsigned Depth) {
1524 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1525 return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
1526
1527 if (auto *Trunc = dyn_cast<TruncInst>(Cond))
1528 return getValueFromTrunc(Val, Trunc, IsTrueDest);
1529
1530 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1531 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1532 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1533 return getValueFromOverflowCondition(Val, WO, IsTrueDest);
1534
1537
1538 Value *N;
1539 if (match(Cond, m_Not(m_Value(N))))
1540 return getValueFromCondition(Val, N, !IsTrueDest, UseBlockValue, Depth);
1541
1542 Value *L, *R;
1543 bool IsAnd;
1544 if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1545 IsAnd = true;
1546 else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1547 IsAnd = false;
1548 else
1550
1551 std::optional<ValueLatticeElement> LV =
1552 getValueFromCondition(Val, L, IsTrueDest, UseBlockValue, Depth);
1553 if (!LV)
1554 return std::nullopt;
1555 std::optional<ValueLatticeElement> RV =
1556 getValueFromCondition(Val, R, IsTrueDest, UseBlockValue, Depth);
1557 if (!RV)
1558 return std::nullopt;
1559
1560 // if (L && R) -> intersect L and R
1561 // if (!(L || R)) -> intersect !L and !R
1562 // if (L || R) -> union L and R
1563 // if (!(L && R)) -> union !L and !R
1564 if (IsTrueDest ^ IsAnd) {
1565 LV->mergeIn(*RV);
1566 return *LV;
1567 }
1568
1569 return LV->intersect(*RV);
1570}
1571
1572// Return true if Usr has Op as an operand, otherwise false.
1573static bool usesOperand(User *Usr, Value *Op) {
1574 return is_contained(Usr->operands(), Op);
1575}
1576
1577// Return true if the instruction type of Val is supported by
1578// constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1579// Call this before calling constantFoldUser() to find out if it's even worth
1580// attempting to call it.
1581static bool isOperationFoldable(User *Usr) {
1582 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1583}
1584
1585// Check if Usr can be simplified to an integer constant when the value of one
1586// of its operands Op is an integer constant OpConstVal. If so, return it as an
1587// lattice value range with a single element or otherwise return an overdefined
1588// lattice value.
1590 const APInt &OpConstVal,
1591 const DataLayout &DL) {
1592 assert(isOperationFoldable(Usr) && "Precondition");
1593 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1594 // Check if Usr can be simplified to a constant.
1595 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1596 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1597 if (auto *C = dyn_cast_or_null<ConstantInt>(
1598 simplifyCastInst(CI->getOpcode(), OpConst,
1599 CI->getDestTy(), DL))) {
1600 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1601 }
1602 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1603 bool Op0Match = BO->getOperand(0) == Op;
1604 bool Op1Match = BO->getOperand(1) == Op;
1605 assert((Op0Match || Op1Match) &&
1606 "Operand 0 nor Operand 1 isn't a match");
1607 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1608 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1609 if (auto *C = dyn_cast_or_null<ConstantInt>(
1610 simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1611 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1612 }
1613 } else if (isa<FreezeInst>(Usr)) {
1614 assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1615 return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1616 }
1618}
1619
1620/// Compute the value of Val on the edge BBFrom -> BBTo.
1621std::optional<ValueLatticeElement>
1622LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1623 BasicBlock *BBTo, bool UseBlockValue) {
1624 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1625 // know that v != 0.
1626 if (CondBrInst *BI = dyn_cast<CondBrInst>(BBFrom->getTerminator())) {
1627 // If this is a conditional branch and only one successor goes to BBTo, then
1628 // we may be able to infer something from the condition.
1629 if (BI->getSuccessor(0) != BI->getSuccessor(1)) {
1630 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1631 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1632 "BBTo isn't a successor of BBFrom");
1633 Value *Condition = BI->getCondition();
1634
1635 // If V is the condition of the branch itself, then we know exactly what
1636 // it is.
1637 // NB: The condition on a `br` can't be a vector type.
1638 if (Condition == Val)
1639 return ValueLatticeElement::get(ConstantInt::get(
1640 Type::getInt1Ty(Val->getContext()), isTrueDest));
1641
1642 // If the condition of the branch is an equality comparison, we may be
1643 // able to infer the value.
1644 std::optional<ValueLatticeElement> Result =
1645 getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1646 if (!Result)
1647 return std::nullopt;
1648
1649 if (!Result->isOverdefined())
1650 return Result;
1651
1652 if (User *Usr = dyn_cast<User>(Val)) {
1653 assert(Result->isOverdefined() && "Result isn't overdefined");
1654 // Check with isOperationFoldable() first to avoid linearly iterating
1655 // over the operands unnecessarily which can be expensive for
1656 // instructions with many operands.
1657 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1658 const DataLayout &DL = BBTo->getDataLayout();
1659 if (usesOperand(Usr, Condition)) {
1660 // If Val has Condition as an operand and Val can be folded into a
1661 // constant with either Condition == true or Condition == false,
1662 // propagate the constant.
1663 // eg.
1664 // ; %Val is true on the edge to %then.
1665 // %Val = and i1 %Condition, true.
1666 // br %Condition, label %then, label %else
1667 APInt ConditionVal(1, isTrueDest ? 1 : 0);
1668 Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1669 } else if (isa<TruncInst, ZExtInst, SExtInst>(Usr)) {
1670 ValueLatticeElement OpLatticeVal =
1671 *getValueFromCondition(Usr->getOperand(0), Condition,
1672 isTrueDest, /*UseBlockValue*/ false);
1673
1674 if (OpLatticeVal.isConstantRange()) {
1675 const unsigned ResultBitWidth =
1676 Usr->getType()->getScalarSizeInBits();
1677 if (auto *Trunc = dyn_cast<TruncInst>(Usr))
1679 OpLatticeVal.getConstantRange().truncate(
1680 ResultBitWidth, Trunc->getNoWrapKind()));
1681
1683 OpLatticeVal.getConstantRange().castOp(
1684 cast<CastInst>(Usr)->getOpcode(), ResultBitWidth));
1685 }
1686 if (OpLatticeVal.isConstant()) {
1687 Constant *C = OpLatticeVal.getConstant();
1688 if (auto *CastC = ConstantFoldCastOperand(
1689 cast<CastInst>(Usr)->getOpcode(), C, Usr->getType(), DL))
1690 return ValueLatticeElement::get(CastC);
1691 }
1693 } else {
1694 // If one of Val's operand has an inferred value, we may be able to
1695 // infer the value of Val.
1696 // eg.
1697 // ; %Val is 94 on the edge to %then.
1698 // %Val = add i8 %Op, 1
1699 // %Condition = icmp eq i8 %Op, 93
1700 // br i1 %Condition, label %then, label %else
1701 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1702 Value *Op = Usr->getOperand(i);
1703 ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1704 Op, Condition, isTrueDest, /*UseBlockValue*/ false);
1705 if (std::optional<APInt> OpConst =
1706 OpLatticeVal.asConstantInteger()) {
1707 Result = constantFoldUser(Usr, Op, *OpConst, DL);
1708 break;
1709 }
1710 }
1711 }
1712 }
1713 }
1714 if (!Result->isOverdefined())
1715 return Result;
1716 }
1717 }
1718
1719 // If the edge was formed by a switch on the value, then we may know exactly
1720 // what it is.
1721 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1722 Value *Condition = SI->getCondition();
1723 if (!isa<IntegerType>(Val->getType()))
1725 bool ValUsesConditionAndMayBeFoldable = false;
1726 if (Condition != Val) {
1727 // Check if Val has Condition as an operand.
1728 if (User *Usr = dyn_cast<User>(Val))
1729 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1730 usesOperand(Usr, Condition);
1731 if (!ValUsesConditionAndMayBeFoldable)
1733 }
1734 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1735 "Condition != Val nor Val doesn't use Condition");
1736
1737 bool DefaultCase = SI->getDefaultDest() == BBTo;
1738 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1739 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1740
1741 for (auto Case : SI->cases()) {
1742 APInt CaseValue = Case.getCaseValue()->getValue();
1743 ConstantRange EdgeVal(CaseValue);
1744 if (ValUsesConditionAndMayBeFoldable) {
1745 User *Usr = cast<User>(Val);
1746 const DataLayout &DL = BBTo->getDataLayout();
1747 ValueLatticeElement EdgeLatticeVal =
1748 constantFoldUser(Usr, Condition, CaseValue, DL);
1749 if (EdgeLatticeVal.isOverdefined())
1751 EdgeVal = EdgeLatticeVal.getConstantRange();
1752 }
1753 if (DefaultCase) {
1754 // It is possible that the default destination is the destination of
1755 // some cases. We cannot perform difference for those cases.
1756 // We know Condition != CaseValue in BBTo. In some cases we can use
1757 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1758 // only do this when f is identity (i.e. Val == Condition), but we
1759 // should be able to do this for any injective f.
1760 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1761 EdgesVals = EdgesVals.difference(EdgeVal);
1762 } else if (Case.getCaseSuccessor() == BBTo)
1763 EdgesVals = EdgesVals.unionWith(EdgeVal);
1764 }
1765 return ValueLatticeElement::getRange(std::move(EdgesVals));
1766 }
1768}
1769
1770/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1771/// the basic block if the edge does not constrain Val.
1772std::optional<ValueLatticeElement>
1773LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1774 BasicBlock *BBTo, Instruction *CxtI) {
1775 // If already a constant, there is nothing to compute.
1776 if (Constant *VC = dyn_cast<Constant>(Val))
1777 return ValueLatticeElement::get(VC);
1778
1779 std::optional<ValueLatticeElement> LocalResult =
1780 getEdgeValueLocal(Val, BBFrom, BBTo, /*UseBlockValue*/ true);
1781 if (!LocalResult)
1782 return std::nullopt;
1783
1784 if (hasSingleValue(*LocalResult))
1785 // Can't get any more precise here
1786 return LocalResult;
1787
1788 std::optional<ValueLatticeElement> OptInBlock =
1789 getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1790 if (!OptInBlock)
1791 return std::nullopt;
1792 ValueLatticeElement &InBlock = *OptInBlock;
1793
1794 // We can use the context instruction (generically the ultimate instruction
1795 // the calling pass is trying to simplify) here, even though the result of
1796 // this function is generally cached when called from the solve* functions
1797 // (and that cached result might be used with queries using a different
1798 // context instruction), because when this function is called from the solve*
1799 // functions, the context instruction is not provided. When called from
1800 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1801 // but then the result is not cached.
1802 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1803
1804 return LocalResult->intersect(InBlock);
1805}
1806
1808 Instruction *CxtI) {
1809 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1810 << BB->getName() << "'\n");
1811
1812 assert(BlockValueStack.empty() && BlockValueSet.empty());
1813 std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1814 if (!OptResult) {
1815 solve();
1816 OptResult = getBlockValue(V, BB, CxtI);
1817 assert(OptResult && "Value not available after solving");
1818 }
1819
1820 LLVM_DEBUG(dbgs() << " Result = " << *OptResult << "\n");
1821 return *OptResult;
1822}
1823
1825 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
1826 << "'\n");
1827
1828 if (auto *C = dyn_cast<Constant>(V))
1830
1832 if (auto *I = dyn_cast<Instruction>(V))
1833 Result = getFromRangeMetadata(I);
1834 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1835
1836 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
1837 return Result;
1838}
1839
1841getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1842 Instruction *CxtI) {
1843 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1844 << FromBB->getName() << "' to '" << ToBB->getName()
1845 << "'\n");
1846
1847 std::optional<ValueLatticeElement> Result =
1848 getEdgeValue(V, FromBB, ToBB, CxtI);
1849 while (!Result) {
1850 // As the worklist only explicitly tracks block values (but not edge values)
1851 // we may have to call solve() multiple times, as the edge value calculation
1852 // may request additional block values.
1853 solve();
1854 Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1855 }
1856
1857 LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n");
1858 return *Result;
1859}
1860
1862 Value *V = U.get();
1863 auto *CxtI = cast<Instruction>(U.getUser());
1864 ValueLatticeElement VL = getValueInBlock(V, CxtI->getParent(), CxtI);
1865
1866 // Check whether the only (possibly transitive) use of the value is in a
1867 // position where V can be constrained by a select or branch condition.
1868 const Use *CurrU = &U;
1869 // TODO: Increase limit?
1870 const unsigned MaxUsesToInspect = 3;
1871 for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
1872 std::optional<ValueLatticeElement> CondVal;
1873 auto *CurrI = cast<Instruction>(CurrU->getUser());
1874 if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
1875 // If the value is undef, a different value may be chosen in
1876 // the select condition and at use.
1877 if (!isGuaranteedNotToBeUndef(SI->getCondition(), AC))
1878 break;
1879 if (CurrU->getOperandNo() == 1)
1880 CondVal =
1881 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ true,
1882 /*UseBlockValue*/ false);
1883 else if (CurrU->getOperandNo() == 2)
1884 CondVal =
1885 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ false,
1886 /*UseBlockValue*/ false);
1887 } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
1888 // TODO: Use non-local query?
1889 CondVal = *getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU),
1890 PHI->getParent(), /*UseBlockValue*/ false);
1891 }
1892 if (CondVal)
1893 VL = VL.intersect(*CondVal);
1894
1895 // Only follow one-use chain, to allow direct intersection of conditions.
1896 // If there are multiple uses, we would have to intersect with the union of
1897 // all conditions at different uses.
1898 // Stop walking if we hit a non-speculatable instruction. Even if the
1899 // result is only used under a specific condition, executing the
1900 // instruction itself may cause side effects or UB already.
1901 // This also disallows looking through phi nodes: If the phi node is part
1902 // of a cycle, we might end up reasoning about values from different cycle
1903 // iterations (PR60629).
1904 if (!CurrI->hasOneUse() ||
1906 CurrI, /*IgnoreUBImplyingAttrs=*/false))
1907 break;
1908 CurrU = &*CurrI->use_begin();
1909 }
1910 return VL;
1911}
1912
1914 BasicBlock *NewSucc) {
1915 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1916}
1917
1918//===----------------------------------------------------------------------===//
1919// LazyValueInfo Impl
1920//===----------------------------------------------------------------------===//
1921
1923 Info.F = &F;
1924 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1925
1926 if (auto *Impl = Info.getImpl())
1927 Impl->clear();
1928
1929 // Fully lazy.
1930 return false;
1931}
1932
1938
1940
1941/// This lazily constructs the LazyValueInfoImpl.
1942LazyValueInfoImpl &LazyValueInfo::getOrCreateImpl() {
1943 if (!PImpl) {
1944 const DataLayout &DL = F->getDataLayout();
1946 F->getParent(), Intrinsic::experimental_guard);
1947 PImpl = new LazyValueInfoImpl(F, AC, DL, GuardDecl);
1948 }
1949 return *PImpl;
1950}
1951
1952LazyValueInfoImpl *LazyValueInfo::getImpl() { return PImpl; }
1953
1955
1957 // If the cache was allocated, free it.
1958 if (auto *Impl = getImpl()) {
1959 delete &*Impl;
1960 PImpl = nullptr;
1961 }
1962}
1963
1965 FunctionAnalysisManager::Invalidator &Inv) {
1966 // We need to invalidate if we have either failed to preserve this analyses
1967 // result directly or if any of its dependencies have been invalidated.
1968 auto PAC = PA.getChecker<LazyValueAnalysis>();
1969 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1970 return true;
1971
1972 return false;
1973}
1974
1975void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1976
1979 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1980
1981 return LazyValueInfo(&F, &AC);
1982}
1983
1984/// Returns true if we can statically tell that this value will never be a
1985/// "useful" constant. In practice, this means we've got something like an
1986/// alloca or a malloc call for which a comparison against a constant can
1987/// only be guarding dead code. Note that we are potentially giving up some
1988/// precision in dead code (a constant result) in favour of avoiding a
1989/// expensive search for a easily answered common query.
1990static bool isKnownNonConstant(Value *V) {
1991 V = V->stripPointerCasts();
1992 // The return val of alloc cannot be a Constant.
1993 if (isa<AllocaInst>(V))
1994 return true;
1995 return false;
1996}
1997
1999 // Bail out early if V is known not to be a Constant.
2000 if (isKnownNonConstant(V))
2001 return nullptr;
2002
2003 BasicBlock *BB = CxtI->getParent();
2004 ValueLatticeElement Result = getOrCreateImpl().getValueInBlock(V, BB, CxtI);
2005
2006 if (Result.isConstant())
2007 return Result.getConstant();
2008 if (Result.isConstantRange()) {
2009 const ConstantRange &CR = Result.getConstantRange();
2010 if (const APInt *SingleVal = CR.getSingleElement())
2011 return ConstantInt::get(V->getType(), *SingleVal);
2012 }
2013 return nullptr;
2014}
2015
2017 bool UndefAllowed) {
2018 BasicBlock *BB = CxtI->getParent();
2019 ValueLatticeElement Result = getOrCreateImpl().getValueInBlock(V, BB, CxtI);
2020 return Result.asConstantRange(V->getType(), UndefAllowed);
2021}
2022
2024 bool UndefAllowed) {
2025 ValueLatticeElement Result = getOrCreateImpl().getValueAtUse(U);
2026 return Result.asConstantRange(U->getType(), UndefAllowed);
2027}
2028
2029/// Determine whether the specified value is known to be a
2030/// constant on the specified edge. Return null if not.
2032 BasicBlock *ToBB,
2033 Instruction *CxtI) {
2034 ValueLatticeElement Result =
2035 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CxtI);
2036
2037 if (Result.isConstant())
2038 return Result.getConstant();
2039 if (Result.isConstantRange()) {
2040 const ConstantRange &CR = Result.getConstantRange();
2041 if (const APInt *SingleVal = CR.getSingleElement())
2042 return ConstantInt::get(V->getType(), *SingleVal);
2043 }
2044 return nullptr;
2045}
2046
2048 BasicBlock *FromBB,
2049 BasicBlock *ToBB,
2050 Instruction *CxtI) {
2051 ValueLatticeElement Result =
2052 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CxtI);
2053 // TODO: Should undef be allowed here?
2054 return Result.asConstantRange(V->getType(), /*UndefAllowed*/ true);
2055}
2056
2058 const ValueLatticeElement &Val,
2059 const DataLayout &DL) {
2060 // If we know the value is a constant, evaluate the conditional.
2061 if (Val.isConstant())
2062 return ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL);
2063
2064 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
2065 if (Val.isConstantRange()) {
2066 const ConstantRange &CR = Val.getConstantRange();
2067 ConstantRange RHS = C->toConstantRange();
2068 if (CR.icmp(Pred, RHS))
2069 return ConstantInt::getTrue(ResTy);
2070 if (CR.icmp(CmpInst::getInversePredicate(Pred), RHS))
2071 return ConstantInt::getFalse(ResTy);
2072 return nullptr;
2073 }
2074
2075 if (Val.isNotConstant()) {
2076 // If this is an equality comparison, we can try to fold it knowing that
2077 // "V != C1".
2078 if (Pred == ICmpInst::ICMP_EQ) {
2079 // !C1 == C -> false iff C1 == C.
2082 if (Res && Res->isNullValue())
2083 return ConstantInt::getFalse(ResTy);
2084 } else if (Pred == ICmpInst::ICMP_NE) {
2085 // !C1 != C -> true iff C1 == C.
2088 if (Res && Res->isNullValue())
2089 return ConstantInt::getTrue(ResTy);
2090 }
2091 return nullptr;
2092 }
2093
2094 return nullptr;
2095}
2096
2097/// Determine whether the specified value comparison with a constant is known to
2098/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
2100 Constant *C, BasicBlock *FromBB,
2101 BasicBlock *ToBB,
2102 Instruction *CxtI) {
2103 ValueLatticeElement Result =
2104 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CxtI);
2105
2106 return getPredicateResult(Pred, C, Result, FromBB->getDataLayout());
2107}
2108
2110 Constant *C, Instruction *CxtI,
2111 bool UseBlockValue) {
2112 // Is or is not NonNull are common predicates being queried. If
2113 // isKnownNonZero can tell us the result of the predicate, we can
2114 // return it quickly. But this is only a fastpath, and falling
2115 // through would still be correct.
2116 const DataLayout &DL = CxtI->getDataLayout();
2117 // NOTE: This check is meant to determine whether a pointer is semantically a
2118 // null pointer, not just whether its value equals ConstantPointerNull. If the
2119 // semantics of ConstantPointerNull change in the future, this should be
2120 // updated to use a semantic check (e.g. isKnownNonNull).
2121 if (V->getType()->isPointerTy() && C->isNullValue() &&
2122 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
2123 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
2124 if (Pred == ICmpInst::ICMP_EQ)
2125 return ConstantInt::getFalse(ResTy);
2126 else if (Pred == ICmpInst::ICMP_NE)
2127 return ConstantInt::getTrue(ResTy);
2128 }
2129
2130 auto &Impl = getOrCreateImpl();
2131 ValueLatticeElement Result =
2132 UseBlockValue ? Impl.getValueInBlock(V, CxtI->getParent(), CxtI)
2133 : Impl.getValueAt(V, CxtI);
2134 Constant *Ret = getPredicateResult(Pred, C, Result, DL);
2135 if (Ret)
2136 return Ret;
2137
2138 // Note: The following bit of code is somewhat distinct from the rest of LVI;
2139 // LVI as a whole tries to compute a lattice value which is conservatively
2140 // correct at a given location. In this case, we have a predicate which we
2141 // weren't able to prove about the merged result, and we're pushing that
2142 // predicate back along each incoming edge to see if we can prove it
2143 // separately for each input. As a motivating example, consider:
2144 // bb1:
2145 // %v1 = ... ; constantrange<1, 5>
2146 // br label %merge
2147 // bb2:
2148 // %v2 = ... ; constantrange<10, 20>
2149 // br label %merge
2150 // merge:
2151 // %phi = phi [%v1, %v2] ; constantrange<1,20>
2152 // %pred = icmp eq i32 %phi, 8
2153 // We can't tell from the lattice value for '%phi' that '%pred' is false
2154 // along each path, but by checking the predicate over each input separately,
2155 // we can.
2156 // We limit the search to one step backwards from the current BB and value.
2157 // We could consider extending this to search further backwards through the
2158 // CFG and/or value graph, but there are non-obvious compile time vs quality
2159 // tradeoffs.
2160 BasicBlock *BB = CxtI->getParent();
2161
2162 // Function entry or an unreachable block. Bail to avoid confusing
2163 // analysis below.
2164 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2165 if (PI == PE)
2166 return nullptr;
2167
2168 // If V is a PHI node in the same block as the context, we need to ask
2169 // questions about the predicate as applied to the incoming value along
2170 // each edge. This is useful for eliminating cases where the predicate is
2171 // known along all incoming edges.
2172 if (auto *PHI = dyn_cast<PHINode>(V))
2173 if (PHI->getParent() == BB) {
2174 Constant *Baseline = nullptr;
2175 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
2176 Value *Incoming = PHI->getIncomingValue(i);
2177 BasicBlock *PredBB = PHI->getIncomingBlock(i);
2178 // Note that PredBB may be BB itself.
2179 Constant *Result =
2180 getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
2181
2182 // Keep going as long as we've seen a consistent known result for
2183 // all inputs.
2184 Baseline = (i == 0) ? Result /* First iteration */
2185 : (Baseline == Result ? Baseline
2186 : nullptr); /* All others */
2187 if (!Baseline)
2188 break;
2189 }
2190 if (Baseline)
2191 return Baseline;
2192 }
2193
2194 // For a comparison where the V is outside this block, it's possible
2195 // that we've branched on it before. Look to see if the value is known
2196 // on all incoming edges.
2197 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
2198 // For predecessor edge, determine if the comparison is true or false
2199 // on that edge. If they're all true or all false, we can conclude
2200 // the value of the comparison in this block.
2201 Constant *Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
2202 if (Baseline) {
2203 // Check that all remaining incoming values match the first one.
2204 while (++PI != PE) {
2205 Constant *Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
2206 if (Ret != Baseline)
2207 break;
2208 }
2209 // If we terminated early, then one of the values didn't match.
2210 if (PI == PE) {
2211 return Baseline;
2212 }
2213 }
2214 }
2215
2216 return nullptr;
2217}
2218
2220 Value *RHS, Instruction *CxtI,
2221 bool UseBlockValue) {
2222 if (auto *C = dyn_cast<Constant>(RHS))
2223 return getPredicateAt(Pred, LHS, C, CxtI, UseBlockValue);
2224 if (auto *C = dyn_cast<Constant>(LHS))
2225 return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
2226 UseBlockValue);
2227
2228 // Got two non-Constant values. Try to determine the comparison results based
2229 // on the block values of the two operands, e.g. because they have
2230 // non-overlapping ranges.
2231 if (UseBlockValue) {
2233 getOrCreateImpl().getValueInBlock(LHS, CxtI->getParent(), CxtI);
2234 if (L.isOverdefined())
2235 return nullptr;
2236
2238 getOrCreateImpl().getValueInBlock(RHS, CxtI->getParent(), CxtI);
2239 Type *Ty = CmpInst::makeCmpResultType(LHS->getType());
2240 return L.getCompare(Pred, Ty, R, CxtI->getDataLayout());
2241 }
2242 return nullptr;
2243}
2244
2246 BasicBlock *NewSucc) {
2247 if (auto *Impl = getImpl())
2248 Impl->threadEdge(PredBB, OldSucc, NewSucc);
2249}
2250
2252 if (auto *Impl = getImpl())
2253 Impl->forgetValue(V);
2254}
2255
2257 if (auto *Impl = getImpl())
2258 Impl->eraseBlock(BB);
2259}
2260
2262 if (auto *Impl = getImpl())
2263 Impl->clear();
2264}
2265
2267 if (auto *Impl = getImpl())
2268 Impl->printLVI(F, DTree, OS);
2269}
2270
2271// Print the LVI for the function arguments at the start of each basic block.
2272void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2273 const BasicBlock *BB, formatted_raw_ostream &OS) {
2274 // Find if there are latticevalues defined for arguments of the function.
2275 auto *F = BB->getParent();
2276 for (const auto &Arg : F->args()) {
2277 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2278 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2279 if (Result.isUnknown())
2280 continue;
2281 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
2282 }
2283}
2284
2285// This function prints the LVI analysis for the instruction I at the beginning
2286// of various basic blocks. It relies on calculated values that are stored in
2287// the LazyValueInfoCache, and in the absence of cached values, recalculate the
2288// LazyValueInfo for `I`, and print that info.
2289void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2290 const Instruction *I, formatted_raw_ostream &OS) {
2291
2292 auto *ParentBB = I->getParent();
2293 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2294 // We can generate (solve) LVI values only for blocks that are dominated by
2295 // the I's parent. However, to avoid generating LVI for all dominating blocks,
2296 // that contain redundant/uninteresting information, we print LVI for
2297 // blocks that may use this LVI information (such as immediate successor
2298 // blocks, and blocks that contain uses of `I`).
2299 auto printResult = [&](const BasicBlock *BB) {
2300 if (!BlocksContainingLVI.insert(BB).second)
2301 return;
2302 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2303 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2304 OS << "; LatticeVal for: '" << *I << "' in BB: '";
2305 BB->printAsOperand(OS, false);
2306 OS << "' is: " << Result << "\n";
2307 };
2308
2309 printResult(ParentBB);
2310 // Print the LVI analysis results for the immediate successor blocks, that
2311 // are dominated by `ParentBB`.
2312 for (const auto *BBSucc : successors(ParentBB))
2313 if (DT.dominates(ParentBB, BBSucc))
2314 printResult(BBSucc);
2315
2316 // Print LVI in blocks where `I` is used.
2317 for (const auto *U : I->users())
2318 if (auto *UseI = dyn_cast<Instruction>(U))
2319 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2320 printResult(UseI->getParent());
2321
2322}
2323
2326 OS << "LVI for function '" << F.getName() << "':\n";
2327 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
2328 auto &DTree = AM.getResult<DominatorTreeAnalysis>(F);
2329 LVI.printLVI(F, DTree, OS);
2330 return PreservedAnalyses::all();
2331}
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:853
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
#define _
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 Value * getOpcode(Value &V, Type &Ty, InstrumentationConfig &IConf, InstrumentorIRBuilderTy &IIRB)
static bool isOperationFoldable(User *Usr)
static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet, bool IsDereferenced=true)
static void AddNonNullPointersByInstruction(Instruction *I, NonNullPointerSet &PtrSet)
static std::optional< ConstantRange > getRangeViaSLT(CmpInst::Predicate Pred, APInt RHS, function_ref< std::optional< ConstantRange >(const APInt &)> Fn)
static const unsigned MaxProcessedPerValue
static ValueLatticeElement getValueFromICmpCtpop(ICmpInst::Predicate Pred, Value *RHS)
Get value range for a "ctpop(Val) Pred RHS" condition.
static bool usesOperand(User *Usr, Value *Op)
static ValueLatticeElement constantFoldUser(User *Usr, Value *Op, const APInt &OpConstVal, const DataLayout &DL)
static ValueLatticeElement getFromRangeMetadata(Instruction *BBI)
lazy value Lazy Value Information static true cl::opt< bool > PerPredRanges("lvi-per-pred-ranges", cl::Hidden, cl::init(false), cl::desc("Enable tracking of ranges for a value in a block for" "each block predecessor (default = false)"))
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
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
const SmallVectorImpl< MachineOperand > & 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:1055
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
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:476
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
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:461
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:479
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 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 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.
LLVM_ABI ConstantRange overflowingBinaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind) const
Return a new range representing the possible values resulting from an application of the specified ov...
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
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:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
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:64
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:289
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
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:314
FunctionPass(char &pid)
Definition Pass.h:316
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:828
unsigned getBlockNumberEpoch() const
Return the "epoch" of current block numbers.
Definition Function.h:842
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.
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 *CxtI=nullptr)
This is the query interface to determine the lattice value for the specified Value* that is true on t...
ValueLatticeElement getValueAt(Value *V, Instruction *CxtI)
This is the query interface to determine the lattice value for the specified Value* at the specified ...
void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
This is the update interface to inform the cache that an edge from PredBB to OldSucc has been threade...
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Printing the LazyValueInfo Analysis.
void forgetValue(Value *V)
This is part of the update interface to remove information related to this value from the cache.
void eraseBlock(BasicBlock *BB)
This is part of the update interface to inform the cache that a block has been deleted.
void clear()
Complete flush all previously computed values.
ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
This is the query interface to determine the lattice value for the specified Value* at the context in...
ValueLatticeElement getValueAtUse(const Use &U)
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 ConstantRange getConstantRange(Value *V, Instruction *CxtI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
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 Constant * getPredicateOnEdge(CmpInst::Predicate Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
LLVM_ABI void releaseMemory()
LLVM_ABI Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
LLVM_ABI ConstantRange getConstantRangeOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Return the ConstantRage constraint that is known to hold for the specified value on the specified edg...
LLVM_ABI Constant * getConstant(Value *V, Instruction *CxtI)
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 void forgetValue(Value *V)
Remove information related to this value from the cache.
LLVM_ABI void clear()
Complete flush all previously computed values.
LLVM_ABI Constant * getPredicateAt(CmpInst::Predicate Pred, Value *V, Constant *C, Instruction *CxtI, bool UseBlockValue)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1069
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:301
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:263
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
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:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:823
use_iterator use_begin()
Definition Value.h:364
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
iterator find_as(const LookupKeyT &Val)
Alternative version of find() which allows a different, and possibly less expensive,...
Definition DenseSet.h:200
bool erase(const ValueT &V)
Definition DenseSet.h:100
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h: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
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
m_Intrinsic_Ty< Opnd0 >::Ty m_Ctpop(const Opnd0 &Op0)
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)
This namespace contains all of the command line option processing machinery.
Definition MCSchedule.h:35
constexpr double e
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
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:2207
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
LLVM_ABI FunctionPass * createLazyValueInfoPass()
createLazyValueInfoPass - This creates an instance of the LazyValueInfo pass.
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 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
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...
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 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.
LLVM_ABI AssumeNonNullInfo getAssumeNonNullInfo(OperandBundleUse)
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)
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:1946
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI AssumeDereferenceableInfo getAssumeDereferenceableInfo(OperandBundleUse)
#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?