LLVM 24.0.0git
Loads.cpp
Go to the documentation of this file.
1//===- Loads.cpp - Local load analysis ------------------------------------===//
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 simple local analyses for load instructions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Analysis/Loads.h"
23#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Operator.h"
27
28using namespace llvm;
29
30static bool isAligned(const Value *Base, Align Alignment,
31 const DataLayout &DL) {
32 return Base->getPointerAlignment(DL) >= Alignment;
33}
34
36 const Value *Ptr, Align Alignment, const SimplifyQuery &SQ, bool IgnoreFree,
37 function_ref<bool(const RetainedKnowledge &RK)> CheckSize) {
38 if (!SQ.CtxI)
39 return false;
40 // Look through assumes to see if both dereferenceability and alignment can
41 // be proven by an assume if needed.
42 bool PtrCanBeFreed = Ptr->canBeFreed() && !IgnoreFree;
43 bool IsAligned = Ptr->getPointerAlignment(SQ.DL) >= Alignment;
44 bool IsDerefable = false;
46 Ptr, {Attribute::Dereferenceable, Attribute::Alignment}, *SQ.AC,
47 [&](RetainedKnowledge RK, Instruction *Assume, auto) {
48 if (!isValidAssumeForContext(Assume, SQ.CtxI, SQ.DT))
49 return false;
50 if (RK.AttrKind == Attribute::Alignment) {
51 IsAligned |= RK.ArgValue >= Alignment.value();
52 } else {
53 assert(RK.AttrKind == Attribute::Dereferenceable);
54 // Dereferenceable information from assumptions is only valid if the
55 // value cannot be freed between the assumption and use.
56 if (!IsDerefable &&
57 (!PtrCanBeFreed || willNotFreeBetween(Assume, SQ.CtxI, SQ.DT)) &&
58 CheckSize(RK))
59 IsDerefable = true;
60 }
61 // Stop looking if we have proven both necessary facts.
62 return IsAligned && IsDerefable;
63 });
64}
65
66/// Test if V is always a pointer to allocated and suitably aligned memory for
67/// a simple load or store.
69 const Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ,
70 bool IgnoreFree, SmallPtrSetImpl<const Value *> &Visited,
71 unsigned MaxDepth) {
72 assert(V->getType()->isPointerTy() && "Base must be pointer");
73
74 // Recursion limit.
75 if (MaxDepth-- == 0)
76 return false;
77
78 // Already visited? Bail out, we've likely hit unreachable code.
79 if (!Visited.insert(V).second)
80 return false;
81
82 // Note that it is not safe to speculate into a malloc'd region because
83 // malloc may return null.
84
85 // For GEPs, determine if the indexing lands within the allocated object.
86 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
87 const Value *Base = GEP->getPointerOperand();
88
89 APInt Offset(SQ.DL.getIndexTypeSizeInBits(GEP->getType()), 0);
90 if (!GEP->accumulateConstantOffset(SQ.DL, Offset) || Offset.isNegative() ||
91 !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
92 .isMinValue())
93 return false;
94
95 // If the base pointer is dereferenceable for Offset+Size bytes, then the
96 // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base
97 // pointer is aligned to Align bytes, and the Offset is divisible by Align
98 // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
99 // aligned to Align bytes.
100
101 // Offset and Size may have different bit widths if we have visited an
102 // addrspacecast, so we can't do arithmetic directly on the APInt values.
104 Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), SQ,
105 IgnoreFree, Visited, MaxDepth);
106 }
107
108 // bitcast instructions are no-ops as far as dereferenceability is concerned.
109 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
110 if (BC->getSrcTy()->isPointerTy())
111 return isDereferenceableAndAlignedPointer(BC->getOperand(0), Alignment,
112 Size, SQ, IgnoreFree, Visited,
113 MaxDepth);
114 }
115
116 // Recurse into both hands of select.
117 if (const SelectInst *Sel = dyn_cast<SelectInst>(V)) {
118 return isDereferenceableAndAlignedPointer(Sel->getTrueValue(), Alignment,
119 Size, SQ, IgnoreFree, Visited,
120 MaxDepth) &&
121 isDereferenceableAndAlignedPointer(Sel->getFalseValue(), Alignment,
122 Size, SQ, IgnoreFree, Visited,
123 MaxDepth);
124 }
125
126 auto IsKnownDeref = [&]() {
127 bool CheckForNonNull, CheckForFreed;
128 if (!Size.ule(V->getPointerDereferenceableBytes(SQ.DL, CheckForNonNull,
129 &CheckForFreed)))
130 return false;
131 if (CheckForNonNull && !isKnownNonZero(V, SQ))
132 return false;
133
134 auto *I = dyn_cast<Instruction>(V);
135 if (CheckForFreed && !IgnoreFree) {
136 const Instruction *DefI;
137 if (I) {
138 // We don't want to consider frees by the instruction producing the
139 // pointer, so skip it if we can.
140 if (auto *II = dyn_cast<InvokeInst>(V)) {
141 DefI = &II->getNormalDest()->front();
142 } else if (!I->isTerminator()) {
143 DefI = I->getNextNode();
144 } else {
145 DefI = I;
146 }
147 } else {
148 // For arguments, check frees from the start of the entry block.
149 DefI = &cast<Argument>(V)->getParent()->getEntryBlock().front();
150 }
151
152 if (!SQ.CtxI || !willNotFreeBetween(DefI, SQ.CtxI, SQ.DT))
153 return false;
154 }
155
156 // When using something like !dereferenceable on a load, the
157 // dereferenceability may only be valid on a specific control-flow path.
158 // If the instruction doesn't dominate the context instruction, we're
159 // asking about dereferenceability under the assumption that the
160 // instruction has been speculated to the point of the context instruction,
161 // in which case we don't know if the dereferenceability info still holds.
162 // We don't bother handling allocas here, as they aren't speculatable
163 // anyway.
164 if (I && !isa<AllocaInst>(I))
165 return SQ.CtxI && isValidAssumeForContext(I, SQ.CtxI, SQ.DT);
166 return true;
167 };
168 if (IsKnownDeref()) {
169 // As we recursed through GEPs to get here, we've incrementally checked
170 // that each step advanced by a multiple of the alignment. If our base is
171 // properly aligned, then the original offset accessed must also be.
172 return isAligned(V, Alignment, SQ.DL);
173 }
174
175 /// TODO refactor this function to be able to search independently for
176 /// Dereferencability and Alignment requirements.
177
178
179 if (const auto *Call = dyn_cast<CallBase>(V)) {
181 Call, /*MustPreserveOffset=*/true))
182 return isDereferenceableAndAlignedPointer(RP, Alignment, Size, SQ,
183 IgnoreFree, Visited, MaxDepth);
184
185 // If we have a call we can't recurse through, check to see if this is an
186 // allocation function for which we can establish an minimum object size.
187 // Such a minimum object size is analogous to a deref_or_null attribute in
188 // that we still need to prove the result non-null at point of use.
189 // NOTE: We can only use the object size as a base fact as we a) need to
190 // prove alignment too, and b) don't want the compile time impact of a
191 // separate recursive walk.
192 ObjectSizeOpts Opts;
193 // TODO: It may be okay to round to align, but that would imply that
194 // accessing slightly out of bounds was legal, and we're currently
195 // inconsistent about that. For the moment, be conservative.
196 Opts.RoundToAlign = false;
197 Opts.NullIsUnknownSize = true;
198 uint64_t ObjSize;
199 if (getObjectSize(V, ObjSize, SQ.DL, SQ.TLI, Opts)) {
200 APInt KnownDerefBytes(Size.getBitWidth(), ObjSize);
201 if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
202 isKnownNonZero(V, SQ) && !V->canBeFreed()) {
203 // As we recursed through GEPs to get here, we've incrementally
204 // checked that each step advanced by a multiple of the alignment. If
205 // our base is properly aligned, then the original offset accessed
206 // must also be.
207 return isAligned(V, Alignment, SQ.DL);
208 }
209 }
210 }
211
212 // For gc.relocate, look through relocations
213 if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
214 return isDereferenceableAndAlignedPointer(RelocateInst->getDerivedPtr(),
215 Alignment, Size, SQ, IgnoreFree,
216 Visited, MaxDepth);
217
220 ASC->getOperand(0), Alignment, Size, SQ, IgnoreFree, Visited, MaxDepth);
221
222 return SQ.AC &&
224 V, Alignment, SQ, IgnoreFree, [Size](const RetainedKnowledge &RK) {
225 return RK.ArgValue >= Size.getZExtValue();
226 });
227}
228
230 const APInt &Size,
231 const SimplifyQuery &SQ,
232 bool IgnoreFree) {
233 // Note: At the moment, Size can be zero. This ends up being interpreted as
234 // a query of whether [Base, V] is dereferenceable and V is aligned (since
235 // that's what the implementation happened to do). It's unclear if this is
236 // the desired semantic, but at least SelectionDAG does exercise this case.
237
239 return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, SQ,
240 IgnoreFree, Visited,
241 /*MaxDepth=*/16);
242}
243
245 Align Alignment,
246 const SimplifyQuery &SQ,
247 bool IgnoreFree) {
248 // For unsized types or scalable vectors we don't know exactly how many bytes
249 // are dereferenced, so bail out.
250 if (!Ty->isSized() || Ty->isScalableTy())
251 return false;
252
253 // When dereferenceability information is provided by a dereferenceable
254 // attribute, we know exactly how many bytes are dereferenceable. If we can
255 // determine the exact offset to the attributed variable, we can use that
256 // information here.
257
258 APInt AccessSize(SQ.DL.getPointerTypeSizeInBits(V->getType()),
259 SQ.DL.getTypeStoreSize(Ty));
260 return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, SQ,
261 IgnoreFree);
262}
263
265 const SimplifyQuery &SQ, bool IgnoreFree) {
266 return isDereferenceableAndAlignedPointer(V, Ty, Align(1), SQ, IgnoreFree);
267}
268
270 const SimplifyQuery &Q, bool IgnoreFree) {
271 return isDereferenceableAndAlignedPointer(V, Align(1), Size, Q, IgnoreFree);
272}
273
274/// Test if A and B will obviously have the same value.
275///
276/// This includes recognizing that %t0 and %t1 will have the same
277/// value in code like this:
278/// \code
279/// %t0 = getelementptr \@a, 0, 3
280/// store i32 0, i32* %t0
281/// %t1 = getelementptr \@a, 0, 3
282/// %t2 = load i32* %t1
283/// \endcode
284///
285static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
286 // Test if the values are trivially equivalent.
287 if (A == B)
288 return true;
289
290 // Test if the values come from identical arithmetic instructions.
291 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
292 // this function is only used when one address use dominates the
293 // other, which means that they'll always either have the same
294 // value or one of them will have an undefined value.
296 if (const Instruction *BI = dyn_cast<Instruction>(B))
297 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
298 return true;
299
300 // Otherwise they may not be equivalent.
301 return false;
302}
303
305 LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT,
307 auto &DL = LI->getDataLayout();
308 Value *Ptr = LI->getPointerOperand();
309 const SCEV *PtrSCEV = SE.getSCEV(Ptr);
310 APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
311 DL.getTypeStoreSize(LI->getType()).getFixedValue());
312
313 // If given a uniform (i.e. non-varying) address, see if we can prove the
314 // access is safe within the loop w/o needing predication.
315 if (L->isLoopInvariant(Ptr))
317 Ptr, LI->getAlign(), EltSize,
318 SimplifyQuery(DL, &DT, AC, &*L->getHeader()->getFirstNonPHIIt()));
319
320 const SCEV *EltSizeSCEV = SE.getConstant(EltSize);
321 return isDereferenceableAndAlignedInLoop(PtrSCEV, LI->getAlign(), EltSizeSCEV,
322 L, SE, DT, AC, Predicates);
323}
324
326 const SCEV *PtrSCEV, Align Alignment, const SCEV *EltSizeSCEV, Loop *L,
329 auto *AddRec = dyn_cast<SCEVAddRecExpr>(PtrSCEV);
330
331 // Check to see if we have a repeating access pattern and it's possible
332 // to prove all accesses are well aligned.
333 if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
334 return false;
335
336 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
337 if (!Step)
338 return false;
339
340 const APInt &EltSize = cast<SCEVConstant>(EltSizeSCEV)->getAPInt();
341 // For the moment, restrict ourselves to the case where the access size is a
342 // multiple of the requested alignment and the base is aligned.
343 // TODO: generalize if a case found which warrants
344 if (EltSize.urem(Alignment.value()) != 0)
345 return false;
346
347 // TODO: Handle overlapping accesses.
348 if (EltSize.ugt(Step->getAPInt().abs()))
349 return false;
350
351 const SCEV *MaxBECount =
352 Predicates ? SE.getPredicatedSymbolicMaxBackedgeTakenCount(L, *Predicates)
354 const SCEV *BECount = Predicates
355 ? SE.getPredicatedBackedgeTakenCount(L, *Predicates)
356 : SE.getBackedgeTakenCount(L);
357 if (isa<SCEVCouldNotCompute>(MaxBECount))
358 return false;
359 std::optional<ScalarEvolution::LoopGuards> LoopGuards;
360
361 auto &DL = L->getHeader()->getDataLayout();
362 const auto &[AccessStart, AccessEnd] =
363 getStartAndEndForAccess(L, PtrSCEV, EltSizeSCEV, BECount, MaxBECount, &SE,
364 nullptr, &DT, AC, LoopGuards);
365 if (isa<SCEVCouldNotCompute>(AccessStart) ||
366 isa<SCEVCouldNotCompute>(AccessEnd))
367 return false;
368
369 // Try to get the access size.
370 const SCEV *PtrDiff = SE.getMinusSCEV(AccessEnd, AccessStart);
371 if (isa<SCEVCouldNotCompute>(PtrDiff))
372 return false;
373
374 if (!LoopGuards)
375 LoopGuards.emplace(
376 ScalarEvolution::LoopGuards::collect(AddRec->getLoop(), SE));
377
378 APInt MaxPtrDiff =
379 SE.getUnsignedRangeMax(SE.applyLoopGuards(PtrDiff, *LoopGuards));
380
381 Value *Base = nullptr;
382 APInt AccessSize;
383 const SCEV *AccessSizeSCEV = nullptr;
384 if (const SCEVUnknown *NewBase = dyn_cast<SCEVUnknown>(AccessStart)) {
385 Base = NewBase->getValue();
386 AccessSize = std::move(MaxPtrDiff);
387 AccessSizeSCEV = PtrDiff;
388 } else if (auto *MinAdd = dyn_cast<SCEVAddExpr>(AccessStart)) {
389 if (MinAdd->getNumOperands() != 2)
390 return false;
391
392 const auto *Offset = dyn_cast<SCEVConstant>(MinAdd->getOperand(0));
393 const auto *NewBase = dyn_cast<SCEVUnknown>(MinAdd->getOperand(1));
394 if (!Offset || !NewBase)
395 return false;
396
397 // The following code below assumes the offset is unsigned, but GEP
398 // offsets are treated as signed so we can end up with a signed value
399 // here too. For example, suppose the initial PHI value is (i8 255),
400 // the offset will be treated as (i8 -1) and sign-extended to (i64 -1).
401 if (Offset->getAPInt().isNegative())
402 return false;
403
404 // For the moment, restrict ourselves to the case where the offset is a
405 // multiple of the requested alignment and the base is aligned.
406 // TODO: generalize if a case found which warrants
407 if (Offset->getAPInt().urem(Alignment.value()) != 0)
408 return false;
409
410 bool Overflow = false;
411 AccessSize = MaxPtrDiff.uadd_ov(Offset->getAPInt(), Overflow);
412 if (Overflow)
413 return false;
414 AccessSizeSCEV = SE.getAddExpr(PtrDiff, Offset);
415 Base = NewBase->getValue();
416 } else
417 return false;
418
419 Instruction *CtxI = &*L->getHeader()->getFirstNonPHIIt();
420 if (BasicBlock *LoopPred = L->getLoopPredecessor()) {
421 if (isa<UncondBrInst, CondBrInst>(LoopPred->getTerminator()))
422 CtxI = LoopPred->getTerminator();
423 }
424 SimplifyQuery SQ(DL, &DT, AC, CtxI);
426 Base, Alignment, SQ, /*IgnoreFree=*/false,
427 [&SE, AccessSizeSCEV, &LoopGuards](const RetainedKnowledge &RK) {
428 const SCEV *DerefBytesSCEV = SE.getSCEV(RK.IRArgValue);
429 Type *WiderTy = SE.getWiderType(AccessSizeSCEV->getType(),
430 DerefBytesSCEV->getType());
431 const SCEV *AccessSizeExt =
432 SE.getNoopOrZeroExtend(AccessSizeSCEV, WiderTy);
433 const SCEV *DerefBytesExt =
434 SE.getNoopOrZeroExtend(DerefBytesSCEV, WiderTy);
435 return SE.isKnownPredicate(
437 SE.applyLoopGuards(AccessSizeExt, *LoopGuards),
438 SE.applyLoopGuards(DerefBytesExt, *LoopGuards));
439 }) ||
440 isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, SQ);
441}
442
444 const Function &F = *CtxI.getFunction();
445 // Speculative load may create a race that did not exist in the source.
446 return F.hasFnAttribute(Attribute::SanitizeThread) ||
447 // Speculative load may load data from dirty regions.
448 F.hasFnAttribute(Attribute::SanitizeAddress) ||
449 F.hasFnAttribute(Attribute::SanitizeHWAddress);
450}
451
455
457 const APInt &Size,
458 const SimplifyQuery &SQ,
459 bool IgnoreFree) {
460 if (isDereferenceableAndAlignedPointer(V, Alignment, Size, SQ, IgnoreFree)) {
461 // With sanitizers `Dereferenceable` is not always enough for unconditional
462 // load.
464 return true;
465 }
466
467 if (!SQ.CtxI)
468 return false;
469
470 if (Size.getBitWidth() > 64)
471 return false;
472 const TypeSize LoadSize = TypeSize::getFixed(Size.getZExtValue());
473
474 // Otherwise, be a little bit aggressive by scanning the local block where we
475 // want to check to see if the pointer is already being loaded or stored
476 // from/to. If so, the previous load or store would have already trapped,
477 // so there is no harm doing an extra load (also, CSE will later eliminate
478 // the load entirely).
479 auto BBI = SQ.CtxI->getIterator(), E = SQ.CtxI->getParent()->begin();
480
481 // We can at least always strip pointer casts even though we can't use the
482 // base here.
483 V = V->stripPointerCasts();
484
485 while (BBI != E) {
486 --BBI;
487
488 // If we see a free or a call which may write to memory (i.e. which might do
489 // a free) the pointer could be marked invalid.
490 if (!IgnoreFree && isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
492 return false;
493
494 const Value *AccessedPtr;
495 Type *AccessedTy;
496 Align AccessedAlign;
497 if (const auto *LI = dyn_cast<LoadInst>(BBI)) {
498 // Ignore volatile loads. The execution of a volatile load cannot
499 // be used to prove an address is backed by regular memory; it can,
500 // for example, point to an MMIO register.
501 if (LI->isVolatile())
502 continue;
503 AccessedPtr = LI->getPointerOperand();
504 AccessedTy = LI->getType();
505 AccessedAlign = LI->getAlign();
506 } else if (const auto *SI = dyn_cast<StoreInst>(BBI)) {
507 // Ignore volatile stores (see comment for loads).
508 if (SI->isVolatile())
509 continue;
510 AccessedPtr = SI->getPointerOperand();
511 AccessedTy = SI->getValueOperand()->getType();
512 AccessedAlign = SI->getAlign();
513 } else
514 continue;
515
516 if (AccessedAlign < Alignment)
517 continue;
518
519 // Handle trivial cases.
520 if (AccessedPtr == V &&
521 TypeSize::isKnownLE(LoadSize, SQ.DL.getTypeStoreSize(AccessedTy)))
522 return true;
523
524 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
525 TypeSize::isKnownLE(LoadSize, SQ.DL.getTypeStoreSize(AccessedTy)))
526 return true;
527 }
528 return false;
529}
530
532 const SimplifyQuery &SQ,
533 bool IgnoreFree) {
534 TypeSize TySize = SQ.DL.getTypeStoreSize(Ty);
535 if (TySize.isScalable())
536 return false;
537 APInt Size(SQ.DL.getIndexTypeSizeInBits(V->getType()),
538 TySize.getFixedValue());
539 return isSafeToLoadUnconditionally(V, Alignment, Size, SQ, IgnoreFree);
540}
541
542/// DefMaxInstsToScan - the default number of maximum instructions
543/// to scan in the block, used by FindAvailableLoadedValue().
544/// FindAvailableLoadedValue() was introduced in r60148, to improve jump
545/// threading in part by eliminating partially redundant loads.
546/// At that point, the value of MaxInstsToScan was already set to '6'
547/// without documented explanation.
549llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
550 cl::desc("Use this to specify the default maximum number of instructions "
551 "to scan backward from a given instruction, when searching for "
552 "available loaded value"));
553
555 BasicBlock::iterator &ScanFrom,
556 unsigned MaxInstsToScan,
557 BatchAAResults *AA, bool *IsLoad,
558 unsigned *NumScanedInst) {
559 // Don't CSE load that is volatile or anything stronger than unordered.
560 if (!Load->isUnordered())
561 return nullptr;
562
564 return findAvailablePtrLoadStore(Loc, Load->getType(), Load->getProperties(),
565 ScanBB, ScanFrom, MaxInstsToScan, AA, IsLoad,
566 NumScanedInst);
567}
568
569// Check if the load and the store have the same base, constant offsets and
570// non-overlapping access ranges.
571static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr,
572 Type *LoadTy,
573 const Value *StorePtr,
574 Type *StoreTy,
575 const DataLayout &DL) {
576 APInt LoadOffset(DL.getIndexTypeSizeInBits(LoadPtr->getType()), 0);
577 APInt StoreOffset(DL.getIndexTypeSizeInBits(StorePtr->getType()), 0);
578 if (LoadOffset.getBitWidth() != StoreOffset.getBitWidth())
579 return false;
580 const Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets(
581 DL, LoadOffset, /* AllowNonInbounds */ false);
582 const Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets(
583 DL, StoreOffset, /* AllowNonInbounds */ false);
584 if (LoadBase != StoreBase)
585 return false;
586 auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy));
587 auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy));
588 ConstantRange LoadRange(LoadOffset,
589 LoadOffset + LoadAccessSize.toRaw());
590 ConstantRange StoreRange(StoreOffset,
591 StoreOffset + StoreAccessSize.toRaw());
592 return LoadRange.intersectWith(StoreRange).isEmptySet();
593}
594
595// For elementwise atomics, each vector element is a separate atomic access.
596// Reusing an operation with a different access size would change atomicity.
598 Type *AccessTy, const LoadStoreInstProperties &AccessProps,
599 Type *OtherAccessTy, const LoadStoreInstProperties &OtherProps,
600 const DataLayout &DL) {
601 if (AccessProps.Ordering == AtomicOrdering::NotAtomic)
602 return true;
603
604 Type *AtomicAccessTy =
605 AccessProps.IsElementwise ? AccessTy->getScalarType() : AccessTy;
606 Type *OtherAtomicAccessTy =
607 OtherProps.IsElementwise ? OtherAccessTy->getScalarType() : OtherAccessTy;
608 return DL.getTypeStoreSize(AtomicAccessTy) ==
609 DL.getTypeStoreSize(OtherAtomicAccessTy);
610}
611
613 Type *AccessTy,
614 const LoadStoreInstProperties &AccessProps,
615 const DataLayout &DL, bool *IsLoadCSE) {
616 const bool AtLeastAtomic = AccessProps.Ordering != AtomicOrdering::NotAtomic;
617
618 // If this is a load of Ptr, the loaded value is available.
619 // (This is true even if the load is volatile or atomic, although
620 // those cases are unlikely.)
621 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
622 // We can value forward from an atomic to a non-atomic, but not the
623 // other way around.
624 if (LI->isAtomic() < AtLeastAtomic)
625 return nullptr;
626
627 Value *LoadPtr = LI->getPointerOperand()->stripPointerCasts();
628 if (!AreEquivalentAddressValues(LoadPtr, Ptr))
629 return nullptr;
630
631 if (hasCompatibleAtomicAccessSize(AccessTy, AccessProps, LI->getType(),
632 LI->getProperties(), DL) &&
633 CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
634 if (IsLoadCSE)
635 *IsLoadCSE = true;
636 return LI;
637 }
638 }
639
640 // If this is a store through Ptr, the value is available!
641 // (This is true even if the store is volatile or atomic, although
642 // those cases are unlikely.)
643 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
644 // We can value forward from an atomic to a non-atomic, but not the
645 // other way around.
646 if (SI->isAtomic() < AtLeastAtomic)
647 return nullptr;
648
649 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
650 if (!AreEquivalentAddressValues(StorePtr, Ptr))
651 return nullptr;
652
653 if (IsLoadCSE)
654 *IsLoadCSE = false;
655
656 Value *Val = SI->getValueOperand();
657 if (!hasCompatibleAtomicAccessSize(AccessTy, AccessProps, Val->getType(),
658 SI->getProperties(), DL))
659 return nullptr;
660
661 if (CastInst::isBitOrNoopPointerCastable(Val->getType(), AccessTy, DL))
662 return Val;
663
664 TypeSize StoreSize = DL.getTypeSizeInBits(Val->getType());
665 TypeSize LoadSize = DL.getTypeSizeInBits(AccessTy);
666 if (TypeSize::isKnownLE(LoadSize, StoreSize))
667 if (auto *C = dyn_cast<Constant>(Val))
668 return ConstantFoldLoadFromConst(C, AccessTy, DL);
669 }
670
671 if (auto *MSI = dyn_cast<MemSetInst>(Inst)) {
672 // Don't forward from (non-atomic) memset to atomic load.
673 if (AtLeastAtomic)
674 return nullptr;
675
676 // Only handle constant memsets.
677 auto *Val = dyn_cast<ConstantInt>(MSI->getValue());
678 auto *Len = dyn_cast<ConstantInt>(MSI->getLength());
679 if (!Val || !Len)
680 return nullptr;
681
682 // Handle offsets.
683 int64_t StoreOffset = 0, LoadOffset = 0;
684 const Value *StoreBase =
685 GetPointerBaseWithConstantOffset(MSI->getDest(), StoreOffset, DL);
686 const Value *LoadBase =
687 GetPointerBaseWithConstantOffset(Ptr, LoadOffset, DL);
688 if (StoreBase != LoadBase || LoadOffset < StoreOffset)
689 return nullptr;
690
691 if (IsLoadCSE)
692 *IsLoadCSE = false;
693
694 TypeSize LoadTypeSize = DL.getTypeSizeInBits(AccessTy);
695 if (LoadTypeSize.isScalable())
696 return nullptr;
697
698 // Make sure the read bytes are contained in the memset.
699 uint64_t LoadSize = LoadTypeSize.getFixedValue();
700 if ((Len->getValue() * 8).ult(LoadSize + (LoadOffset - StoreOffset) * 8))
701 return nullptr;
702
703 APInt Splat = LoadSize >= 8 ? APInt::getSplat(LoadSize, Val->getValue())
704 : Val->getValue().trunc(LoadSize);
705 ConstantInt *SplatC = ConstantInt::get(MSI->getContext(), Splat);
706 if (CastInst::isBitOrNoopPointerCastable(SplatC->getType(), AccessTy, DL))
707 return SplatC;
708
709 return nullptr;
710 }
711
712 return nullptr;
713}
714
716 const MemoryLocation &Loc, Type *AccessTy,
717 const LoadStoreInstProperties &AccessProps, BasicBlock *ScanBB,
718 BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, BatchAAResults *AA,
719 bool *IsLoadCSE, unsigned *NumScanedInst) {
720 if (MaxInstsToScan == 0)
721 MaxInstsToScan = ~0U;
722
723 const DataLayout &DL = ScanBB->getDataLayout();
724 const Value *StrippedPtr = Loc.Ptr->stripPointerCasts();
725
726 while (ScanFrom != ScanBB->begin()) {
727 // We must ignore debug info directives when counting (otherwise they
728 // would affect codegen).
729 Instruction *Inst = &*--ScanFrom;
730 if (Inst->isDebugOrPseudoInst())
731 continue;
732
733 // Restore ScanFrom to expected value in case next test succeeds
734 ScanFrom++;
735
736 if (NumScanedInst)
737 ++(*NumScanedInst);
738
739 // Don't scan huge blocks.
740 if (MaxInstsToScan-- == 0)
741 return nullptr;
742
743 --ScanFrom;
744
745 if (Value *Available = getAvailableLoadStore(Inst, StrippedPtr, AccessTy,
746 AccessProps, DL, IsLoadCSE))
747 return Available;
748
749 // Try to get the store size for the type.
750 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
751 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
752
753 // If both StrippedPtr and StorePtr reach all the way to an alloca or
754 // global and they are different, ignore the store. This is a trivial form
755 // of alias analysis that is important for reg2mem'd code.
756 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
757 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
758 StrippedPtr != StorePtr)
759 continue;
760
761 if (!AA) {
762 // When AA isn't available, but if the load and the store have the same
763 // base, constant offsets and non-overlapping access ranges, ignore the
764 // store. This is a simple form of alias analysis that is used by the
765 // inliner. FIXME: use BasicAA if possible.
767 Loc.Ptr, AccessTy, SI->getPointerOperand(),
768 SI->getValueOperand()->getType(), DL))
769 continue;
770 } else {
771 // If we have alias analysis and it says the store won't modify the
772 // loaded value, ignore the store.
773 if (!isModSet(AA->getModRefInfo(SI, Loc)))
774 continue;
775 }
776
777 // Otherwise the store that may or may not alias the pointer, bail out.
778 ++ScanFrom;
779 return nullptr;
780 }
781
782 // If this is some other instruction that may clobber Ptr, bail out.
783 if (Inst->mayWriteToMemory()) {
784 // If alias analysis claims that it really won't modify the load,
785 // ignore it.
786 if (AA && !isModSet(AA->getModRefInfo(Inst, Loc)))
787 continue;
788
789 // May modify the pointer, bail out.
790 ++ScanFrom;
791 return nullptr;
792 }
793 }
794
795 // Got to the start of the block, we didn't find it, but are done for this
796 // block.
797 return nullptr;
798}
799
801 bool *IsLoadCSE,
802 unsigned MaxInstsToScan) {
803 const DataLayout &DL = Load->getDataLayout();
804 Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts();
805 BasicBlock *ScanBB = Load->getParent();
806 Type *AccessTy = Load->getType();
807 LoadStoreInstProperties AccessProps = Load->getProperties();
808
809 if (!Load->isUnordered())
810 return nullptr;
811
812 // Try to find an available value first, and delay expensive alias analysis
813 // queries until later.
814 Value *Available = nullptr;
815 SmallVector<Instruction *> MustNotAliasInsts;
816 for (Instruction &Inst : make_range(++Load->getReverseIterator(),
817 ScanBB->rend())) {
818 if (Inst.isDebugOrPseudoInst())
819 continue;
820
821 if (MaxInstsToScan-- == 0)
822 return nullptr;
823
824 Available = getAvailableLoadStore(&Inst, StrippedPtr, AccessTy, AccessProps,
825 DL, IsLoadCSE);
826 if (Available)
827 break;
828
829 if (Inst.mayWriteToMemory())
830 MustNotAliasInsts.push_back(&Inst);
831 }
832
833 // If we found an available value, ensure that the instructions in between
834 // did not modify the memory location.
835 if (Available) {
837 for (Instruction *Inst : MustNotAliasInsts)
838 if (isModSet(AA.getModRefInfo(Inst, Loc)))
839 return nullptr;
840 }
841
842 return Available;
843}
844
846 const MemoryLocation &MemLoc,
847 Align MemLocAlign,
849 unsigned ScanLimit) {
850 // Ensure no partial overlap is possible, and that the stored value is the
851 // current content of MemLoc.
852 if (!MemLoc.Size.hasValue() || MemLoc.Size.isScalable())
853 return false;
854 if (MemoryLocation::get(SI).Size != MemLoc.Size)
855 return false;
856 if (std::min(MemLocAlign, SI->getAlign()).value() <
857 MemLoc.Size.getValue().getFixedValue())
858 return false;
859
860 auto *LI = dyn_cast<LoadInst>(SI->getValueOperand());
861 if (!LI || LI->getParent() != SI->getParent())
862 return false;
863 if (AA.alias(MemoryLocation::get(LI), MemLoc) != AliasResult::MustAlias)
864 return false;
865
866 // No memory operation in between may modify MemLoc.
867 unsigned NumVisited = 0;
868 for (const Instruction *I = LI; I != SI; I = I->getNextNode())
869 if (++NumVisited > ScanLimit || isModSet(AA.getModRefInfo(I, MemLoc)))
870 return false;
871
872 return true;
873}
874
875// Returns true if a use is either in an ICmp/PtrToInt or a Phi/Select that only
876// feeds into them.
877static bool isPointerUseReplaceable(const Use &U, bool HasNonAddressBits) {
878 unsigned Limit = 40;
879 SmallVector<const User *> Worklist({U.getUser()});
881
882 while (!Worklist.empty() && --Limit) {
883 auto *User = Worklist.pop_back_val();
884 if (!Visited.insert(User).second)
885 continue;
887 continue;
888 // FIXME: The PtrToIntInst case here is not strictly correct, as it
889 // changes which provenance is exposed.
890 if (!HasNonAddressBits && isa<PtrToIntInst>(User))
891 continue;
893 Worklist.append(User->user_begin(), User->user_end());
894 else
895 return false;
896 }
897
898 return Limit != 0;
899}
900
901static bool isPointerAlwaysReplaceable(const Value *From, const Value *To,
902 const DataLayout &DL) {
903 // This is not strictly correct, but we do it for now to retain important
904 // optimizations.
906 return true;
907 // Conversely, replacing null in the default address space with destination
908 // pointer is always valid.
909 if (isa<ConstantPointerNull>(From) &&
910 From->getType()->getPointerAddressSpace() == 0)
911 return true;
912 // Allow replacement with dereferenceable constants. This is not strictly
913 // correct, but required for vtable assumptions.
914 auto IsBasedOnConstantGlobal = [](const Value *V) {
916 return GV && GV->isConstant();
917 };
918 if (isa<Constant>(To) && To->getType()->isPointerTy() &&
920 IsBasedOnConstantGlobal(To))
921 return true;
922 return getUnderlyingObjectAggressive(From, /*MustPreserveProvenance=*/true) ==
923 getUnderlyingObjectAggressive(To, /*MustPreserveProvenance=*/true);
924}
925
927 const DataLayout &DL) {
928 Type *Ty = To->getType();
929 assert(U->getType() == Ty && "values must have matching types");
930 // Not a pointer, just return true.
931 if (!Ty->isPtrOrPtrVectorTy())
932 return true;
933
934 // Do not perform replacements in lifetime intrinsic arguments.
935 if (isa<LifetimeIntrinsic>(U.getUser()))
936 return false;
937
938 if (isPointerAlwaysReplaceable(&*U, To, DL))
939 return true;
940
941 bool HasNonAddressBits =
942 DL.getAddressSizeInBits(Ty) != DL.getPointerTypeSizeInBits(Ty);
943 return isPointerUseReplaceable(U, HasNonAddressBits);
944}
945
946bool llvm::canReplacePointersIfEqual(const Value *From, const Value *To,
947 const DataLayout &DL) {
948 assert(From->getType() == To->getType() && "values must have matching types");
949 // Not a pointer, just return true.
950 if (!From->getType()->isPtrOrPtrVectorTy())
951 return true;
952
953 return isPointerAlwaysReplaceable(From, To, DL);
954}
955
958 SmallVectorImpl<LoadInst *> &NonDereferenceableAndAlignedLoads,
960 for (BasicBlock *BB : L->blocks()) {
961 for (Instruction &I : *BB) {
962 if (auto *LI = dyn_cast<LoadInst>(&I)) {
963 if (!isDereferenceableAndAlignedInLoop(LI, L, *SE, *DT, AC, Predicates))
964 NonDereferenceableAndAlignedLoads.push_back(LI);
965 } else if (I.mayReadFromMemory() || I.mayWriteToMemory() ||
966 I.mayThrow()) {
967 return false;
968 }
969 }
970 }
971 return true;
972}
973
975 Value *Ptr) {
976 assert(Ptr->getType()->isPointerTy() && "Must be called with pointer arg");
977
978 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
979 LinearExpression Expr(Ptr, BitWidth);
980
981 while (true) {
982 auto *GEP = dyn_cast<GEPOperator>(Expr.BasePtr);
983 if (!GEP || GEP->getSourceElementType()->isScalableTy())
984 return Expr;
985
986 Value *VarIndex = nullptr;
987 for (Value *Index : GEP->indices()) {
988 if (isa<ConstantInt>(Index))
989 continue;
990 // Only allow a single variable index. We do not bother to handle the
991 // case of the same variable index appearing multiple times.
992 if (Expr.Index || VarIndex)
993 return Expr;
994 VarIndex = Index;
995 }
996
997 // Don't return non-canonical indexes.
998 if (VarIndex && !VarIndex->getType()->isIntegerTy(BitWidth))
999 return Expr;
1000
1001 // We have verified that we can fully handle this GEP, so we can update Expr
1002 // members past this point.
1003 Expr.BasePtr = GEP->getPointerOperand();
1004 Expr.Flags = Expr.Flags.intersectForOffsetAdd(GEP->getNoWrapFlags());
1006 GTI != GTE; ++GTI) {
1007 Value *Index = GTI.getOperand();
1008 if (auto *ConstOffset = dyn_cast<ConstantInt>(Index)) {
1009 if (ConstOffset->isZero())
1010 continue;
1011 if (StructType *STy = GTI.getStructTypeOrNull()) {
1012 unsigned ElementIdx = ConstOffset->getZExtValue();
1013 const StructLayout *SL = DL.getStructLayout(STy);
1014 Expr.Offset += SL->getElementOffset(ElementIdx);
1015 continue;
1016 }
1017 // Truncate if type size exceeds index space.
1018 APInt IndexedSize(BitWidth, GTI.getSequentialElementStride(DL),
1019 /*isSigned=*/false,
1020 /*implcitTrunc=*/true);
1021 Expr.Offset += ConstOffset->getValue() * IndexedSize;
1022 continue;
1023 }
1024
1025 // FIXME: Also look through a mul/shl in the index.
1026 assert(Expr.Index == nullptr && "Shouldn't have index yet");
1027 Expr.Index = Index;
1028 // Truncate if type size exceeds index space.
1029 Expr.Scale = APInt(BitWidth, GTI.getSequentialElementStride(DL),
1030 /*isSigned=*/false, /*implicitTrunc=*/true);
1031 }
1032 }
1033
1034 return Expr;
1035}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:1232
Hexagon Common GEP
static bool AreEquivalentAddressValues(const Value *A, const Value *B)
Test if A and B will obviously have the same value.
Definition Loads.cpp:285
static bool isPointerUseReplaceable(const Use &U, bool HasNonAddressBits)
Definition Loads.cpp:877
static bool isPointerAlwaysReplaceable(const Value *From, const Value *To, const DataLayout &DL)
Definition Loads.cpp:901
static bool isDereferenceableAndAlignedPointerViaAssumption(const Value *Ptr, Align Alignment, const SimplifyQuery &SQ, bool IgnoreFree, function_ref< bool(const RetainedKnowledge &RK)> CheckSize)
Definition Loads.cpp:35
static bool areNonOverlapSameBaseLoadAndStore(const Value *LoadPtr, Type *LoadTy, const Value *StorePtr, Type *StoreTy, const DataLayout &DL)
Definition Loads.cpp:571
static bool hasCompatibleAtomicAccessSize(Type *AccessTy, const LoadStoreInstProperties &AccessProps, Type *OtherAccessTy, const LoadStoreInstProperties &OtherProps, const DataLayout &DL)
Definition Loads.cpp:597
static Value * getAvailableLoadStore(Instruction *Inst, const Value *Ptr, Type *AccessTy, const LoadStoreInstProperties &AccessProps, const DataLayout &DL, bool *IsLoadCSE)
Definition Loads.cpp:612
static bool suppressSpeculativeLoadForSanitizers(const Instruction &CtxI)
Definition Loads.cpp:443
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
uint64_t IntrinsicInst * II
Class for arbitrary precision integers.
Definition APInt.h:78
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
@ MustAlias
The two locations precisely alias each other.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
reverse_iterator rend()
Definition BasicBlock.h:464
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:579
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Represents calls to the gc.relocate intrinsic.
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
LLVM_ABI bool isDebugOrPseudoInst() const LLVM_READONLY
Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
An instruction for reading from memory.
Value * getPointerOperand()
bool isUnordered() const
Align getAlign() const
Return the alignment of the access that is being performed.
bool hasValue() const
static LocationSize precise(uint64_t Value)
bool isScalable() const
TypeSize getValue() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
The main scalar evolution driver.
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
This class represents the LLVM 'select' instruction.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
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.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:1002
LLVM_ABI bool canBeFreed() const
Return true if the memory object referred to by V can by freed in the scope for which the SSA value d...
Definition Value.cpp:832
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:712
user_iterator user_end()
Definition Value.h:412
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
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
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:165
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::pair< const SCEV *, const SCEV * > getStartAndEndForAccess(const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE, DenseMap< std::pair< const SCEV *, const SCEV * >, std::pair< const SCEV *, const SCEV * > > *PointerBounds, DominatorTree *DT, AssumptionCache *AC, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
Calculate Start and End points of memory access using exact backedge taken count BTC if computable or...
@ Offset
Definition DWP.cpp:577
LLVM_ABI RetainedKnowledge getKnowledgeForValue(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, function_ref< bool(RetainedKnowledge, Instruction *, const CallBase::BundleOpInfo *)> Filter=[](auto...) { return true;})
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and it match...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool isStorePreservingMemoryLocation(const StoreInst *SI, const MemoryLocation &MemLoc, Align MemLocAlign, BatchAAResults &AA, unsigned ScanLimit)
Check whether SI, which may alias MemLoc, can be safely skipped.
Definition Loads.cpp:845
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:452
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition Loads.cpp:554
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:926
LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To, const DataLayout &DL)
Returns true if a pointer value From can be replaced with another pointer value \To if they are deeme...
Definition Loads.cpp:946
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp:974
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
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 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 bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:456
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:244
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isReadOnlyLoop(Loop *L, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, SmallVectorImpl< LoadInst * > &NonDereferenceableAndAlignedLoads, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns true if the loop contains read-only memory accesses and doesn't throw.
Definition Loads.cpp:956
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:264
LLVM_ABI Value * findAvailablePtrLoadStore(const MemoryLocation &Loc, Type *AccessTy, const LoadStoreInstProperties &AccessProps, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, BatchAAResults *AA, bool *IsLoadCSE, unsigned *NumScanedInst)
Scan backwards to see if we have the value of the given pointer available locally within a small numb...
Definition Loads.cpp:715
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:304
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:226
GEPNoWrapFlags Flags
Definition Loads.h:231
A structure representing the properties of a load or store instruction.
Various options to control the behavior of getObjectSize.
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can't be evaluated.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
Represent one information held inside an operand bundle of an llvm.assume.
Attribute::AttrKind AttrKind
const DataLayout & DL
const DominatorTree * DT
AssumptionCache * AC
const Instruction * CtxI
const TargetLibraryInfo * TLI