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