LLVM 24.0.0git
BasicAliasAnalysis.cpp
Go to the documentation of this file.
1//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
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 primary stateless implementation of the
10// Alias Analysis interface that implements identities (two different
11// globals cannot alias, etc), but does no stateful analysis.
12//
13//===----------------------------------------------------------------------===//
14
16#include "AnalysisOptions.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ScopeExit.h"
21#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/CFG.h"
30#include "llvm/IR/Argument.h"
31#include "llvm/IR/Attributes.h"
33#include "llvm/IR/Constant.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/CycleInfo.h"
37#include "llvm/IR/DataLayout.h"
39#include "llvm/IR/Dominators.h"
40#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalAlias.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/Operator.h"
51#include "llvm/IR/Type.h"
52#include "llvm/IR/User.h"
53#include "llvm/IR/Value.h"
55#include "llvm/Pass.h"
59#include "llvm/Support/ModRef.h"
61#include <cassert>
62#include <cstdint>
63#include <cstdlib>
64#include <optional>
65#include <utility>
66
67#define DEBUG_TYPE "basicaa"
68
69using namespace llvm;
70
71/// SearchLimitReached / SearchTimes shows how often the limit of
72/// to decompose GEPs is reached. It will affect the precision
73/// of basic alias analysis.
74STATISTIC(SearchLimitReached, "Number of times the limit to "
75 "decompose GEPs is reached");
76STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
77
79 const TargetLibraryInfo &TLI, AssumptionCache &AC,
80 DominatorTree *DT)
81 : Opts(getAnalysisOptions(F)), DL(DL), F(F), TLI(TLI), AC(AC), DT_(DT) {}
82
84 FunctionAnalysisManager::Invalidator &Inv) {
85 // We don't care if this analysis itself is preserved, it has no state. But
86 // we need to check that the analyses it depends on have been. Note that we
87 // may be created without handles to some analyses and in that case don't
88 // depend on them.
89 if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
90 (DT_ && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
91 Inv.invalidate<TargetLibraryAnalysis>(Fn, PA))
92 return true;
93
94 // Otherwise this analysis result remains valid.
95 return false;
96}
97
98//===----------------------------------------------------------------------===//
99// Useful predicates
100//===----------------------------------------------------------------------===//
101
102/// Returns the size of the object specified by V or UnknownSize if unknown.
103static std::optional<TypeSize> getObjectSize(const Value *V,
104 const DataLayout &DL,
105 const TargetLibraryInfo &TLI,
106 bool NullIsValidLoc,
107 bool RoundToAlign = false) {
108 ObjectSizeOpts Opts;
109 Opts.RoundToAlign = RoundToAlign;
110 Opts.NullIsUnknownSize = NullIsValidLoc;
111 if (std::optional<TypeSize> Size = getBaseObjectSize(V, DL, &TLI, Opts)) {
112 // FIXME: Remove this check, only exists to preserve previous behavior.
113 if (Size->isScalable())
114 return std::nullopt;
115 return Size;
116 }
117 return std::nullopt;
118}
119
120/// Return the minimal extent from \p V to the end of the underlying object,
121/// assuming the result is used in an aliasing query. E.g., we do use the query
122/// location size and the fact that null pointers cannot alias here.
124 const LocationSize &LocSize,
125 const DataLayout &DL,
126 bool NullIsValidLoc) {
127 // If we have dereferenceability information we know a lower bound for the
128 // extent as accesses for a lower offset would be valid. We need to exclude
129 // the "or null" part if null is a valid pointer. We can ignore frees, as an
130 // access after free would be undefined behavior.
131 bool CanBeNull;
132 uint64_t DerefBytes =
133 V.getPointerDereferenceableBytes(DL, CanBeNull, /*CanBeFreed=*/nullptr);
134 DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
135 // If queried with a precise location size, we assume that location size to be
136 // accessed, thus valid.
137 if (LocSize.isPrecise())
138 DerefBytes = std::max(DerefBytes, LocSize.getValue().getKnownMinValue());
139 return TypeSize::getFixed(DerefBytes);
140}
141
142/// Returns true if we can prove that the object specified by V is smaller than
143/// the minimal extent accessed from OtherV with size OtherSize. Bails out early
144/// unless the root object is passed as the first parameter.
145static bool isObjectSmallerThan(const Value *V, const Value &OtherV,
146 LocationSize OtherSize, const DataLayout &DL,
147 const TargetLibraryInfo &TLI,
148 bool NullIsValidLoc) {
149 // Note that the meanings of the "object" are slightly different in the
150 // following contexts:
151 // c1: llvm::getObjectSize()
152 // c2: llvm.objectsize() intrinsic
153 // c3: isObjectSmallerThan()
154 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
155 // refers to the "entire object".
156 //
157 // Consider this example:
158 // char *p = (char*)malloc(100)
159 // char *q = p+80;
160 //
161 // In the context of c1 and c2, the "object" pointed by q refers to the
162 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
163 //
164 // In the context of c3, the "object" refers to the chunk of memory being
165 // allocated. So, the "object" has 100 bytes, and q points to the middle the
166 // "object". However, unless p, the root object, is passed as the first
167 // parameter, the call to isIdentifiedObject() makes isObjectSmallerThan()
168 // bail out early.
169 if (!isIdentifiedObject(V))
170 return false;
171
172 // This function needs to use the aligned object size because we allow
173 // reads a bit past the end given sufficient alignment.
174 std::optional<TypeSize> ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
175 /*RoundToAlign*/ true);
176 if (!ObjectSize)
177 return false;
178
179 TypeSize Size = getMinimalExtentFrom(OtherV, OtherSize, DL, NullIsValidLoc);
180 return TypeSize::isKnownLT(*ObjectSize, Size);
181}
182
183/// Returns true if we can prove that the object specified by V has size Size.
184static bool isObjectSize(const Value *V, TypeSize Size, const DataLayout &DL,
185 const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
186 std::optional<TypeSize> ObjectSize =
187 getObjectSize(V, DL, TLI, NullIsValidLoc);
188 return ObjectSize && *ObjectSize == Size;
189}
190
191/// Return true if both V1 and V2 are VScale
192static bool areBothVScale(const Value *V1, const Value *V2) {
195}
196
197//===----------------------------------------------------------------------===//
198// CaptureAnalysis implementations
199//===----------------------------------------------------------------------===//
200
202
204 const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) {
205 if (!isIdentifiedFunctionLocal(Object))
207
208 auto [CacheIt, Inserted] = IsCapturedCache.try_emplace(Object);
209 if (Inserted)
210 CacheIt->second = PointerMayBeCaptured(
213
214 return ReturnCaptures ? CacheIt->second.WithRet : CacheIt->second.WithoutRet;
215}
216
217static bool isNotInCycle(const Instruction *I, const DominatorTree *DT,
218 const LoopInfo *LI, const CycleInfo *CI) {
219 if (CI)
220 return !CI->getCycle(I->getParent());
221
222 BasicBlock *BB = const_cast<BasicBlock *>(I->getParent());
224 return Succs.empty() ||
225 !isPotentiallyReachableFromMany(Succs, BB, nullptr, DT, LI);
226}
227
229 const LoopInfo *LI,
230 const CycleInfo *CI)
231 : DT(DT), LI(LI), CI(CI),
232 BlockNumberEpoch(DT.getRoot()->getParent()->getBlockNumberEpoch()) {}
233
235 const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) {
236 if (!isIdentifiedFunctionLocal(Object))
238
239 auto Iter = EarliestEscapes.try_emplace(Object);
240 if (Iter.second) {
241 auto [EarliestInst, Res] = FindEarliestCapture(
242 Object, *DT.getRoot()->getParent(), DT, CaptureComponents::Provenance);
243 if (EarliestInst)
244 Inst2Obj[EarliestInst].push_back(Object);
245 Iter.first->second = {EarliestInst, Res};
246 }
247
248 if (ReturnCaptures) {
249 assert(!I && "Context instruction not supported if ReturnCaptures");
250 return Iter.first->second.second.WithRet;
251 }
252
253 auto IsNotCapturedBefore = [&]() {
254 // No capturing instruction.
255 Instruction *CaptureInst = Iter.first->second.first;
256 if (!CaptureInst)
257 return true;
258
259 // No context instruction means any use is capturing.
260 if (!I)
261 return false;
262
263 if (I == CaptureInst) {
264 if (OrAt || !isNotInCycle(I, &DT, LI, CI))
265 return false;
266 } else {
267 // A capture earlier in the same block always reaches I. Otherwise,
268 // reachability only depends on the two blocks, so cache it.
269 const BasicBlock *CaptureBB = CaptureInst->getParent();
270 const BasicBlock *BB = I->getParent();
271 if (CaptureBB == BB && CaptureInst->comesBefore(I))
272 return false;
273 assert(BB->getParent()->getBlockNumberEpoch() == BlockNumberEpoch &&
274 "Blocks were renumbered while EarliestEscapeAnalysis was alive");
275 auto [It, Inserted] = IsReachableCache.try_emplace(
276 {CaptureBB->getNumber(), BB->getNumber()});
277 if (Inserted)
278 It->second =
279 isPotentiallyReachable(CaptureInst, I, nullptr, &DT, LI, CI);
280 if (It->second)
281 return false;
282 }
283
284 // Handle longjmp during re-entry. Checked last, as it scans the whole
285 // function the first time it is queried.
286 return !callsReturnsTwiceFn();
287 };
288 if (IsNotCapturedBefore())
290 return Iter.first->second.second.WithoutRet;
291}
292
293bool EarliestEscapeAnalysis::callsReturnsTwiceFn() {
294 if (!CallsReturnsTwiceFn)
295 CallsReturnsTwiceFn =
297 return *CallsReturnsTwiceFn;
298}
299
301 auto Iter = Inst2Obj.find(I);
302 if (Iter != Inst2Obj.end()) {
303 for (const Value *Obj : Iter->second)
304 EarliestEscapes.erase(Obj);
305 Inst2Obj.erase(I);
306 }
307}
308
310 for (const Use &U : I->operands()) {
311 if (!U->getType()->isPointerTy())
312 continue;
313
315 DetermineUseCaptureKind(U, /*Base=*/nullptr).UseCC)) {
316 EarliestEscapes.clear();
317 Inst2Obj.clear();
318 return;
319 }
320 }
321}
322
323//===----------------------------------------------------------------------===//
324// GetElementPtr Instruction Decomposition and Analysis
325//===----------------------------------------------------------------------===//
326
327namespace {
328/// Represents zext(sext(trunc(V))).
329struct CastedValue {
330 const Value *V;
331 unsigned ZExtBits = 0;
332 unsigned SExtBits = 0;
333 unsigned TruncBits = 0;
334 /// Whether trunc(V) is non-negative.
335 bool IsNonNegative = false;
336
337 explicit CastedValue(const Value *V) : V(V) {}
338 explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits,
339 unsigned TruncBits, bool IsNonNegative)
340 : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits),
341 IsNonNegative(IsNonNegative) {}
342
343 unsigned getBitWidth() const {
344 return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits +
345 SExtBits;
346 }
347
348 CastedValue withValue(const Value *NewV, bool PreserveNonNeg) const {
349 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits,
350 IsNonNegative && PreserveNonNeg);
351 }
352
353 /// Replace V with zext(NewV)
354 CastedValue withZExtOfValue(const Value *NewV, bool ZExtNonNegative) const {
355 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
357 if (ExtendBy <= TruncBits)
358 // zext<nneg>(trunc(zext(NewV))) == zext<nneg>(trunc(NewV))
359 // The nneg can be preserved on the outer zext here.
360 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,
361 IsNonNegative);
362
363 // zext(sext(zext(NewV))) == zext(zext(zext(NewV)))
364 ExtendBy -= TruncBits;
365 // zext<nneg>(zext(NewV)) == zext(NewV)
366 // zext(zext<nneg>(NewV)) == zext<nneg>(NewV)
367 // The nneg can be preserved from the inner zext here but must be dropped
368 // from the outer.
369 return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0,
370 ZExtNonNegative);
371 }
372
373 /// Replace V with sext(NewV)
374 CastedValue withSExtOfValue(const Value *NewV) const {
375 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
377 if (ExtendBy <= TruncBits)
378 // zext<nneg>(trunc(sext(NewV))) == zext<nneg>(trunc(NewV))
379 // The nneg can be preserved on the outer zext here
380 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,
381 IsNonNegative);
382
383 // zext(sext(sext(NewV)))
384 ExtendBy -= TruncBits;
385 // zext<nneg>(sext(sext(NewV))) = zext<nneg>(sext(NewV))
386 // The nneg can be preserved on the outer zext here
387 return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0, IsNonNegative);
388 }
389
390 APInt evaluateWith(APInt N) const {
391 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
392 "Incompatible bit width");
393 if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits);
394 if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits);
395 if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits);
396 return N;
397 }
398
399 ConstantRange evaluateWith(ConstantRange N) const {
400 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
401 "Incompatible bit width");
402 if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits);
403 if (IsNonNegative && !N.isAllNonNegative())
404 N = N.intersectWith(
405 ConstantRange(APInt::getZero(N.getBitWidth()),
406 APInt::getSignedMinValue(N.getBitWidth())));
407 if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits);
408 if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits);
409 return N;
410 }
411
412 KnownBits evaluateWith(KnownBits K) const {
413 assert(K.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
414 "Incompatible bit width");
415 if (TruncBits)
416 K = K.trunc(K.getBitWidth() - TruncBits);
417 if (SExtBits)
418 K = K.sext(K.getBitWidth() + SExtBits);
419 if (ZExtBits)
420 K = K.zext(K.getBitWidth() + ZExtBits);
421 return K;
422 }
423
424 bool canDistributeOver(bool NUW, bool NSW) const {
425 // zext(x op<nuw> y) == zext(x) op<nuw> zext(y)
426 // sext(x op<nsw> y) == sext(x) op<nsw> sext(y)
427 // trunc(x op y) == trunc(x) op trunc(y)
428 return (!ZExtBits || NUW) && (!SExtBits || NSW);
429 }
430
431 bool hasSameCastsAs(const CastedValue &Other) const {
432 if (V->getType() != Other.V->getType())
433 return false;
434
435 if (ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits &&
436 TruncBits == Other.TruncBits)
437 return true;
438 // If either CastedValue has a nneg zext then the sext/zext bits are
439 // interchangable for that value.
440 if (IsNonNegative || Other.IsNonNegative)
441 return (ZExtBits + SExtBits == Other.ZExtBits + Other.SExtBits &&
442 TruncBits == Other.TruncBits);
443 return false;
444 }
445};
446
447/// Represents zext(sext(trunc(V))) * Scale + Offset.
448struct LinearExpression {
449 CastedValue Val;
450 APInt Scale;
451 APInt Offset;
452
453 /// True if all operations in this expression are NUW.
454 bool IsNUW;
455 /// True if all operations in this expression are NSW.
456 bool IsNSW;
457
458 LinearExpression(const CastedValue &Val, const APInt &Scale,
459 const APInt &Offset, bool IsNUW, bool IsNSW)
460 : Val(Val), Scale(Scale), Offset(Offset), IsNUW(IsNUW), IsNSW(IsNSW) {}
461
462 LinearExpression(const CastedValue &Val)
463 : Val(Val), IsNUW(true), IsNSW(true) {
464 unsigned BitWidth = Val.getBitWidth();
465 Scale = APInt(BitWidth, 1);
466 Offset = APInt(BitWidth, 0);
467 }
468
469 LinearExpression mul(const APInt &Other, bool MulIsNUW, bool MulIsNSW) const {
470 // The check for zero offset is necessary, because generally
471 // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z).
472 bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero()));
473 bool NUW = IsNUW && (Other.isOne() || MulIsNUW);
474 // (V *nsw Scale) *nsw Other is V *nsw (Scale * Other) only if the new
475 // scale does not overflow. Otherwise the scale we record is not the value
476 // V is multiplied by: V * 2^32 * 2^31 is V * 2^63 and is defined for
477 // V == -1, while V *nsw INT64_MIN is not.
478 bool ScaleOverflow;
479 APInt NewScale = Scale.smul_ov(Other, ScaleOverflow);
480 NSW &= !ScaleOverflow;
481 return LinearExpression(Val, NewScale, Offset * Other, NUW, NSW);
482 }
483};
484}
485
486/// Analyzes the specified value as a linear expression: "A*V + B", where A and
487/// B are constant integers.
489 const CastedValue &Val, const DataLayout &DL, unsigned Depth,
491 // Limit our recursion depth.
492 if (Depth == 6)
493 return Val;
494
495 if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V))
496 return LinearExpression(Val, APInt(Val.getBitWidth(), 0),
497 Val.evaluateWith(Const->getValue()), true, true);
498
499 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) {
500 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
501 APInt RHS = Val.evaluateWith(RHSC->getValue());
502 // The only non-OBO case we deal with is or, and only limited to the
503 // case where it is both nuw and nsw.
504 bool NUW = true, NSW = true;
506 NUW &= BOp->hasNoUnsignedWrap();
507 NSW &= BOp->hasNoSignedWrap();
508 }
509 if (!Val.canDistributeOver(NUW, NSW))
510 return Val;
511
512 // While we can distribute over trunc, we cannot preserve nowrap flags
513 // in that case.
514 if (Val.TruncBits)
515 NUW = NSW = false;
516
517 LinearExpression E(Val);
518 switch (BOp->getOpcode()) {
519 default:
520 // We don't understand this instruction, so we can't decompose it any
521 // further.
522 return Val;
523 case Instruction::Or:
524 // X|C == X+C if it is disjoint. Otherwise we can't analyze it.
525 if (!cast<PossiblyDisjointInst>(BOp)->isDisjoint())
526 return Val;
527
528 [[fallthrough]];
529 case Instruction::Add: {
530 E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,
531 Depth + 1, AC, DT);
532 // Folding the constants can overflow even if each add is nsw.
533 bool Overflow;
534 E.Offset = E.Offset.sadd_ov(RHS, Overflow);
535 E.IsNUW &= NUW;
536 E.IsNSW &= NSW && !Overflow;
537 break;
538 }
539 case Instruction::Sub: {
540 E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,
541 Depth + 1, AC, DT);
542 bool Overflow;
543 E.Offset = E.Offset.ssub_ov(RHS, Overflow);
544 E.IsNUW = false; // sub nuw x, y is not add nuw x, -y.
545 E.IsNSW &= NSW && !Overflow;
546 break;
547 }
548 case Instruction::Mul:
549 E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,
550 Depth + 1, AC, DT)
551 .mul(RHS, NUW, NSW);
552 break;
553 case Instruction::Shl: {
554 // We're trying to linearize an expression of the kind:
555 // shl i8 -128, 36
556 // where the shift count exceeds the bitwidth of the type.
557 // We can't decompose this further (the expression would return
558 // a poison value).
559 if (RHS.getLimitedValue() > Val.getBitWidth())
560 return Val;
561
562 // X << C is X * (1 << C). Treat it as a multiplication, so that nsw
563 // is dropped in the cases where mul drops it. In addition, 1 << C is
564 // INT_MIN when C is the bit width minus one, so shl nsw is not mul
565 // nsw by that constant: shl nsw -1, C is defined, mul nsw -1, INT_MIN
566 // is not.
567 unsigned BitWidth = Val.getBitWidth();
568 unsigned ShAmt = RHS.getLimitedValue();
569 E = GetLinearExpression(Val.withValue(BOp->getOperand(0), NSW), DL,
570 Depth + 1, AC, DT)
571 .mul(APInt(BitWidth, 1).shl(ShAmt), NUW,
572 NSW && ShAmt < BitWidth - 1);
573 break;
574 }
575 }
576 return E;
577 }
578 }
579
580 if (const auto *ZExt = dyn_cast<ZExtInst>(Val.V))
581 return GetLinearExpression(
582 Val.withZExtOfValue(ZExt->getOperand(0), ZExt->hasNonNeg()), DL,
583 Depth + 1, AC, DT);
584
585 if (isa<SExtInst>(Val.V))
586 return GetLinearExpression(
587 Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
588 DL, Depth + 1, AC, DT);
589
590 return Val;
591}
592
593namespace {
594// A linear transformation of a Value; this class represents
595// ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale.
596struct VariableGEPIndex {
597 CastedValue Val;
598 APInt Scale;
599
600 // Context instruction to use when querying information about this index.
601 const Instruction *CtxI;
602
603 /// True if all operations in this expression are NSW.
604 bool IsNSW;
605
606 /// True if the index should be subtracted rather than added. We don't simply
607 /// negate the Scale, to avoid losing the NSW flag: X - INT_MIN*1 may be
608 /// non-wrapping, while X + INT_MIN*(-1) wraps.
609 bool IsNegated;
610
611 bool hasNegatedScaleOf(const VariableGEPIndex &Other) const {
612 if (IsNegated == Other.IsNegated)
613 return Scale == -Other.Scale;
614 return Scale == Other.Scale;
615 }
616
617 void dump() const {
618 print(dbgs());
619 dbgs() << "\n";
620 }
621 void print(raw_ostream &OS) const {
622 OS << "(V=" << Val.V->getName()
623 << ", zextbits=" << Val.ZExtBits
624 << ", sextbits=" << Val.SExtBits
625 << ", truncbits=" << Val.TruncBits
626 << ", scale=" << Scale
627 << ", nsw=" << IsNSW
628 << ", negated=" << IsNegated << ")";
629 }
630};
631}
632
633// Represents the internal structure of a GEP, decomposed into a base pointer,
634// constant offsets, and variable scaled indices.
636 // Base pointer of the GEP
637 const Value *Base;
638 // Total constant offset from base.
640 // Scaled variable (non-constant) indices.
642 // Nowrap flags common to all GEP operations involved in expression.
644
645 void dump() const {
646 print(dbgs());
647 dbgs() << "\n";
648 }
649 void print(raw_ostream &OS) const {
650 OS << ", inbounds=" << (NWFlags.isInBounds() ? "1" : "0")
651 << ", nuw=" << (NWFlags.hasNoUnsignedWrap() ? "1" : "0")
652 << "(DecomposedGEP Base=" << Base->getName() << ", Offset=" << Offset
653 << ", VarIndices=[";
654 for (size_t i = 0; i < VarIndices.size(); i++) {
655 if (i != 0)
656 OS << ", ";
657 VarIndices[i].print(OS);
658 }
659 OS << "])";
660 }
661};
662
663// Results of analyzing variable GEP indices for offset-based disambiguation.
669
670/// If V is a symbolic pointer expression, decompose it into a base pointer
671/// with a constant offset and a number of scaled symbolic offsets.
672///
673/// The scaled symbolic offsets (represented by pairs of a Value* and a scale
674/// in the VarIndices vector) are Value*'s that are known to be scaled by the
675/// specified amount, but which may have other unrepresented high bits. As
676/// such, the gep cannot necessarily be reconstructed from its decomposed form.
678BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
680 // Limit recursion depth to limit compile time in crazy cases.
681 unsigned MaxLookup = MaxLookupSearchDepth;
682 SearchTimes++;
683 const Instruction *CtxI = dyn_cast<Instruction>(V);
684
685 unsigned IndexSize = DL.getIndexTypeSizeInBits(V->getType());
686 DecomposedGEP Decomposed;
687 Decomposed.Offset = APInt(IndexSize, 0);
688 do {
689 // See if this is a bitcast or GEP.
690 const Operator *Op = dyn_cast<Operator>(V);
691 if (!Op) {
692 // The only non-operator case we can handle are GlobalAliases.
693 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
694 if (!GA->isInterposable()) {
695 V = GA->getAliasee();
696 continue;
697 }
698 }
699 Decomposed.Base = V;
700 return Decomposed;
701 }
702
703 if (Op->getOpcode() == Instruction::BitCast ||
704 Op->getOpcode() == Instruction::AddrSpaceCast) {
705 Value *NewV = Op->getOperand(0);
706 auto *NewVTy = NewV->getType();
707 // Don't look through casts to non-scalar-pointer types or address spaces
708 // with differing index widths.
709 if (!isa<PointerType>(NewVTy) ||
710 DL.getIndexTypeSizeInBits(NewVTy) != IndexSize) {
711 Decomposed.Base = V;
712 return Decomposed;
713 }
714 V = NewV;
715 continue;
716 }
717
718 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
719 if (!GEPOp) {
720 if (const auto *PHI = dyn_cast<PHINode>(V)) {
721 // Look through single-arg phi nodes created by LCSSA.
722 if (PHI->getNumIncomingValues() == 1) {
723 V = PHI->getIncomingValue(0);
724 continue;
725 }
726 } else if (const auto *Call = dyn_cast<CallBase>(V)) {
727 // CaptureTracking can know about special capturing properties of some
728 // intrinsics like launder.invariant.group, that can't be expressed with
729 // the attributes, but have properties like returning aliasing pointer.
730 // Because some analysis may assume that nocaptured pointer is not
731 // returned from some special intrinsic (because function would have to
732 // be marked with returns attribute), it is crucial to use this function
733 // because it should be in sync with CaptureTracking. Not using it may
734 // cause weird miscompilations where 2 aliasing pointers are assumed to
735 // noalias.
736 // Pass MustPreserveOffset=true so we exclude llvm.ptrmask, which can
737 // change the byte offset by clearing low bits and would otherwise
738 // corrupt the symbolic offset we are accumulating in `Decomposed`.
740 Call, /*MustPreserveOffset=*/true)) {
741 V = RP;
742 continue;
743 }
744 }
745
746 Decomposed.Base = V;
747 return Decomposed;
748 }
749
750 // Track the common nowrap flags for all GEPs we see.
751 Decomposed.NWFlags &= GEPOp->getNoWrapFlags();
752
753 assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized");
754
755 // Fast path for canonical constant-offset getelementptr i8.
756 if (GEPOp->getSourceElementType()->isIntegerTy(8) &&
757 GEPOp->getNumOperands() == 2) {
758 if (const auto *CIdx = dyn_cast<ConstantInt>(GEPOp->getOperand(1))) {
759 if (!CIdx->isZero())
760 Decomposed.Offset += CIdx->getValue().sextOrTrunc(IndexSize);
761 V = GEPOp->getOperand(0);
762 continue;
763 }
764 }
765
766 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
768 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
769 I != E; ++I, ++GTI) {
770 const Value *Index = *I;
771 // Compute the (potentially symbolic) offset in bytes for this index.
772 if (StructType *STy = GTI.getStructTypeOrNull()) {
773 // For a struct, add the member offset.
774 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
775 if (FieldNo == 0)
776 continue;
777
778 Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);
779 continue;
780 }
781
782 // For an array/pointer, add the element offset, explicitly scaled.
783 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
784 if (CIdx->isZero())
785 continue;
786
787 // Don't attempt to analyze GEPs if the scalable index is not zero.
788 TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);
789 if (AllocTypeSize.isScalable()) {
790 Decomposed.Base = V;
791 return Decomposed;
792 }
793
794 Decomposed.Offset += AllocTypeSize.getFixedValue() *
795 CIdx->getValue().sextOrTrunc(IndexSize);
796 continue;
797 }
798
799 TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);
800 if (AllocTypeSize.isScalable()) {
801 Decomposed.Base = V;
802 return Decomposed;
803 }
804
805 // If the integer type is smaller than the index size, it is implicitly
806 // sign extended or truncated to index size.
807 bool NUSW = GEPOp->hasNoUnsignedSignedWrap();
808 bool NUW = GEPOp->hasNoUnsignedWrap();
809 bool NonNeg = NUSW && NUW;
810 unsigned Width = Index->getType()->getIntegerBitWidth();
811 unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0;
812 unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0;
814 CastedValue(Index, 0, SExtBits, TruncBits, NonNeg), DL, 0, AC, DT);
815
816 // Scale by the type size.
817 APInt TypeSize(IndexSize, AllocTypeSize.getFixedValue(),
818 /*isSigned=*/false, /*implicitTrunc=*/true);
819 LE = LE.mul(TypeSize, NUW, NUSW);
820 Decomposed.Offset += LE.Offset;
821 APInt Scale = LE.Scale;
822 if (!LE.IsNUW)
823 Decomposed.NWFlags = Decomposed.NWFlags.withoutNoUnsignedWrap();
824
825 // If we already had an occurrence of this index variable, merge this
826 // scale into it. For example, we want to handle:
827 // A[x][x] -> x*16 + x*4 -> x*20
828 // This also ensures that 'x' only appears in the index list once.
829 for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
830 if ((Decomposed.VarIndices[i].Val.V == LE.Val.V ||
831 areBothVScale(Decomposed.VarIndices[i].Val.V, LE.Val.V)) &&
832 Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) {
833 Scale += Decomposed.VarIndices[i].Scale;
834 // We cannot guarantee no-wrap for the merge.
835 LE.IsNSW = LE.IsNUW = false;
836 Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
837 break;
838 }
839 }
840
841 if (!!Scale) {
842 VariableGEPIndex Entry = {LE.Val, Scale, CtxI, LE.IsNSW,
843 /* IsNegated */ false};
844 Decomposed.VarIndices.push_back(Entry);
845 }
846 }
847
848 // Analyze the base pointer next.
849 V = GEPOp->getOperand(0);
850 } while (--MaxLookup);
851
852 // If the chain of expressions is too deep, just return early.
853 Decomposed.Base = V;
854 SearchLimitReached++;
855 return Decomposed;
856}
857
859 AAQueryInfo &AAQI,
860 bool IgnoreLocals) {
861 assert(Visited.empty() && "Visited must be cleared after use!");
862 llvm::scope_exit _([&] { Visited.clear(); });
863
864 unsigned MaxLookup = 8;
866 Worklist.push_back(Loc.Ptr);
868
869 do {
870 const Value *V = getUnderlyingObject(Worklist.pop_back_val());
871 if (!Visited.insert(V).second)
872 continue;
873
874 // Ignore allocas if we were instructed to do so.
875 if (IgnoreLocals && isa<AllocaInst>(V))
876 continue;
877
878 // If the location points to memory that is known to be invariant for
879 // the life of the underlying SSA value, then we can exclude Mod from
880 // the set of valid memory effects.
881 //
882 // An argument that is marked readonly and noalias is known to be
883 // invariant while that function is executing.
884 if (const Argument *Arg = dyn_cast<Argument>(V)) {
885 if (Arg->hasNoAliasAttr() && Arg->onlyReadsMemory()) {
886 Result |= ModRefInfo::Ref;
887 continue;
888 }
889 }
890
891 // A global constant can't be mutated.
892 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
893 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
894 // global to be marked constant in some modules and non-constant in
895 // others. GV may even be a declaration, not a definition.
896 if (!GV->isConstant())
897 return ModRefInfo::ModRef;
898 continue;
899 }
900
901 // If both select values point to local memory, then so does the select.
902 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
903 Worklist.push_back(SI->getTrueValue());
904 Worklist.push_back(SI->getFalseValue());
905 continue;
906 }
907
908 // If all values incoming to a phi node point to local memory, then so does
909 // the phi.
910 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
911 // Don't bother inspecting phi nodes with many operands.
912 if (PN->getNumIncomingValues() > MaxLookup)
913 return ModRefInfo::ModRef;
914 append_range(Worklist, PN->incoming_values());
915 continue;
916 }
917
918 // Otherwise be conservative.
919 return ModRefInfo::ModRef;
920 } while (!Worklist.empty() && --MaxLookup);
921
922 // If we hit the maximum number of instructions to examine, be conservative.
923 if (!Worklist.empty())
924 return ModRefInfo::ModRef;
925
926 return Result;
927}
928
929static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
931 return II && II->getIntrinsicID() == IID;
932}
933
934/// Returns the behavior when calling the given call site.
936 AAQueryInfo &AAQI) {
937 MemoryEffects Min = Call->getAttributes().getMemoryEffects();
938
939 if (const Function *F = dyn_cast<Function>(Call->getCalledOperand())) {
940 MemoryEffects FuncME = AAQI.AAR.getMemoryEffects(F);
941 // Operand bundles on the call may also read or write memory, in addition
942 // to the behavior of the called function.
943 if (Call->hasReadingOperandBundles())
944 FuncME |= MemoryEffects::readOnly();
945 if (Call->hasClobberingOperandBundles())
946 FuncME |= MemoryEffects::writeOnly();
947 if (Call->isVolatile()) {
948 // Volatile operations also access inaccessible memory.
950 }
951 Min &= FuncME;
952 }
953
954 return Min;
955}
956
957/// Returns the behavior when calling the given function. For use when the call
958/// site is not known.
960 return F->getMemoryEffects();
961}
962
964 unsigned ArgIdx) {
965 if (Call->doesNotAccessMemory(ArgIdx))
967
968 if (Call->onlyWritesMemory(ArgIdx))
969 return ModRefInfo::Mod;
970
971 if (Call->onlyReadsMemory(ArgIdx))
972 return ModRefInfo::Ref;
973
974 return ModRefInfo::ModRef;
975}
976
977#ifndef NDEBUG
978static const Function *getParent(const Value *V) {
979 if (const Instruction *inst = dyn_cast<Instruction>(V)) {
980 if (!inst->getParent())
981 return nullptr;
982 return inst->getParent()->getParent();
983 }
984
985 if (const Argument *arg = dyn_cast<Argument>(V))
986 return arg->getParent();
987
988 return nullptr;
989}
990
991static bool notDifferentParent(const Value *O1, const Value *O2) {
992
993 const Function *F1 = getParent(O1);
994 const Function *F2 = getParent(O2);
995
996 return !F1 || !F2 || F1 == F2;
997}
998#endif
999
1001 const MemoryLocation &LocB, AAQueryInfo &AAQI,
1002 const Instruction *CtxI) {
1003 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
1004 "BasicAliasAnalysis doesn't support interprocedural queries.");
1005 return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI, CtxI);
1006}
1007
1008/// Checks to see if the specified callsite can clobber the specified memory
1009/// object.
1010///
1011/// Since we only look at local properties of this function, we really can't
1012/// say much about this query. We do, however, use simple "address taken"
1013/// analysis on local objects.
1015 const MemoryLocation &Loc,
1016 AAQueryInfo &AAQI) {
1018 "AliasAnalysis query involving multiple functions!");
1019
1020 const Value *Object = getUnderlyingObject(Loc.Ptr);
1021
1022 // Calls marked 'tail' cannot read or write allocas from the current frame
1023 // because the current frame might be destroyed by the time they run. However,
1024 // a tail call may use an alloca with byval. Calling with byval copies the
1025 // contents of the alloca into argument registers or stack slots, so there is
1026 // no lifetime issue.
1027 if (isa<AllocaInst>(Object))
1028 if (const CallInst *CI = dyn_cast<CallInst>(Call))
1029 if (CI->isTailCall() &&
1030 !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
1031 return ModRefInfo::NoModRef;
1032
1033 // Stack restore is able to modify unescaped dynamic allocas. Assume it may
1034 // modify them even though the alloca is not escaped.
1035 if (auto *AI = dyn_cast<AllocaInst>(Object))
1036 if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
1037 return ModRefInfo::Mod;
1038
1039 // We can completely ignore inaccessible memory here, because MemoryLocations
1040 // can only reference accessible memory.
1041 auto ME = AAQI.AAR.getMemoryEffects(Call, AAQI)
1043 if (ME.doesNotAccessMemory())
1044 return ModRefInfo::NoModRef;
1045
1046 ModRefInfo ArgMR = ME.getModRef(IRMemLocation::ArgMem);
1047 ModRefInfo ErrnoMR = ME.getModRef(IRMemLocation::ErrnoMem);
1048 ModRefInfo OtherMR = ME.getModRef(IRMemLocation::Other);
1049
1050 // Take into account potential synchronization effects of the call.
1051 // We assume synchronization can not occur if the call does not read/write
1052 // other memory (this in particular ensures that readonly/argmemonly continue
1053 // to work as expected for frontends that do not emit nosync).
1054 // FIXME: This should apply to all calls, but is limited to inline asm to
1055 // limit impact. This ensures that inline asm memory barriers work correctly.
1057 if (isModAndRefSet(OtherMR) && Call->maySynchronize() &&
1058 Call->isInlineAsm()) {
1059 SyncMR = getSyncEffects(&AAQI.AAR, Loc, AAQI);
1060 if (isModAndRefSet(SyncMR))
1061 return SyncMR;
1062 }
1063
1064 // An identified function-local object that does not escape can only be
1065 // accessed via call arguments. Reduce OtherMR (which includes accesses to
1066 // escaped memory) based on that.
1067 //
1068 // We model calls that can return twice (setjmp) as clobbering non-escaping
1069 // objects, to model any accesses that may occur prior to the second return.
1070 // As an exception, ignore allocas, as setjmp is not required to preserve
1071 // non-volatile stores for them.
1072 if (isModOrRefSet(OtherMR) && !isa<Constant>(Object) && Call != Object &&
1073 (isa<AllocaInst>(Object) || !Call->hasFnAttr(Attribute::ReturnsTwice))) {
1075 Object, Call, /*OrAt=*/false, /*ReturnCaptures=*/false);
1076 if (capturesNothing(CC))
1077 OtherMR = ModRefInfo::NoModRef;
1079 OtherMR = ModRefInfo::Ref;
1080 }
1081
1082 // Refine the modref info for argument memory. We only bother to do this
1083 // if ArgMR is not a subset of OtherMR, otherwise this won't have an impact
1084 // on the final result.
1085 if ((ArgMR | OtherMR) != OtherMR) {
1087 for (const Use &U : Call->data_ops()) {
1088 const Value *Arg = U;
1089 if (!Arg->getType()->isPointerTy())
1090 continue;
1091 unsigned ArgIdx = Call->getDataOperandNo(&U);
1092 MemoryLocation ArgLoc =
1093 Call->isArgOperand(&U)
1094 ? MemoryLocation::getForArgument(Call, ArgIdx, TLI)
1096 AliasResult ArgAlias = AAQI.AAR.alias(ArgLoc, Loc, AAQI, Call);
1097 if (ArgAlias != AliasResult::NoAlias)
1098 NewArgMR |= ArgMR & AAQI.AAR.getArgModRefInfo(Call, ArgIdx);
1099
1100 // Exit early if we cannot improve over the original ArgMR.
1101 if (NewArgMR == ArgMR)
1102 break;
1103 }
1104 ArgMR = NewArgMR;
1105 }
1106
1107 ModRefInfo Result = ArgMR | OtherMR | SyncMR;
1108
1109 // Refine accesses to errno memory.
1110 if ((ErrnoMR | Result) != Result) {
1111 if (AAQI.AAR.aliasErrno(Loc, Call) != AliasResult::NoAlias) {
1112 // Exclusion conditions do not hold, this memory location may alias errno.
1113 Result |= ErrnoMR;
1114 }
1115 }
1116
1117 if (!isModAndRefSet(Result))
1118 return Result;
1119
1120 // Like assumes, invariant.start intrinsics were also marked as arbitrarily
1121 // writing so that proper control dependencies are maintained but they never
1122 // mod any particular memory location visible to the IR.
1123 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
1124 // intrinsic is now modeled as reading memory. This prevents hoisting the
1125 // invariant.start intrinsic over stores. Consider:
1126 // *ptr = 40;
1127 // *ptr = 50;
1128 // invariant_start(ptr)
1129 // int val = *ptr;
1130 // print(val);
1131 //
1132 // This cannot be transformed to:
1133 //
1134 // *ptr = 40;
1135 // invariant_start(ptr)
1136 // *ptr = 50;
1137 // int val = *ptr;
1138 // print(val);
1139 //
1140 // The transformation will cause the second store to be ignored (based on
1141 // rules of invariant.start) and print 40, while the first program always
1142 // prints 50.
1143 if (isIntrinsicCall(Call, Intrinsic::invariant_start))
1144 return ModRefInfo::Ref;
1145
1146 // Be conservative.
1147 return ModRefInfo::ModRef;
1148}
1149
1151 const CallBase *Call2,
1152 AAQueryInfo &AAQI) {
1153 // Guard intrinsics are marked as arbitrarily writing so that proper control
1154 // dependencies are maintained but they never mods any particular memory
1155 // location.
1156 //
1157 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
1158 // heap state at the point the guard is issued needs to be consistent in case
1159 // the guard invokes the "deopt" continuation.
1160
1161 // NB! This function is *not* commutative, so we special case two
1162 // possibilities for guard intrinsics.
1163
1164 if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
1165 return isModSet(getMemoryEffects(Call2, AAQI).getModRef())
1168
1169 if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
1170 return isModSet(getMemoryEffects(Call1, AAQI).getModRef())
1173
1174 // Be conservative.
1175 return ModRefInfo::ModRef;
1176}
1177
1178/// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1179/// another pointer.
1180///
1181/// We know that V1 is a GEP, but we don't know anything about V2.
1182/// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
1183/// V2.
1184AliasResult BasicAAResult::aliasGEP(
1185 const GEPOperator *GEP1, LocationSize V1Size,
1186 const Value *V2, LocationSize V2Size,
1187 const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1188 auto BaseObjectsAlias = [&]() {
1189 AliasResult BaseAlias =
1190 AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1191 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);
1192 return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias
1194 };
1195
1196 if (!V1Size.hasValue() && !V2Size.hasValue()) {
1197 // Skip if V2 is itself a phi or select, leave the recursive walk to
1198 // aliasPHI/aliasSelect.
1200 return AliasResult::MayAlias;
1201
1202 // Otherwise check whether the base objects don't alias. Only do so if V2
1203 // is a GEP or an underlying object is a GEP/phi/select, which can be
1204 // analyzed further.
1205 if (isa<GEPOperator>(V2) ||
1208 return BaseObjectsAlias();
1209
1210 return AliasResult::MayAlias;
1211 }
1212
1213 DominatorTree *DT = getDT(AAQI);
1214 DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);
1215 DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT);
1216
1217 // Bail if we were not able to decompose anything.
1218 if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2)
1219 return AliasResult::MayAlias;
1220
1221 // Fall back to base objects if pointers have different index widths.
1222 if (DecompGEP1.Offset.getBitWidth() != DecompGEP2.Offset.getBitWidth())
1223 return BaseObjectsAlias();
1224
1225 // Swap GEP1 and GEP2 if GEP2 has more variable indices.
1226 if (DecompGEP1.VarIndices.size() < DecompGEP2.VarIndices.size()) {
1227 std::swap(DecompGEP1, DecompGEP2);
1228 std::swap(V1Size, V2Size);
1229 std::swap(UnderlyingV1, UnderlyingV2);
1230 }
1231
1232 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1233 // symbolic difference.
1234 subtractDecomposedGEPs(DecompGEP1, DecompGEP2, AAQI);
1235
1236 // If an inbounds GEP would have to start from an out of bounds address
1237 // for the two to alias, then we can assume noalias.
1238 // TODO: Remove !isScalable() once BasicAA fully support scalable location
1239 // size.
1240 if (DecompGEP1.NWFlags.isInBounds() && DecompGEP1.VarIndices.empty() &&
1241 V2Size.hasValue() && !V2Size.isScalable() &&
1242 DecompGEP1.Offset.sge(V2Size.getValue()) &&
1243 isBaseOfObject(DecompGEP2.Base))
1244 return AliasResult::NoAlias;
1245
1246 // Symmetric case to above.
1247 if (DecompGEP2.NWFlags.isInBounds() && DecompGEP1.VarIndices.empty() &&
1248 V1Size.hasValue() && !V1Size.isScalable() &&
1249 DecompGEP1.Offset.sle(-V1Size.getValue()) &&
1250 isBaseOfObject(DecompGEP1.Base))
1251 return AliasResult::NoAlias;
1252
1253 // For GEPs with identical offsets, we can preserve the size and AAInfo
1254 // when performing the alias check on the underlying objects.
1255 if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())
1256 return AAQI.AAR.alias(MemoryLocation(DecompGEP1.Base, V1Size),
1257 MemoryLocation(DecompGEP2.Base, V2Size), AAQI);
1258
1259 // Do the base pointers alias?
1260 AliasResult BaseAlias =
1261 AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(DecompGEP1.Base),
1262 MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI);
1263
1264 // If we get a No or May, then return it immediately, no amount of analysis
1265 // will improve this situation.
1266 if (BaseAlias != AliasResult::MustAlias) {
1267 assert(BaseAlias == AliasResult::NoAlias ||
1268 BaseAlias == AliasResult::MayAlias);
1269 return BaseAlias;
1270 }
1271
1272 // If there is a constant difference between the pointers, but the difference
1273 // is less than the size of the associated memory object, then we know
1274 // that the objects are partially overlapping. If the difference is
1275 // greater, we know they do not overlap.
1276 if (DecompGEP1.VarIndices.empty()) {
1277 APInt &Off = DecompGEP1.Offset;
1278
1279 // Initialize for Off >= 0 (V2 <= GEP1) case.
1280 LocationSize VLeftSize = V2Size;
1281 LocationSize VRightSize = V1Size;
1282 const bool Swapped = Off.isNegative();
1283
1284 if (Swapped) {
1285 // Swap if we have the situation where:
1286 // + +
1287 // | BaseOffset |
1288 // ---------------->|
1289 // |-->V1Size |-------> V2Size
1290 // GEP1 V2
1291 std::swap(VLeftSize, VRightSize);
1292 Off = -Off;
1293 }
1294
1295 if (!VLeftSize.hasValue())
1296 return AliasResult::MayAlias;
1297
1298 const TypeSize LSize = VLeftSize.getValue();
1299 if (!LSize.isScalable()) {
1300 if (Off.ult(LSize)) {
1301 // Conservatively drop processing if a phi was visited and/or offset is
1302 // too big.
1303 AliasResult AR = AliasResult::PartialAlias;
1304 if (VRightSize.hasValue() && !VRightSize.isScalable() &&
1305 Off.ule(INT32_MAX) && (Off + VRightSize.getValue()).ule(LSize)) {
1306 // Memory referenced by right pointer is nested. Save the offset in
1307 // cache. Note that originally offset estimated as GEP1-V2, but
1308 // AliasResult contains the shift that represents GEP1+Offset=V2.
1309 AR.setOffset(-Off.getSExtValue());
1310 AR.swap(Swapped);
1311 }
1312 return AR;
1313 }
1314 return AliasResult::NoAlias;
1315 }
1316
1317 // We can use the getVScaleRange to prove that Off >= (CR.upper * LSize).
1318 ConstantRange CR = getVScaleRange(&F, Off.getBitWidth());
1319 bool Overflow;
1320 APInt UpperRange = CR.getUnsignedMax().umul_ov(
1321 APInt(Off.getBitWidth(), LSize.getKnownMinValue()), Overflow);
1322 if (!Overflow && Off.uge(UpperRange))
1323 return AliasResult::NoAlias;
1324 }
1325
1326 // VScale Alias Analysis - Given one scalable offset between accesses and a
1327 // scalable typesize, we can divide each side by vscale, treating both values
1328 // as a constant. We prove that Offset/vscale >= TypeSize/vscale.
1329 if (DecompGEP1.VarIndices.size() == 1 &&
1330 DecompGEP1.VarIndices[0].Val.TruncBits == 0 &&
1331 DecompGEP1.Offset.isZero() &&
1332 PatternMatch::match(DecompGEP1.VarIndices[0].Val.V,
1334 const VariableGEPIndex &ScalableVar = DecompGEP1.VarIndices[0];
1335 APInt Scale =
1336 ScalableVar.IsNegated ? -ScalableVar.Scale : ScalableVar.Scale;
1337 LocationSize VLeftSize = Scale.isNegative() ? V1Size : V2Size;
1338
1339 // Check if the offset is known to not overflow, if it does then attempt to
1340 // prove it with the known values of vscale_range.
1341 bool Overflows = !DecompGEP1.VarIndices[0].IsNSW;
1342 if (Overflows) {
1343 ConstantRange CR = getVScaleRange(&F, Scale.getBitWidth());
1344 (void)CR.getSignedMax().smul_ov(Scale, Overflows);
1345 }
1346
1347 if (!Overflows) {
1348 // Note that we do not check that the typesize is scalable, as vscale >= 1
1349 // so noalias still holds so long as the dependency distance is at least
1350 // as big as the typesize.
1351 if (VLeftSize.hasValue() &&
1352 Scale.abs().uge(VLeftSize.getValue().getKnownMinValue()))
1353 return AliasResult::NoAlias;
1354 }
1355 }
1356
1357 // If the difference between pointers is Offset +<nuw> Indices then we know
1358 // that the addition does not wrap the pointer index type (add nuw) and the
1359 // constant Offset is a lower bound on the distance between the pointers. We
1360 // can then prove NoAlias via Offset u>= VLeftSize.
1361 // + + +
1362 // | BaseOffset | +<nuw> Indices |
1363 // ---------------->|-------------------->|
1364 // |-->V2Size | |-------> V1Size
1365 // LHS RHS
1366 if (!DecompGEP1.VarIndices.empty() &&
1367 DecompGEP1.NWFlags.hasNoUnsignedWrap() && V2Size.hasValue() &&
1368 !V2Size.isScalable() && DecompGEP1.Offset.uge(V2Size.getValue()))
1369 return AliasResult::NoAlias;
1370
1371 // Bail on analyzing scalable LocationSize.
1372 if (V1Size.isScalable() || V2Size.isScalable())
1373 return AliasResult::MayAlias;
1374
1375 // We need to know both access sizes for all the following heuristics. Don't
1376 // try to reason about sizes larger than the index space.
1377 unsigned BW = DecompGEP1.Offset.getBitWidth();
1378 if (!V1Size.hasValue() || !V2Size.hasValue() ||
1379 !isUIntN(BW, V1Size.getValue()) || !isUIntN(BW, V2Size.getValue()))
1380 return AliasResult::MayAlias;
1381
1382 // Analyze the variable indices, and compute the GCD that the total
1383 // variable offset is guaranteed to be a multiple of, and its approximate
1384 // range.
1385 auto [GCD, OffsetRange, VIKnownBits] = analyzeVariableOffsets(DecompGEP1, DT);
1386
1387 // We now have accesses at two offsets from the same base:
1388 // 1. (...)*GCD + DecompGEP1.Offset with size V1Size
1389 // 2. 0 with size V2Size
1390 // Using arithmetic modulo GCD, the accesses are at
1391 // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits
1392 // into the range [V2Size..GCD), then we know they cannot overlap.
1393 APInt ModOffset = DecompGEP1.Offset.srem(GCD);
1394 if (ModOffset.isNegative())
1395 ModOffset += GCD; // We want mod, not rem.
1396 if (ModOffset.uge(V2Size.getValue()) &&
1397 (GCD - ModOffset).uge(V1Size.getValue()))
1398 return AliasResult::NoAlias;
1399
1400 // If the ranges of potentially accessed bytes are disjoint, there cannot be
1401 // any overlap.
1402 ConstantRange Range1 = OffsetRange.add(
1403 ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));
1404 ConstantRange Range2 =
1405 ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));
1406 if (Range1.intersectWith(Range2).isEmptySet())
1407 return AliasResult::NoAlias;
1408
1409 // If a minimum absolute variable offset can be established, employ it to
1410 // prove that the two accesses are far enough apart.
1411 if (auto MinAbsVarIndex =
1412 computeMinAbsVarOffset(DecompGEP1, VIKnownBits, DT, AAQI)) {
1413 // The constant offset will have added at least +/-MinAbsVarIndex to it.
1414 APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;
1415 APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;
1416 // We know that Offset <= OffsetLo || Offset >= OffsetHi
1417 if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) &&
1418 OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue()))
1419 return AliasResult::NoAlias;
1420 }
1421
1422 // As a last attempt, search for a constant offset between the variable
1423 // indices that GetLinearExpression could not extract through casts.
1424 if (computeConstantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT, AAQI))
1425 return AliasResult::NoAlias;
1426
1427 // Statically, we can see that the base objects are the same, but the
1428 // pointers have dynamic offsets which we can't resolve. And none of our
1429 // little tricks above worked.
1430 return AliasResult::MayAlias;
1431}
1432
1434 // If the results agree, take it.
1435 if (A == B)
1436 return A;
1437 // A mix of PartialAlias and MustAlias is PartialAlias.
1441 // Otherwise, we don't know anything.
1442 return AliasResult::MayAlias;
1443}
1444
1445/// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1446/// against another.
1448BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
1449 const Value *V2, LocationSize V2Size,
1450 AAQueryInfo &AAQI) {
1451 // If the values are Selects with the same condition, we can do a more precise
1452 // check: just check for aliases between the values on corresponding arms.
1453 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1454 if (isValueEqualInPotentialCycles(SI->getCondition(), SI2->getCondition(),
1455 AAQI)) {
1456 AliasResult Alias =
1457 AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize),
1458 MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);
1459 if (Alias == AliasResult::MayAlias)
1460 return AliasResult::MayAlias;
1461 AliasResult ThisAlias =
1462 AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),
1463 MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);
1464 return MergeAliasResults(ThisAlias, Alias);
1465 }
1466
1467 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1468 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1469 AliasResult Alias = AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize),
1470 MemoryLocation(V2, V2Size), AAQI);
1471 if (Alias == AliasResult::MayAlias)
1472 return AliasResult::MayAlias;
1473
1474 AliasResult ThisAlias =
1475 AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),
1476 MemoryLocation(V2, V2Size), AAQI);
1477 return MergeAliasResults(ThisAlias, Alias);
1478}
1479
1480/// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1481/// another.
1482AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1483 const Value *V2, LocationSize V2Size,
1484 AAQueryInfo &AAQI) {
1485 if (!PN->getNumIncomingValues())
1486 return AliasResult::NoAlias;
1487 // If the values are PHIs in the same block, we can do a more precise
1488 // as well as efficient check: just check for aliases between the values
1489 // on corresponding edges. Don't do this if we are analyzing across
1490 // iterations, as we may pick a different phi entry in different iterations.
1491 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1492 if (PN2->getParent() == PN->getParent() && !AAQI.MayBeCrossIteration) {
1493 std::optional<AliasResult> Alias;
1494 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1495 AliasResult ThisAlias = AAQI.AAR.alias(
1496 MemoryLocation(PN->getIncomingValue(i), PNSize),
1497 MemoryLocation(
1498 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size),
1499 AAQI);
1500 if (Alias)
1501 *Alias = MergeAliasResults(*Alias, ThisAlias);
1502 else
1503 Alias = ThisAlias;
1504 if (*Alias == AliasResult::MayAlias)
1505 break;
1506 }
1507 return *Alias;
1508 }
1509
1510 SmallVector<Value *, 4> V1Srcs;
1511 // If a phi operand recurses back to the phi, we can still determine NoAlias
1512 // if we don't alias the underlying objects of the other phi operands, as we
1513 // know that the recursive phi needs to be based on them in some way.
1514 bool isRecursive = false;
1515 auto CheckForRecPhi = [&](Value *PV) {
1516 if (!Opts.basic_aa_recphi)
1517 return false;
1518 if (getUnderlyingObject(PV) == PN) {
1519 isRecursive = true;
1520 return true;
1521 }
1522 return false;
1523 };
1524
1525 SmallPtrSet<Value *, 4> UniqueSrc;
1526 for (Value *PV1 : PN->incoming_values()) {
1527 // Skip the phi itself being the incoming value.
1528 if (PV1 == PN)
1529 continue;
1530
1531 if (CheckForRecPhi(PV1))
1532 continue;
1533
1534 if (UniqueSrc.insert(PV1).second)
1535 V1Srcs.push_back(PV1);
1536 }
1537
1538 // To control compile time, only allow a phi source if there is either single
1539 // source or all sources are not phis, e.g. LCSSA phis or phi start values of
1540 // pointer IVs.
1541 if (V1Srcs.size() > 1 && any_of(V1Srcs, IsaPred<PHINode>))
1542 return AliasResult::MayAlias;
1543
1544 // If V1Srcs is empty then that means that the phi has no underlying non-phi
1545 // value. This should only be possible in blocks unreachable from the entry
1546 // block, but return MayAlias just in case.
1547 if (V1Srcs.empty())
1548 return AliasResult::MayAlias;
1549
1550 // If this PHI node is recursive, indicate that the pointer may be moved
1551 // across iterations. We can only prove NoAlias if different underlying
1552 // objects are involved.
1553 if (isRecursive)
1555
1556 // In the recursive alias queries below, we may compare values from two
1557 // different loop iterations.
1558 SaveAndRestore SavedMayBeCrossIteration(AAQI.MayBeCrossIteration, true);
1559
1560 AliasResult Alias = AAQI.AAR.alias(MemoryLocation(V1Srcs[0], PNSize),
1561 MemoryLocation(V2, V2Size), AAQI);
1562
1563 // Early exit if the check of the first PHI source against V2 is MayAlias.
1564 // Other results are not possible.
1565 if (Alias == AliasResult::MayAlias)
1566 return AliasResult::MayAlias;
1567 // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
1568 // remain valid to all elements and needs to conservatively return MayAlias.
1569 if (isRecursive && Alias != AliasResult::NoAlias)
1570 return AliasResult::MayAlias;
1571
1572 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1573 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1574 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1575 Value *V = V1Srcs[i];
1576
1577 AliasResult ThisAlias = AAQI.AAR.alias(
1578 MemoryLocation(V, PNSize), MemoryLocation(V2, V2Size), AAQI);
1579 Alias = MergeAliasResults(ThisAlias, Alias);
1580 if (Alias == AliasResult::MayAlias)
1581 break;
1582 }
1583
1584 return Alias;
1585}
1586
1587// Return true for an Argument or extractvalue(Argument). These are all known
1588// to not alias with FunctionLocal objects and can come up from coerced function
1589// arguments.
1590static bool isArgumentOrArgumentLike(const Value *V) {
1591 if (isa<Argument>(V))
1592 return true;
1594 return E && isa<Argument>(E->getOperand(0));
1595}
1596
1597/// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1598/// array references.
1599AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1600 const Value *V2, LocationSize V2Size,
1601 AAQueryInfo &AAQI,
1602 const Instruction *CtxI) {
1603 // If either of the memory references is empty, it doesn't matter what the
1604 // pointer values are.
1605 if (V1Size.isZero() || V2Size.isZero())
1606 return AliasResult::NoAlias;
1607
1608 // Strip off any casts if they exist.
1609 V1 = V1->stripPointerCastsForAliasAnalysis();
1611
1612 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1613 // value for undef that aliases nothing in the program.
1615 return AliasResult::NoAlias;
1616
1617 // Are we checking for alias of the same value?
1618 // Because we look 'through' phi nodes, we could look at "Value" pointers from
1619 // different iterations. We must therefore make sure that this is not the
1620 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1621 // happen by looking at the visited phi nodes and making sure they cannot
1622 // reach the value.
1623 if (isValueEqualInPotentialCycles(V1, V2, AAQI))
1625
1626 // Figure out what objects these things are pointing to if we can.
1629
1630 // Null values in the default address space don't point to any object, so they
1631 // don't alias any other pointer.
1632 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1633 if (!NullPointerIsDefined(&F, CPN->getPointerType()->getAddressSpace()))
1634 return AliasResult::NoAlias;
1635 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1636 if (!NullPointerIsDefined(&F, CPN->getPointerType()->getAddressSpace()))
1637 return AliasResult::NoAlias;
1638
1639 if (O1 != O2) {
1640 // If V1/V2 point to two different objects, we know that we have no alias.
1642 return AliasResult::NoAlias;
1643
1644 // Function arguments can't alias with things that are known to be
1645 // unambigously identified at the function level.
1648 return AliasResult::NoAlias;
1649
1650 // If one pointer is the result of a call/invoke or load and the other is a
1651 // non-escaping local object within the same function, then we know the
1652 // object couldn't escape to a point where the call could return it.
1653 //
1654 // Note that if the pointers are in different functions, there are a
1655 // variety of complications. A call with a nocapture argument may still
1656 // temporary store the nocapture argument's value in a temporary memory
1657 // location if that memory location doesn't escape. Or it may pass a
1658 // nocapture value to other functions as long as they don't capture it.
1660 O2, dyn_cast<Instruction>(O1), /*OrAt=*/true,
1661 /*ReturnCaptures=*/false)))
1662 return AliasResult::NoAlias;
1664 O1, dyn_cast<Instruction>(O2), /*OrAt=*/true,
1665 /*ReturnCaptures=*/false)))
1666 return AliasResult::NoAlias;
1667 }
1668
1669 // If the size of one access is larger than the entire object on the other
1670 // side, then we know such behavior is undefined and can assume no alias.
1671 bool NullIsValidLocation = NullPointerIsDefined(&F);
1672 if (isObjectSmallerThan(O2, *V1, V1Size, DL, TLI, NullIsValidLocation) ||
1673 isObjectSmallerThan(O1, *V2, V2Size, DL, TLI, NullIsValidLocation))
1674 return AliasResult::NoAlias;
1675
1676 if (Opts.basic_aa_separate_storage) {
1677 for (AssumptionCache::ResultElem &Elem : AC.assumptionsFor(O1)) {
1678 if (!Elem || Elem.Index == AssumptionCache::ExprResultIdx)
1679 continue;
1680
1681 AssumeInst *Assume = cast<AssumeInst>(Elem);
1682 OperandBundleUse OBU = Assume->getOperandBundleAt(Elem.Index);
1683 if (getBundleAttrFromOBU(OBU) == BundleAttr::SeparateStorage) {
1684 assert(OBU.Inputs.size() == 2);
1685 const Value *Hint1 = OBU.Inputs[0].get();
1686 const Value *Hint2 = OBU.Inputs[1].get();
1687 // This is often a no-op; instcombine rewrites this for us. No-op
1688 // getUnderlyingObject calls are fast, though.
1689 const Value *HintO1 = getUnderlyingObject(Hint1);
1690 const Value *HintO2 = getUnderlyingObject(Hint2);
1691
1692 DominatorTree *DT = getDT(AAQI);
1693 auto ValidAssumeForPtrContext = [&](const Value *Ptr) {
1694 if (const Instruction *PtrI = dyn_cast<Instruction>(Ptr)) {
1695 return isValidAssumeForContext(Assume, PtrI, DT,
1696 /* AllowEphemerals */ true);
1697 }
1698 if (const Argument *PtrA = dyn_cast<Argument>(Ptr)) {
1699 const Instruction *FirstI =
1700 &*PtrA->getParent()->getEntryBlock().begin();
1701 return isValidAssumeForContext(Assume, FirstI, DT,
1702 /* AllowEphemerals */ true);
1703 }
1704 return false;
1705 };
1706
1707 if ((O1 == HintO1 && O2 == HintO2) || (O1 == HintO2 && O2 == HintO1)) {
1708 // Note that we go back to V1 and V2 for the
1709 // ValidAssumeForPtrContext checks; they're dominated by O1 and O2,
1710 // so strictly more assumptions are valid for them.
1711 if ((CtxI && isValidAssumeForContext(Assume, CtxI, DT,
1712 AAQI.AllowEphemerals)) ||
1713 (AAQI.AllowEphemerals && (ValidAssumeForPtrContext(V1) ||
1714 ValidAssumeForPtrContext(V2)))) {
1715 // The assumption relates values from the same iteration. Across
1716 // iterations, both underlying objects must be invariant.
1717 if (!isValueEqualInPotentialCycles(O1, O1, AAQI) ||
1718 !isValueEqualInPotentialCycles(O2, O2, AAQI))
1719 break;
1720 return AliasResult::NoAlias;
1721 }
1722 }
1723 }
1724 }
1725 }
1726
1727 // aliasCheckRecursive() only looks through GEPs, phis and selects, and
1728 // otherwise only refines accesses to the same underlying object. All other
1729 // pairs are MayAlias without further queries, so don't cache them.
1732 return AliasResult::MayAlias;
1733
1734 // If one the accesses may be before the accessed pointer, canonicalize this
1735 // by using unknown after-pointer sizes for both accesses. This is
1736 // equivalent, because regardless of which pointer is lower, one of them
1737 // will always came after the other, as long as the underlying objects aren't
1738 // disjoint. We do this so that the rest of BasicAA does not have to deal
1739 // with accesses before the base pointer, and to improve cache utilization by
1740 // merging equivalent states.
1741 if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {
1742 V1Size = LocationSize::afterPointer();
1743 V2Size = LocationSize::afterPointer();
1744 }
1745
1746 // FIXME: If this depth limit is hit, then we may cache sub-optimal results
1747 // for recursive queries. For this reason, this limit is chosen to be large
1748 // enough to be very rarely hit, while still being small enough to avoid
1749 // stack overflows.
1750 if (AAQI.Depth >= 512)
1751 return AliasResult::MayAlias;
1752
1753 // Check the cache before climbing up use-def chains. This also terminates
1754 // otherwise infinitely recursive queries. Include MayBeCrossIteration in the
1755 // cache key, because some cases where MayBeCrossIteration==false returns
1756 // MustAlias or NoAlias may become MayAlias under MayBeCrossIteration==true.
1757 AAQueryInfo::LocPair Locs({V1, V1Size, AAQI.MayBeCrossIteration},
1758 {V2, V2Size, AAQI.MayBeCrossIteration});
1759 const bool Swapped = V1 > V2;
1760 if (Swapped)
1761 std::swap(Locs.first, Locs.second);
1762 const auto &Pair = AAQI.AliasCache.try_emplace(
1763 Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0});
1764 if (!Pair.second) {
1765 auto &Entry = Pair.first->second;
1766 if (!Entry.isDefinitive()) {
1767 // Remember that we used an assumption. This may either be a direct use
1768 // of an assumption, or a use of an entry that may itself be based on an
1769 // assumption.
1770 ++AAQI.NumAssumptionUses;
1771 if (Entry.isAssumption())
1772 ++Entry.NumAssumptionUses;
1773 }
1774 // Cache contains sorted {V1,V2} pairs but we should return original order.
1775 auto Result = Entry.Result;
1776 Result.swap(Swapped);
1777 return Result;
1778 }
1779
1780 int OrigNumAssumptionUses = AAQI.NumAssumptionUses;
1781 unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();
1782 AliasResult Result =
1783 aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2);
1784
1785 auto It = AAQI.AliasCache.find(Locs);
1786 assert(It != AAQI.AliasCache.end() && "Must be in cache");
1787 auto &Entry = It->second;
1788
1789 // Check whether a NoAlias assumption has been used, but disproven.
1790 bool AssumptionDisproven =
1791 Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias;
1792 if (AssumptionDisproven)
1794
1795 // This is a definitive result now, when considered as a root query.
1796 AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;
1797 Entry.Result = Result;
1798 // Cache contains sorted {V1,V2} pairs.
1799 Entry.Result.swap(Swapped);
1800
1801 // If the assumption has been disproven, remove any results that may have
1802 // been based on this assumption. Do this after the Entry updates above to
1803 // avoid iterator invalidation.
1804 if (AssumptionDisproven)
1805 while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)
1807
1808 // The result may still be based on assumptions higher up in the chain.
1809 // Remember it, so it can be purged from the cache later.
1810 if (OrigNumAssumptionUses != AAQI.NumAssumptionUses &&
1811 Result != AliasResult::MayAlias) {
1814 } else {
1815 Entry.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;
1816 }
1817
1818 // Depth is incremented before this function is called, so Depth==1 indicates
1819 // a root query.
1820 if (AAQI.Depth == 1) {
1821 // Any remaining assumption based results must be based on proven
1822 // assumptions, so convert them to definitive results.
1823 for (const auto &Loc : AAQI.AssumptionBasedResults) {
1824 auto It = AAQI.AliasCache.find(Loc);
1825 if (It != AAQI.AliasCache.end())
1826 It->second.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;
1827 }
1829 AAQI.NumAssumptionUses = 0;
1830 }
1831 return Result;
1832}
1833
1834AliasResult BasicAAResult::aliasCheckRecursive(
1835 const Value *V1, LocationSize V1Size,
1836 const Value *V2, LocationSize V2Size,
1837 AAQueryInfo &AAQI, const Value *O1, const Value *O2) {
1838 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1839 AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI);
1840 if (Result != AliasResult::MayAlias)
1841 return Result;
1842 } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {
1843 AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI);
1844 Result.swap();
1845 if (Result != AliasResult::MayAlias)
1846 return Result;
1847 }
1848
1849 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1850 AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI);
1851 if (Result != AliasResult::MayAlias)
1852 return Result;
1853 } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {
1854 AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI);
1855 Result.swap();
1856 if (Result != AliasResult::MayAlias)
1857 return Result;
1858 }
1859
1860 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1861 AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI);
1862 if (Result != AliasResult::MayAlias)
1863 return Result;
1864 } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {
1865 AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI);
1866 Result.swap();
1867 if (Result != AliasResult::MayAlias)
1868 return Result;
1869 }
1870
1871 // If both pointers are pointing into the same object and one of them
1872 // accesses the entire object, then the accesses must overlap in some way.
1873 if (O1 == O2) {
1874 bool NullIsValidLocation = NullPointerIsDefined(&F);
1875 if (V1Size.isPrecise() && V2Size.isPrecise() &&
1876 (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1877 isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))
1879 }
1880
1881 return AliasResult::MayAlias;
1882}
1883
1885 const Instruction *CtxI) {
1886 // Do not make any assumptions when targeting freestanding environments (e.g.,
1887 // in the context of baremetal LTO, errno may have been internalized or
1888 // otherwise promoted to a local variable).
1889 bool IsFreestanding = CtxI->getFunction()->hasFnAttribute("no-builtins");
1890 if (IsFreestanding)
1891 return AliasResult::MayAlias;
1892
1893 // There cannot be any alias with errno if the given memory location is an
1894 // identified function-local object, or the size of the memory access is
1895 // larger than the integer size. The size must be precise: an access with an
1896 // upper-bound size, such as a masked load, may be smaller.
1897 if (Loc.Size.isPrecise() &&
1898 Loc.Size.getValue().getKnownMinValue() * 8 > TLI.getIntSize())
1899 return AliasResult::NoAlias;
1900
1901 const Value *Object = getUnderlyingObject(Loc.Ptr);
1902 if (isIdentifiedFunctionLocal(Object))
1903 return AliasResult::NoAlias;
1904
1905 if (auto *GV = dyn_cast<GlobalVariable>(Object)) {
1906 // Errno cannot alias internal/private globals.
1907 if (GV->hasLocalLinkage())
1908 return AliasResult::NoAlias;
1909
1910 // Neither can errno alias globals where environments define it as a
1911 // function call.
1912 if (TLI.isErrnoFunctionCall())
1913 return AliasResult::NoAlias;
1914 }
1915
1916 return AliasResult::MayAlias;
1917}
1918
1919/// Check whether two Values can be considered equivalent.
1920///
1921/// If the values may come from different cycle iterations, this will also
1922/// check that the values are not part of cycle. We have to do this because we
1923/// are looking through phi nodes, that is we say
1924/// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1925bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1926 const Value *V2,
1927 const AAQueryInfo &AAQI) {
1928 if (V != V2)
1929 return false;
1930
1931 if (!AAQI.MayBeCrossIteration)
1932 return true;
1933
1934 // Non-instructions and instructions in the entry block cannot be part of
1935 // a loop.
1936 const Instruction *Inst = dyn_cast<Instruction>(V);
1937 if (!Inst || Inst->getParent()->isEntryBlock())
1938 return true;
1939
1940 return isNotInCycle(Inst, getDT(AAQI), /*LI=*/nullptr, /*CI=*/nullptr);
1941}
1942
1943/// Computes the symbolic difference between two de-composed GEPs.
1944void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP,
1945 const DecomposedGEP &SrcGEP,
1946 const AAQueryInfo &AAQI) {
1947 // Drop nuw flag from GEP if subtraction of constant offsets overflows in an
1948 // unsigned sense.
1949 if (DestGEP.Offset.ult(SrcGEP.Offset))
1950 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1951
1952 DestGEP.Offset -= SrcGEP.Offset;
1953 for (const VariableGEPIndex &Src : SrcGEP.VarIndices) {
1954 // Find V in Dest. This is N^2, but pointer indices almost never have more
1955 // than a few variable indexes.
1956 bool Found = false;
1957 for (auto I : enumerate(DestGEP.VarIndices)) {
1958 VariableGEPIndex &Dest = I.value();
1959 if ((!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V, AAQI) &&
1960 !areBothVScale(Dest.Val.V, Src.Val.V)) ||
1961 !Dest.Val.hasSameCastsAs(Src.Val))
1962 continue;
1963
1964 // Normalize IsNegated if we're going to lose the NSW flag anyway.
1965 if (Dest.IsNegated) {
1966 Dest.Scale = -Dest.Scale;
1967 Dest.IsNegated = false;
1968 Dest.IsNSW = false;
1969 }
1970
1971 // If we found it, subtract off Scale V's from the entry in Dest. If it
1972 // goes to zero, remove the entry.
1973 if (Dest.Scale != Src.Scale) {
1974 // Drop nuw flag from GEP if subtraction of V's Scale overflows in an
1975 // unsigned sense.
1976 if (Dest.Scale.ult(Src.Scale))
1977 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1978
1979 Dest.Scale -= Src.Scale;
1980 Dest.IsNSW = false;
1981 } else {
1982 DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index());
1983 }
1984 Found = true;
1985 break;
1986 }
1987
1988 // If we didn't consume this entry, add it to the end of the Dest list.
1989 if (!Found) {
1990 VariableGEPIndex Entry = {Src.Val, Src.Scale, Src.CtxI, Src.IsNSW,
1991 /* IsNegated */ true};
1992 DestGEP.VarIndices.push_back(Entry);
1993
1994 // Drop nuw flag when we have unconsumed variable indices from SrcGEP.
1995 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1996 }
1997 }
1998}
1999
2001BasicAAResult::analyzeVariableOffsets(const DecomposedGEP &GEP,
2002 DominatorTree *DT) {
2003 APInt GCD;
2004 ConstantRange OffsetRange(GEP.Offset);
2005 SmallVector<KnownBits, 4> VarIndexKnownBits;
2006 VarIndexKnownBits.reserve(GEP.VarIndices.size());
2007
2008 for (unsigned I = 0, E = GEP.VarIndices.size(); I != E; ++I) {
2009 const VariableGEPIndex &Index = GEP.VarIndices[I];
2010 const APInt &Scale = Index.Scale;
2011
2012 SimplifyQuery SQ(DL, DT, &AC, Index.CtxI, /*UseInstrInfo=*/true);
2013 KnownBits Known = computeKnownBits(Index.Val.V, SQ);
2014 VarIndexKnownBits.emplace_back(Known);
2015
2016 APInt ScaleForGCD = Scale;
2017 if (!Index.IsNSW)
2018 ScaleForGCD =
2020
2021 // If V has known trailing zeros, V is a multiple of 2^VarTZ, so
2022 // V*Scale is a multiple of ScaleForGCD * 2^VarTZ. Shift ScaleForGCD
2023 // left to account for this (trailing zeros compose additively through
2024 // multiplication, even in Z/2^n).
2025 unsigned VarTZ = Known.countMinTrailingZeros();
2026 if (VarTZ > 0) {
2027 unsigned MaxShift =
2028 Scale.getBitWidth() - ScaleForGCD.getSignificantBits();
2029 ScaleForGCD <<= std::min(VarTZ, MaxShift);
2030 }
2031
2032 if (I == 0)
2033 GCD = ScaleForGCD.abs();
2034 else
2035 GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs());
2036
2037 ConstantRange CR =
2038 computeConstantRange(Index.Val.V, /*ForSigned=*/false, SQ);
2039 CR =
2040 CR.intersectWith(ConstantRange::fromKnownBits(Known, /*IsSigned=*/true),
2042 CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth());
2043
2044 assert(OffsetRange.getBitWidth() == Scale.getBitWidth() &&
2045 "Bit widths are normalized to MaxIndexSize");
2046 if (Index.IsNSW)
2047 CR = CR.smul_sat(ConstantRange(Scale));
2048 else
2049 CR = CR.smul_fast(ConstantRange(Scale));
2050
2051 if (Index.IsNegated)
2052 OffsetRange = OffsetRange.sub(CR);
2053 else
2054 OffsetRange = OffsetRange.add(CR);
2055 }
2056
2057 return {GCD, OffsetRange, std::move(VarIndexKnownBits)};
2058}
2059
2060/// Check whether V*Scale cannot wrap for any value of V, so that abs(V*Scale)
2061/// >= abs(Scale) holds in the presence of potentially wrapping math.
2062static bool multiplyByScaleNoWrap(const VariableGEPIndex &Var) {
2063 if (Var.IsNSW)
2064 return true;
2065
2066 int ValOrigBW = Var.Val.V->getType()->getPrimitiveSizeInBits();
2067 // If Scale is small enough so that abs(V*Scale) >= abs(Scale) holds.
2068 // The max value of abs(V) is 2^ValOrigBW - 1. Multiplying with a
2069 // constant smaller than 2^(bitwidth(Val) - ValOrigBW) won't wrap.
2070 int MaxScaleValueBW = Var.Val.getBitWidth() - ValOrigBW;
2071 if (MaxScaleValueBW <= 0)
2072 return false;
2073 return Var.Scale.ule(
2074 APInt::getMaxValue(MaxScaleValueBW).zext(Var.Scale.getBitWidth()));
2075}
2076
2077std::optional<APInt> BasicAAResult::computeMinAbsVarOffset(
2078 const DecomposedGEP &GEP, ArrayRef<KnownBits> VIKnownBits,
2079 DominatorTree *DT, const AAQueryInfo &AAQI) {
2080 const auto &VarIndices = GEP.VarIndices;
2081 if (VarIndices.size() == 1) {
2082 // VarIndex = Scale*V.
2083 const VariableGEPIndex &Var = VarIndices[0];
2084 if (Var.Val.TruncBits == 0 &&
2085 isKnownNonZero(Var.Val.V, SimplifyQuery(DL, DT, &AC, Var.CtxI))) {
2086 // Refine MinAbsVarIndex, if abs(Scale*V) >= abs(Scale) holds in the
2087 // presence of potentially wrapping math.
2088 if (multiplyByScaleNoWrap(Var)) {
2089 // If V != 0 then abs(VarIndex) >= abs(Scale).
2090 return Var.Scale.abs();
2091 }
2092 }
2093 return std::nullopt;
2094 }
2095
2096 if (VarIndices.size() == 2) {
2097 // VarIndex = Scale*V0 + (-Scale)*V1.
2098 // If V0 != V1 then abs(VarIndex) >= abs(Scale).
2099 // Check that MayBeCrossIteration is false, to avoid reasoning about
2100 // inequality of values across loop iterations.
2101 const VariableGEPIndex &Var0 = VarIndices[0];
2102 const VariableGEPIndex &Var1 = VarIndices[1];
2103 bool Preconditions =
2104 Var0.Val.TruncBits == 0 && Var0.Val.hasSameCastsAs(Var1.Val) &&
2107
2108 if (!Preconditions)
2109 return std::nullopt;
2110
2111 if (Var0.hasNegatedScaleOf(Var1)) {
2112 if (isKnownNonEqual(Var0.Val.V, Var1.Val.V,
2113 SimplifyQuery(DL, DT, &AC, /*CtxI=*/Var0.CtxI
2114 ? Var0.CtxI
2115 : Var1.CtxI)))
2116 return Var0.Scale.abs();
2117 // Equal scales would imply the GCD equals the scale itself, leading
2118 // the generalized path below not to do better than isKnownNonEqual.
2119 return std::nullopt;
2120 }
2121
2122 // On the chance we have not found a min abs, fallback to the generalization
2123 // of the two variables case being handled to different scales:
2124 // VarIndex = Scale0*V0 + (-Scale1)*V1 = ScaleGCD*(C0*V0 - C1*V1)
2125 // where C0 = abs(Scale0)/ScaleGCD, C1 = abs(Scale1)/ScaleGCD.
2126 // If C0*V0 != C1*V1, then abs(VarIndex) >= ScaleGCD, leading to the min
2127 // absolute value being ScaleGCD.
2128 //
2129 // Ensure scales, after subtraction, have opposite signs.
2130 bool EffectiveNeg0 = Var0.IsNegated ^ Var0.Scale.isNegative();
2131 bool EffectiveNeg1 = Var1.IsNegated ^ Var1.Scale.isNegative();
2132 if (EffectiveNeg0 != EffectiveNeg1) {
2133 APInt AbsScale0 = Var0.Scale.abs();
2134 APInt AbsScale1 = Var1.Scale.abs();
2135 APInt ScaleGCD = APIntOps::GreatestCommonDivisor(AbsScale0, AbsScale1);
2136 APInt C0 = AbsScale0.udiv(ScaleGCD);
2137 APInt C1 = AbsScale1.udiv(ScaleGCD);
2138
2139 // Try to check whether C0*V0 and C1*V1 are provably distinct (i.e., one
2140 // is guaranteed even while the other is guaranteed odd).
2141 auto Known0 = KnownBits::mul(Var0.Val.evaluateWith(VIKnownBits[0]),
2143
2144 auto Known1 = KnownBits::mul(Var1.Val.evaluateWith(VIKnownBits[1]),
2146
2147 if (auto Res = KnownBits::ne(Known0, Known1); Res && *Res)
2148 return ScaleGCD;
2149 }
2150 }
2151
2152 return std::nullopt;
2153}
2154
2155bool BasicAAResult::computeConstantOffsetHeuristic(const DecomposedGEP &GEP,
2156 LocationSize MaybeV1Size,
2157 LocationSize MaybeV2Size,
2158 AssumptionCache *AC,
2159 DominatorTree *DT,
2160 const AAQueryInfo &AAQI) {
2161 if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||
2162 !MaybeV2Size.hasValue())
2163 return false;
2164
2165 const uint64_t V1Size = MaybeV1Size.getValue();
2166 const uint64_t V2Size = MaybeV2Size.getValue();
2167
2168 const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1];
2169
2170 // After subtracting the two GEP decompositions, we handle variable indices of
2171 // the form of Scale*ext(V0) − Scale*ext(V1), where ext() is the same cast.
2172 if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) ||
2173 !Var0.hasNegatedScaleOf(Var1) ||
2174 Var0.Val.V->getType() != Var1.Val.V->getType())
2175 return false;
2176
2177 // MinDiffBytes below is computed as MinDiff * Scale in the index width. This
2178 // is correct so long as neither Scale*ext(V0) nor Scale*ext(V1) wraps around
2179 // the index space.
2180 if (!multiplyByScaleNoWrap(Var0) || !multiplyByScaleNoWrap(Var1))
2181 return false;
2182
2183 // We'll strip off the Extensions of Var0 and Var1 and do another round
2184 // of GetLinearExpression decomposition. In the example above, if Var0
2185 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
2186
2187 LinearExpression E0 =
2188 GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT);
2189 LinearExpression E1 =
2190 GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT);
2191 if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) ||
2192 !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V, AAQI))
2193 return false;
2194
2195 // We have a hit - Var0 and Var1 only differ by a constant offset!
2196
2197 // If we've been sext'ed then zext'd the maximum difference between Var0 and
2198 // Var1 is possible to calculate, but we're just interested in the absolute
2199 // minimum difference between the two. The minimum distance may occur due to
2200 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
2201 // the minimum distance between %i and %i + 5 is 3.
2202 APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff;
2203 MinDiff = APIntOps::umin(MinDiff, Wrapped);
2204 APInt MinDiffBytes =
2205 MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
2206
2207 // We can't definitely say whether GEP1 is before or after V2 due to wrapping
2208 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
2209 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
2210 // V2Size can fit in the MinDiffBytes gap.
2211 return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) &&
2212 MinDiffBytes.uge(V2Size + GEP.Offset.abs());
2213}
2214
2215//===----------------------------------------------------------------------===//
2216// BasicAliasAnalysis Pass
2217//===----------------------------------------------------------------------===//
2218
2219AnalysisKey BasicAA::Key;
2220
2222 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2223 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2224 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
2225 return BasicAAResult(F.getDataLayout(), F, TLI, AC, DT);
2226}
2227
2229
2230char BasicAAWrapperPass::ID = 0;
2231
2232void BasicAAWrapperPass::anchor() {}
2233
2235 "Basic Alias Analysis (stateless AA impl)", true, true)
2240 "Basic Alias Analysis (stateless AA impl)", true, true)
2241
2245
2250
2251 Result.reset(new BasicAAResult(F.getDataLayout(), F,
2252 TLIWP.getTLI(F), ACT.getAssumptionCache(F),
2253 &DTWP.getDomTree()));
2254
2255 return false;
2256}
2257
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
static bool isObjectSize(const Value *V, TypeSize Size, const DataLayout &DL, const TargetLibraryInfo &TLI, bool NullIsValidLoc)
Returns true if we can prove that the object specified by V has size Size.
static bool isArgumentOrArgumentLike(const Value *V)
static bool notDifferentParent(const Value *O1, const Value *O2)
static bool multiplyByScaleNoWrap(const VariableGEPIndex &Var)
Check whether V*Scale cannot wrap for any value of V, so that abs(V*Scale) >= abs(Scale) holds in the...
static LinearExpression GetLinearExpression(const CastedValue &Val, const DataLayout &DL, unsigned Depth, AssumptionCache *AC, DominatorTree *DT)
Analyzes the specified value as a linear expression: "A*V + B", where A and B are constant integers.
static bool isNotInCycle(const Instruction *I, const DominatorTree *DT, const LoopInfo *LI, const CycleInfo *CI)
static bool areBothVScale(const Value *V1, const Value *V2)
Return true if both V1 and V2 are VScale.
basic Basic Alias true
static TypeSize getMinimalExtentFrom(const Value &V, const LocationSize &LocSize, const DataLayout &DL, bool NullIsValidLoc)
Return the minimal extent from V to the end of the underlying object, assuming the result is used in ...
static AliasResult MergeAliasResults(AliasResult A, AliasResult B)
static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID)
static bool isObjectSmallerThan(const Value *V, const Value &OtherV, LocationSize OtherSize, const DataLayout &DL, const TargetLibraryInfo &TLI, bool NullIsValidLoc)
Returns true if we can prove that the object specified by V is smaller than the minimal extent access...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
static DeltaTreeNode * getRoot(void *Root)
Hexagon Common GEP
#define _
#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
#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
int64_t C1
RISCVCC::CondCode CC
int64_t C0
This file provides utility classes that use RAII to save and restore values.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
This class stores info we want to provide to or retain within an alias query.
SmallVector< AAQueryInfo::LocPair, 4 > AssumptionBasedResults
Location pairs for which an assumption based result is currently stored.
unsigned Depth
Query depth used to distinguish recursive queries.
int NumAssumptionUses
How many active NoAlias assumption uses there are.
std::pair< AACacheLoc, AACacheLoc > LocPair
AliasCacheT AliasCache
bool MayBeCrossIteration
Tracks whether the accesses may be on different cycle iterations.
CaptureAnalysis * CA
bool AllowEphemerals
Whether ephemeral values should be allowed when checking assumes.
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
LLVM_ABI AliasResult aliasErrno(const MemoryLocation &Loc, const Instruction *CtxI)
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
LLVM_ABI ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx)
Get the ModRef info associated with a pointer argument of a call.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2018
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
The possible results of an alias query.
void swap(bool DoSwap=true)
Helper for processing AliasResult for swapped memory location pairs.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
void setOffset(int32_t NewOffset)
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.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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.
This is the AA result object for the basic, local, and stateless alias analysis.
LLVM_ABI ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, AAQueryInfo &AAQI)
Checks to see if the specified callsite can clobber the specified memory object.
LLVM_ABI ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx)
Get the location associated with a pointer argument of a callsite.
LLVM_ABI BasicAAResult(const DataLayout &DL, const Function &F, const TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree *DT=nullptr)
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI)
Returns the behavior when calling the given call site.
LLVM_ABI AliasResult aliasErrno(const MemoryLocation &Loc, const Instruction *CtxI)
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
LLVM_ABI bool invalidate(Function &Fn, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, AAQueryInfo &AAQI, const Instruction *CtxI)
Legacy wrapper pass to provide the BasicAAResult object.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI BasicAAResult run(Function &F, FunctionAnalysisManager &AM)
LLVM Basic Block Representation.
Definition BasicBlock.h:61
unsigned getNumber() const
Definition BasicBlock.h:94
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI ConstantRange smul_fast(const ConstantRange &Other) const
Return range of possible values for a signed multiplication of this and Other.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange smul_sat(const ConstantRange &Other) const
Perform a signed saturating multiplication of two constant ranges.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
void removeInstruction(Instruction *I)
CaptureComponents getCapturesBefore(const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) override
Return how Object may be captured before instruction I, considering only provenance captures.
void insertPotentialCapture(const Instruction *I)
Notify the analysis that I is about to be inserted or moved.
EarliestEscapeAnalysis(DominatorTree &DT, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
FunctionPass(char &pid)
Definition Pass.h:314
unsigned getBlockNumberEpoch() const
Return the "epoch" of current block numbers.
Definition Function.h:836
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags all()
GEPNoWrapFlags withoutNoUnsignedWrap() const
bool hasNoUnsignedSignedWrap() const
Definition Operator.h:392
bool hasNoUnsignedWrap() const
Definition Operator.h:396
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:86
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:385
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
A wrapper class for inspecting calls to intrinsic functions.
bool hasValue() const
bool mayBeBeforePointer() const
Whether accesses before the base pointer are possible.
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
bool isScalable() const
TypeSize getValue() const
bool isPrecise() const
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
MemoryEffectsBase getWithoutLoc(Location Loc) const
Get new MemoryEffectsBase with NoModRef on the given Loc.
Definition ModRef.h:231
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
Representation for a specific memory location.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
op_range incoming_values()
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
This class represents the LLVM 'select' instruction.
CaptureComponents getCapturesBefore(const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) override
Return how Object may be captured before instruction I, considering only provenance captures.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
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
op_iterator op_begin()
Definition User.h:259
const Use * const_op_iterator
Definition User.h:255
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
op_iterator op_end()
Definition User.h:261
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI const Value * stripPointerCastsForAliasAnalysis() const
Strip off pointer casts, all-zero GEPs, single-argument phi nodes and invariant group info.
Definition Value.cpp:723
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
@ Entry
Definition COFF.h:862
bool match(Val *V, const Pattern &P)
auto m_VScale()
Matches a call to llvm.vscale().
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool capturesReadProvenanceOnly(CaptureComponents CC)
Definition ModRef.h:391
SaveAndRestore(T &) -> SaveAndRestore< T >
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
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)
LLVM_ABI bool isBaseOfObject(const Value *V)
Return true if we know V to the base address of the corresponding memory object.
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.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI std::optional< TypeSize > getBaseObjectSize(const Value *Ptr, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Like getObjectSize(), but only returns the size of base objects (like allocas, global variables and a...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
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.
bool capturesFullProvenance(CaptureComponents CC)
Definition ModRef.h:396
LLVM_ABI ModRefInfo getSyncEffects(AAResults *AA, const MemoryLocation &Loc, AAQueryInfo &AAQI)
Get ModRefInfo for a synchronizing operation, such as a fence or stronger than monotonic atomic load/...
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
@ Off
Use window algorithm after SMS algorithm fails.
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
generic_gep_type_iterator<> gep_type_iterator
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI FunctionPass * createBasicAAWrapperPass()
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI 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.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ Other
Any other memory.
Definition ModRef.h:68
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition CFG.cpp:335
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool isPotentiallyReachableFromMany(SmallVectorImpl< BasicBlock * > &Worklist, const BasicBlock *StopBB, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether there is at least one path from a block in 'Worklist' to 'StopBB' without passing t...
Definition CFG.cpp:293
LLVM_ABI std::pair< Instruction *, CaptureResult > FindEarliestCapture(const Value *V, Function &F, const DominatorTree &DT, CaptureComponents Mask, unsigned MaxUsesToExplore=0)
bool isModAndRefSet(const ModRefInfo MRI)
Definition ModRef.h:46
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
constexpr unsigned BitWidth
LLVM_ABI bool isEscapeSource(const Value *V)
Returns true if the pointer is one which would have been considered an escape by isNotCapturedBefore.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI UseCaptureInfo DetermineUseCaptureKind(const Use &U, const Value *Base)
Determine what kind of capture behaviour U may exhibit.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool capturesAnyProvenance(CaptureComponents CC)
Definition ModRef.h:400
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
SmallVector< VariableGEPIndex, 4 > VarIndices
static constexpr int Definitive
Cache entry is neither an assumption nor does it use a (non-definitive) assumption.
static constexpr int AssumptionBased
Cache entry is not an assumption itself, but may be using an assumption from higher up the stack.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
virtual CaptureComponents getCapturesBefore(const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures)=0
Return how Object may be captured before instruction I, considering only provenance captures.
virtual ~CaptureAnalysis()=0
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:227
LinearExpression(Value *BasePtr, unsigned BitWidth)
Definition Loads.h:234
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.
ArrayRef< Use > Inputs