LLVM 23.0.0git
AliasAnalysis.cpp
Go to the documentation of this file.
1//==- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation --==//
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 implements the generic AliasAnalysis interface which is used as the
10// common interface used by all clients and implementations of alias analysis.
11//
12// This file also implements the default version of the AliasAnalysis interface
13// that is to be used when no other implementation is specified. This does some
14// simple tests that detect obvious cases: two different global pointers cannot
15// alias, a global cannot alias a malloc, two different mallocs cannot alias,
16// etc.
17//
18// This alias analysis implementation really isn't very good for anything, but
19// it is very fast, and makes a nice clean default implementation. Because it
20// handles lots of little corner cases, other, more complex, alias analysis
21// implementations may choose to rely on this pass to resolve these simple and
22// easy cases.
23//
24//===----------------------------------------------------------------------===//
25
27#include "llvm/ADT/Statistic.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
40#include "llvm/IR/Instruction.h"
42#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
45#include "llvm/Pass.h"
49#include <cassert>
50#include <functional>
51#include <iterator>
52
53#define DEBUG_TYPE "aa"
54
55using namespace llvm;
56
57STATISTIC(NumNoAlias, "Number of NoAlias results");
58STATISTIC(NumMayAlias, "Number of MayAlias results");
59STATISTIC(NumMustAlias, "Number of MustAlias results");
60
61/// Allow disabling BasicAA from the AA results. This is particularly useful
62/// when testing to isolate a single AA implementation.
63static cl::opt<bool> DisableBasicAA("disable-basic-aa", cl::Hidden,
64 cl::init(false));
65
66#ifndef NDEBUG
67/// Print a trace of alias analysis queries and their results.
68static cl::opt<bool> EnableAATrace("aa-trace", cl::Hidden, cl::init(false));
69#else
70static const bool EnableAATrace = false;
71#endif
72
73AAResults::AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
74
76 : TLI(Arg.TLI), AAs(std::move(Arg.AAs)), AADeps(std::move(Arg.AADeps)) {}
77
78AAResults::~AAResults() = default;
79
81 FunctionAnalysisManager::Invalidator &Inv) {
82 // AAResults preserves the AAManager by default, due to the stateless nature
83 // of AliasAnalysis. There is no need to check whether it has been preserved
84 // explicitly. Check if any module dependency was invalidated and caused the
85 // AAManager to be invalidated. Invalidate ourselves in that case.
86 auto PAC = PA.getChecker<AAManager>();
87 if (!PAC.preservedWhenStateless())
88 return true;
89
90 // Check if any of the function dependencies were invalidated, and invalidate
91 // ourselves in that case.
92 for (AnalysisKey *ID : AADeps)
93 if (Inv.invalidate(ID, F, PA))
94 return true;
95
96 // Everything we depend on is still fine, so are we. Nothing to invalidate.
97 return false;
98}
99
100//===----------------------------------------------------------------------===//
101// Default chaining methods
102//===----------------------------------------------------------------------===//
103
105 const MemoryLocation &LocB) {
106 SimpleAAQueryInfo AAQIP(*this);
107 return alias(LocA, LocB, AAQIP, nullptr);
108}
109
111 const MemoryLocation &LocB, AAQueryInfo &AAQI,
112 const Instruction *CtxI) {
113 assert(LocA.Ptr->getType()->isPointerTy() &&
114 LocB.Ptr->getType()->isPointerTy() &&
115 "Can only call alias() on pointers");
117
118 if (EnableAATrace) {
119 for (unsigned I = 0; I < AAQI.Depth; ++I)
120 dbgs() << " ";
121 dbgs() << "Start " << *LocA.Ptr << " @ " << LocA.Size << ", "
122 << *LocB.Ptr << " @ " << LocB.Size << "\n";
123 }
124
125 AAQI.Depth++;
126 for (const auto &AA : AAs) {
127 Result = AA->alias(LocA, LocB, AAQI, CtxI);
128 if (Result != AliasResult::MayAlias)
129 break;
130 }
131 AAQI.Depth--;
132
133 if (EnableAATrace) {
134 for (unsigned I = 0; I < AAQI.Depth; ++I)
135 dbgs() << " ";
136 dbgs() << "End " << *LocA.Ptr << " @ " << LocA.Size << ", "
137 << *LocB.Ptr << " @ " << LocB.Size << " = " << Result << "\n";
138 }
139
140 if (AAQI.Depth == 0) {
141 if (Result == AliasResult::NoAlias)
142 ++NumNoAlias;
143 else if (Result == AliasResult::MustAlias)
144 ++NumMustAlias;
145 else
146 ++NumMayAlias;
147 }
148 return Result;
149}
150
153
154 for (const auto &AA : AAs) {
155 Result = AA->aliasErrno(Loc, M);
156 if (Result != AliasResult::MayAlias)
157 break;
158 }
159
160 return Result;
161}
162
164 bool IgnoreLocals) {
165 SimpleAAQueryInfo AAQIP(*this);
166 return getModRefInfoMask(Loc, AAQIP, IgnoreLocals);
167}
168
170 AAQueryInfo &AAQI, bool IgnoreLocals) {
172
173 for (const auto &AA : AAs) {
174 Result &= AA->getModRefInfoMask(Loc, AAQI, IgnoreLocals);
175
176 // Early-exit the moment we reach the bottom of the lattice.
177 if (isNoModRef(Result))
179 }
180
181 return Result;
182}
183
186
187 for (const auto &AA : AAs) {
188 Result &= AA->getArgModRefInfo(Call, ArgIdx);
189
190 // Early-exit the moment we reach the bottom of the lattice.
191 if (isNoModRef(Result))
193 }
194
195 return Result;
196}
197
199 const CallBase *Call2) {
200 SimpleAAQueryInfo AAQIP(*this);
201 return getModRefInfo(I, Call2, AAQIP);
202}
203
205 AAQueryInfo &AAQI) {
206 // We may have two calls.
207 if (const auto *Call1 = dyn_cast<CallBase>(I)) {
208 // Check if the two calls modify the same memory.
209 return getModRefInfo(Call1, Call2, AAQI);
210 }
211 // If this is a fence, just return ModRef.
212 if (I->isFenceLike())
213 return ModRefInfo::ModRef;
214 // Otherwise, check if the call modifies or references the
215 // location this memory access defines. The best we can say
216 // is that if the call references what this instruction
217 // defines, it must be clobbered by this location.
218 const MemoryLocation DefLoc = MemoryLocation::get(I);
219 ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI);
220 if (isModOrRefSet(MR))
221 return ModRefInfo::ModRef;
223}
224
226 const MemoryLocation &Loc,
227 AAQueryInfo &AAQI) {
229
230 for (const auto &AA : AAs) {
231 Result &= AA->getModRefInfo(Call, Loc, AAQI);
232
233 // Early-exit the moment we reach the bottom of the lattice.
234 if (isNoModRef(Result))
236 }
237
238 // Apply the ModRef mask. This ensures that if Loc is a constant memory
239 // location, we take into account the fact that the call definitely could not
240 // modify the memory location.
241 if (!isNoModRef(Result))
242 Result &= getModRefInfoMask(Loc);
243
244 return Result;
245}
246
249 const MemoryEffects CallDef) {
250
252 auto addModRefInfoForLoc = [&](IRMemLocation L) {
253 ModRefInfo UseMR = CallUse.getModRef(L);
254 if (UseMR == ModRefInfo::NoModRef)
255 return;
256 ModRefInfo DefMR = CallDef.getModRef(L);
257 if (DefMR == ModRefInfo::NoModRef)
258 return;
259 if (DefMR == ModRefInfo::Ref && DefMR == UseMR)
260 return;
261 Result |= UseMR;
262 };
263
264 addModRefInfoForLoc(IRMemLocation::InaccessibleMem);
266 addModRefInfoForLoc(Loc);
267 return Result;
268}
269
271 const CallBase *Call2, AAQueryInfo &AAQI) {
273
274 for (const auto &AA : AAs) {
275 Result &= AA->getModRefInfo(Call1, Call2, AAQI);
276
277 // Early-exit the moment we reach the bottom of the lattice.
278 if (isNoModRef(Result))
280 }
281
282 // Try to refine the mod-ref info further using other API entry points to the
283 // aggregate set of AA results.
284
285 // If Call1 or Call2 are readnone, they don't interact.
286 auto Call1B = getMemoryEffects(Call1, AAQI);
287 if (Call1B.doesNotAccessMemory())
289
290 auto Call2B = getMemoryEffects(Call2, AAQI);
291 if (Call2B.doesNotAccessMemory())
293
294 // If they both only read from memory, there is no dependence.
295 if (Call1B.onlyReadsMemory() && Call2B.onlyReadsMemory())
297
298 // If Call1 only reads memory, the only dependence on Call2 can be
299 // from Call1 reading memory written by Call2.
300 if (Call1B.onlyReadsMemory())
301 Result &= ModRefInfo::Ref;
302 else if (Call1B.onlyWritesMemory())
303 Result &= ModRefInfo::Mod;
304
305 // If Call2 only access memory through arguments, accumulate the mod/ref
306 // information from Call1's references to the memory referenced by
307 // Call2's arguments.
308 if (Call2B.onlyAccessesArgPointees()) {
309 if (!Call2B.doesAccessArgPointees())
312 for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) {
313 const Value *Arg = *I;
314 if (!Arg->getType()->isPointerTy())
315 continue;
316 unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I);
317 auto Call2ArgLoc =
318 MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI);
319
320 // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the
321 // dependence of Call1 on that location is the inverse:
322 // - If Call2 modifies location, dependence exists if Call1 reads or
323 // writes.
324 // - If Call2 only reads location, dependence exists if Call1 writes.
325 ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx);
327 if (isModSet(ArgModRefC2))
328 ArgMask = ModRefInfo::ModRef;
329 else if (isRefSet(ArgModRefC2))
330 ArgMask = ModRefInfo::Mod;
331
332 // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use
333 // above ArgMask to update dependence info.
334 ArgMask &= getModRefInfo(Call1, Call2ArgLoc, AAQI);
335
336 R = (R | ArgMask) & Result;
337 if (R == Result)
338 break;
339 }
340
341 return R;
342 }
343
344 // If Call1 only accesses memory through arguments, check if Call2 references
345 // any of the memory referenced by Call1's arguments. If not, return NoModRef.
346 if (Call1B.onlyAccessesArgPointees()) {
347 if (!Call1B.doesAccessArgPointees())
350 for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) {
351 const Value *Arg = *I;
352 if (!Arg->getType()->isPointerTy())
353 continue;
354 unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I);
355 auto Call1ArgLoc =
356 MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI);
357
358 // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1
359 // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by
360 // Call2. If Call1 might Ref, then we care only about a Mod by Call2.
361 ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx);
362 ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc, AAQI);
363 if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) ||
364 (isRefSet(ArgModRefC1) && isModSet(ModRefC2)))
365 R = (R | ArgModRefC1) & Result;
366
367 if (R == Result)
368 break;
369 }
370
371 return R;
372 }
373
374 // If only Inaccessible and Target Memory Location have set ModRefInfo
375 // then check the relation between the same locations.
376 if (Call1B.onlyAccessesInaccessibleOrTargetMem() &&
377 Call2B.onlyAccessesInaccessibleOrTargetMem())
378 return getModRefInfoInaccessibleAndTargetMemLoc(Call1B, Call2B);
379
380 return Result;
381}
382
384 const Instruction *I2) {
385 SimpleAAQueryInfo AAQIP(*this);
386 return getModRefInfo(I1, I2, AAQIP);
387}
388
390 const Instruction *I2, AAQueryInfo &AAQI) {
391 // Early-exit if either instruction does not read or write memory.
392 if (!I1->mayReadOrWriteMemory() || !I2->mayReadOrWriteMemory())
394
395 if (const auto *Call2 = dyn_cast<CallBase>(I2))
396 return getModRefInfo(I1, Call2, AAQI);
397
398 // FIXME: We can have a more precise result.
401}
402
404 AAQueryInfo &AAQI) {
406
407 for (const auto &AA : AAs) {
408 Result &= AA->getMemoryEffects(Call, AAQI);
409
410 // Early-exit the moment we reach the bottom of the lattice.
411 if (Result.doesNotAccessMemory())
412 return Result;
413 }
414
415 return Result;
416}
417
422
425
426 for (const auto &AA : AAs) {
427 Result &= AA->getMemoryEffects(F);
428
429 // Early-exit the moment we reach the bottom of the lattice.
430 if (Result.doesNotAccessMemory())
431 return Result;
432 }
433
434 return Result;
435}
436
438 switch (AR) {
440 OS << "NoAlias";
441 break;
443 OS << "MustAlias";
444 break;
446 OS << "MayAlias";
447 break;
449 OS << "PartialAlias";
450 if (AR.hasOffset())
451 OS << " (off " << AR.getOffset() << ")";
452 break;
453 }
454 return OS;
455}
456
457//===----------------------------------------------------------------------===//
458// Helper method implementation
459//===----------------------------------------------------------------------===//
460
462 AAQueryInfo &AAQI) {
463 if (!Loc.Ptr)
464 return ModRefInfo::ModRef;
465
466 // If the location is *never* captured, it cannot be affected by
467 // synchronizing operations. However, we cannot ignore locations that are
468 // only captured after the operation, as the synchronization may still have
469 // an effect if the object is only captured *later*. As such, set I to null
470 // and ReturnCaptures to true here.
471 const Value *Obj = getUnderlyingObject(Loc.Ptr);
473 Obj, /*I=*/nullptr, /*OrAt=*/true, /*ReturnCaptures=*/true);
474 if (capturesNothing(CC))
476
477 // If only read provenance was captured, other threads may only read the
478 // object.
479 ModRefInfo MR =
481
482 // If Loc is a constant memory location, the synchronization operation
483 // definitely could not modify it.
484 return MR & AA->getModRefInfoMask(Loc);
485}
486
488 const MemoryLocation &Loc,
489 AAQueryInfo &AAQI) {
490 // If the load address doesn't alias the given address, it doesn't read
491 // or write the specified memory.
492 if (Loc.Ptr) {
493 AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI, L);
494 if (AR == AliasResult::NoAlias) {
495 // Synchronization effects may affect locations that do not alias.
496 if (isStrongerThanMonotonic(L->getOrdering()))
497 return getSyncEffects(this, Loc, AAQI);
499 }
500 }
501
502 // Preserve the ordering requirement.
503 if (isStrongerThanUnordered(L->getOrdering()))
504 return ModRefInfo::ModRef;
505
506 // Otherwise, a load just reads.
507 return ModRefInfo::Ref;
508}
509
511 const MemoryLocation &Loc,
512 AAQueryInfo &AAQI) {
513 if (Loc.Ptr) {
514 AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI, S);
515 // If the store address cannot alias the pointer in question, then the
516 // specified memory cannot be modified by the store.
517 if (AR == AliasResult::NoAlias) {
518 // Synchronization effects may affect locations that do not alias.
520 return getSyncEffects(this, Loc, AAQI);
522 }
523
524 // Examine the ModRef mask. If Mod isn't present, then return NoModRef.
525 // This ensures that if Loc is a constant memory location, we take into
526 // account the fact that the store definitely could not modify the memory
527 // location.
530 }
531
532 // Preserve the ordering requirement.
534 return ModRefInfo::ModRef;
535
536 // Otherwise, a store just writes.
537 return ModRefInfo::Mod;
538}
539
541 const MemoryLocation &Loc,
542 AAQueryInfo &AAQI) {
543 if (Loc.Ptr) {
545
546 for (const auto &AA : AAs) {
547 Result &= AA->getModRefInfo(F, Loc, AAQI);
548
549 if (isNoModRef(Result))
551 }
552
553 return Result & getSyncEffects(this, Loc, AAQI);
554 }
555
556 return ModRefInfo::ModRef;
557}
558
560 const MemoryLocation &Loc,
561 AAQueryInfo &AAQI) {
562 if (Loc.Ptr) {
563 AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI, V);
564 // If the va_arg address cannot alias the pointer in question, then the
565 // specified memory cannot be accessed by the va_arg.
566 if (AR == AliasResult::NoAlias)
568
569 // If the pointer is a pointer to invariant memory, then it could not have
570 // been modified by this va_arg.
571 return getModRefInfoMask(Loc, AAQI);
572 }
573
574 // Otherwise, a va_arg reads and writes.
575 return ModRefInfo::ModRef;
576}
577
579 const MemoryLocation &Loc,
580 AAQueryInfo &AAQI) {
581 if (Loc.Ptr) {
582 // If the pointer is a pointer to invariant memory,
583 // then it could not have been modified by this catchpad.
584 return getModRefInfoMask(Loc, AAQI);
585 }
586
587 // Otherwise, a catchpad reads and writes.
588 return ModRefInfo::ModRef;
589}
590
592 const MemoryLocation &Loc,
593 AAQueryInfo &AAQI) {
594 if (Loc.Ptr) {
595 // If the pointer is a pointer to invariant memory,
596 // then it could not have been modified by this catchpad.
597 return getModRefInfoMask(Loc, AAQI);
598 }
599
600 // Otherwise, a catchret reads and writes.
601 return ModRefInfo::ModRef;
602}
603
605 const MemoryLocation &Loc,
606 AAQueryInfo &AAQI) {
607 if (Loc.Ptr) {
608 AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI, CX);
609 // If the cmpxchg address does not alias the location, it does not access
610 // it.
611 if (AR == AliasResult::NoAlias) {
612 // Synchronization effects may affect locations that do not alias.
614 return getSyncEffects(this, Loc, AAQI);
616 }
617 }
618
619 return ModRefInfo::ModRef;
620}
621
623 const MemoryLocation &Loc,
624 AAQueryInfo &AAQI) {
625 if (Loc.Ptr) {
626 AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI, RMW);
627 // If the atomicrmw address does not alias the location, it does not access
628 // it.
629 if (AR == AliasResult::NoAlias) {
630 // Synchronization effects may affect locations that do not alias.
632 return getSyncEffects(this, Loc, AAQI);
634 }
635 }
636
637 return ModRefInfo::ModRef;
638}
639
641 const std::optional<MemoryLocation> &OptLoc,
642 AAQueryInfo &AAQIP) {
643 if (OptLoc == std::nullopt) {
644 if (const auto *Call = dyn_cast<CallBase>(I))
645 return getMemoryEffects(Call, AAQIP).getModRef();
646 }
647
648 const MemoryLocation &Loc = OptLoc.value_or(MemoryLocation());
649
650 switch (I->getOpcode()) {
651 case Instruction::VAArg:
652 return getModRefInfo((const VAArgInst *)I, Loc, AAQIP);
653 case Instruction::Load:
654 return getModRefInfo((const LoadInst *)I, Loc, AAQIP);
655 case Instruction::Store:
656 return getModRefInfo((const StoreInst *)I, Loc, AAQIP);
657 case Instruction::Fence:
658 return getModRefInfo((const FenceInst *)I, Loc, AAQIP);
659 case Instruction::AtomicCmpXchg:
660 return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP);
661 case Instruction::AtomicRMW:
662 return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP);
663 case Instruction::Call:
664 case Instruction::CallBr:
665 case Instruction::Invoke:
666 return getModRefInfo((const CallBase *)I, Loc, AAQIP);
667 case Instruction::CatchPad:
668 return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP);
669 case Instruction::CatchRet:
670 return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP);
671 default:
672 assert(!I->mayReadOrWriteMemory() &&
673 "Unhandled memory access instruction!");
675 }
676}
677
678/// Return information about whether a particular call site modifies
679/// or reads the specified memory location \p MemLoc before instruction \p I
680/// in a BasicBlock.
681/// FIXME: this is really just shoring-up a deficiency in alias analysis.
682/// BasicAA isn't willing to spend linear time determining whether an alloca
683/// was captured before or after this particular call, while we are. However,
684/// with a smarter AA in place, this test is just wasting compile time.
686 const MemoryLocation &MemLoc,
687 DominatorTree *DT,
688 AAQueryInfo &AAQI) {
689 if (!DT)
690 return ModRefInfo::ModRef;
691
692 const Value *Object = getUnderlyingObject(MemLoc.Ptr);
693 if (!isIdentifiedFunctionLocal(Object))
694 return ModRefInfo::ModRef;
695
696 const auto *Call = dyn_cast<CallBase>(I);
697 if (!Call || Call == Object)
698 return ModRefInfo::ModRef;
699
701 Object, /* ReturnCaptures */ true, I, DT,
702 /* include Object */ true, CaptureComponents::Provenance)))
703 return ModRefInfo::ModRef;
704
705 unsigned ArgNo = 0;
707 // Set flag only if no May found and all operands processed.
708 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
709 CI != CE; ++CI, ++ArgNo) {
710 // Only look at the no-capture or byval pointer arguments. If this
711 // pointer were passed to arguments that were neither of these, then it
712 // couldn't be no-capture.
713 if (!(*CI)->getType()->isPointerTy())
714 continue;
715
716 // Make sure we still check captures(ret: address, provenance) and
717 // captures(address) arguments, as these wouldn't be treated as a capture
718 // at the call-site.
719 CaptureInfo Captures = Call->getCaptureInfo(ArgNo);
721 continue;
722
723 AliasResult AR =
726 // If this is a no-capture pointer argument, see if we can tell that it
727 // is impossible to alias the pointer we're checking. If not, we have to
728 // assume that the call could touch the pointer, even though it doesn't
729 // escape.
730 if (AR == AliasResult::NoAlias)
731 continue;
732 if (Call->doesNotAccessMemory(ArgNo))
733 continue;
734 if (Call->onlyReadsMemory(ArgNo)) {
735 R = ModRefInfo::Ref;
736 continue;
737 }
738 return ModRefInfo::ModRef;
739 }
740 return R;
741}
742
743/// canBasicBlockModify - Return true if it is possible for execution of the
744/// specified basic block to modify the location Loc.
745///
750
751/// canInstructionRangeModRef - Return true if it is possible for the
752/// execution of the specified instructions to mod\ref (according to the
753/// mode) the location Loc. The instructions to consider are all
754/// of the instructions in the range of [I1,I2] INCLUSIVE.
755/// I1 and I2 must be in the same basic block.
757 const Instruction &I2,
758 const MemoryLocation &Loc,
759 const ModRefInfo Mode) {
760 assert(I1.getParent() == I2.getParent() &&
761 "Instructions not in same basic block!");
762 BasicBlock::const_iterator I = I1.getIterator();
764 ++E; // Convert from inclusive to exclusive range.
765
766 for (; I != E; ++I) // Check every instruction in range
767 if (isModOrRefSet(getModRefInfo(&*I, Loc) & Mode))
768 return true;
769 return false;
770}
771
772// Provide a definition for the root virtual destructor.
774
775// Provide a definition for the static object used to identify passes.
776AnalysisKey AAManager::Key;
777
779
782
784
785INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis",
786 false, true)
787
790 return new ExternalAAWrapperPass(std::move(Callback));
791}
792
794
796
798 "Function Alias Analysis Results", false, true)
806 "Function Alias Analysis Results", false, true)
807
808/// Run the wrapper pass to rebuild an aggregation over known AA passes.
809///
810/// This is the legacy pass manager's interface to the new-style AA results
811/// aggregation object. Because this is somewhat shoe-horned into the legacy
812/// pass manager, we hard code all the specific alias analyses available into
813/// it. While the particular set enabled is configured via commandline flags,
814/// adding a new alias analysis to LLVM will require adding support for it to
815/// this list.
817 // NB! This *must* be reset before adding new AA results to the new
818 // AAResults object because in the legacy pass manager, each instance
819 // of these will refer to the *same* immutable analyses, registering and
820 // unregistering themselves with them. We need to carefully tear down the
821 // previous object first, in this case replacing it with an empty one, before
822 // registering new results.
823 AAR.reset(
825
826 // Add any target-specific alias analyses that should be run early.
827 auto *ExtWrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>();
828 if (ExtWrapperPass && ExtWrapperPass->RunEarly && ExtWrapperPass->CB) {
829 LLVM_DEBUG(dbgs() << "AAResults register Early ExternalAA: "
830 << ExtWrapperPass->getPassName() << "\n");
831 ExtWrapperPass->CB(*this, F, *AAR);
832 }
833
834 // BasicAA is always available for function analyses. Also, we add it first
835 // so that it can trump TBAA results when it proves MustAlias.
836 // FIXME: TBAA should have an explicit mode to support this and then we
837 // should reconsider the ordering here.
838 if (!DisableBasicAA) {
839 LLVM_DEBUG(dbgs() << "AAResults register BasicAA\n");
840 AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult());
841 }
842
843 // Populate the results with the currently available AAs.
844 if (auto *WrapperPass =
846 LLVM_DEBUG(dbgs() << "AAResults register ScopedNoAliasAA\n");
847 AAR->addAAResult(WrapperPass->getResult());
848 }
849 if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) {
850 LLVM_DEBUG(dbgs() << "AAResults register TypeBasedAA\n");
851 AAR->addAAResult(WrapperPass->getResult());
852 }
853 if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>()) {
854 LLVM_DEBUG(dbgs() << "AAResults register GlobalsAA\n");
855 AAR->addAAResult(WrapperPass->getResult());
856 }
857 if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>()) {
858 LLVM_DEBUG(dbgs() << "AAResults register SCEVAA\n");
859 AAR->addAAResult(WrapperPass->getResult());
860 }
861
862 // If available, run an external AA providing callback over the results as
863 // well.
864 if (ExtWrapperPass && !ExtWrapperPass->RunEarly && ExtWrapperPass->CB) {
865 LLVM_DEBUG(dbgs() << "AAResults register Late ExternalAA: "
866 << ExtWrapperPass->getPassName() << "\n");
867 ExtWrapperPass->CB(*this, F, *AAR);
868 }
869
870 // Analyses don't mutate the IR, so return false.
871 return false;
872}
873
875 AU.setPreservesAll();
878
879 // We also need to mark all the alias analysis passes we will potentially
880 // probe in runOnFunction as used here to ensure the legacy pass manager
881 // preserves them. This hard coding of lists of alias analyses is specific to
882 // the legacy pass manager.
888}
889
892 for (auto &Getter : ResultGetters)
893 (*Getter)(F, AM, R);
894 return R;
895}
896
898 if (const auto *Call = dyn_cast<CallBase>(V))
899 return Call->hasRetAttr(Attribute::NoAlias);
900 return false;
901}
902
903static bool isNoAliasOrByValArgument(const Value *V) {
904 if (const Argument *A = dyn_cast<Argument>(V))
905 return A->hasNoAliasAttr() || A->hasByValAttr();
906 return false;
907}
908
910 if (isa<AllocaInst>(V))
911 return true;
913 return true;
914 if (isNoAliasCall(V))
915 return true;
917 return true;
918 return false;
919}
920
924
926 // TODO: We can handle other cases here
927 // 1) For GC languages, arguments to functions are often required to be
928 // base pointers.
929 // 2) Result of allocation routines are often base pointers. Leverage TLI.
930 return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));
931}
932
934 if (auto *CB = dyn_cast<CallBase>(V)) {
936 CB, /*MustPreserveOffset=*/false))
937 return false;
938
939 // The return value of a function with a captures(ret: address, provenance)
940 // attribute is not necessarily an escape source. The return value may
941 // alias with a non-escaping object.
942 return !CB->hasArgumentWithAdditionalReturnCaptureComponents();
943 }
944
945 // The load case works because isNotCapturedBefore considers all
946 // stores to be escapes (it passes true for the StoreCaptures argument
947 // to PointerMayBeCaptured).
948 if (isa<LoadInst>(V))
949 return true;
950
951 // The inttoptr case works because isNotCapturedBefore considers all
952 // means of converting or equating a pointer to an int (ptrtoint, ptr store
953 // which could be followed by an integer load, ptr<->int compare) as
954 // escaping, and objects located at well-known addresses via platform-specific
955 // means cannot be considered non-escaping local objects.
956 if (isa<IntToPtrInst>(V))
957 return true;
958
959 // Capture tracking considers insertions into aggregates and vectors as
960 // captures. As such, extractions from aggregates and vectors are escape
961 // sources.
963 return true;
964
965 // Same for inttoptr constant expressions.
966 if (auto *CE = dyn_cast<ConstantExpr>(V))
967 if (CE->getOpcode() == Instruction::IntToPtr)
968 return true;
969
970 return false;
971}
972
974 bool &RequiresNoCaptureBeforeUnwind) {
975 RequiresNoCaptureBeforeUnwind = false;
976
977 // Alloca goes out of scope on unwind.
978 if (isa<AllocaInst>(Object))
979 return true;
980
981 // Byval goes out of scope on unwind.
982 if (auto *A = dyn_cast<Argument>(Object))
983 return A->hasByValAttr() || A->hasAttribute(Attribute::DeadOnUnwind);
984
985 // A noalias return is not accessible from any other code. If the pointer
986 // does not escape prior to the unwind, then the caller cannot access the
987 // memory either.
988 if (isNoAliasCall(Object)) {
989 RequiresNoCaptureBeforeUnwind = true;
990 return true;
991 }
992
993 return false;
994}
995
996// We don't consider globals as writable: While the physical memory is writable,
997// we may not have provenance to perform the write.
998bool llvm::isWritableObject(const Value *Object,
999 bool &ExplicitlyDereferenceableOnly) {
1000 ExplicitlyDereferenceableOnly = false;
1001
1002 // TODO: Alloca might not be writable after its lifetime ends.
1003 // See https://github.com/llvm/llvm-project/issues/51838.
1004 if (isa<AllocaInst>(Object))
1005 return true;
1006
1007 if (auto *A = dyn_cast<Argument>(Object)) {
1008 // Also require noalias, otherwise writability at function entry cannot be
1009 // generalized to writability at other program points, even if the pointer
1010 // does not escape.
1011 if (A->hasAttribute(Attribute::Writable) && A->hasNoAliasAttr()) {
1012 ExplicitlyDereferenceableOnly = true;
1013 return true;
1014 }
1015
1016 return A->hasByValAttr();
1017 }
1018
1019 // TODO: Noalias shouldn't imply writability, this should check for an
1020 // allocator function instead.
1021 return isNoAliasCall(Object);
1022}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ModRefInfo getModRefInfoInaccessibleAndTargetMemLoc(const MemoryEffects CallUse, const MemoryEffects CallDef)
static cl::opt< bool > EnableAATrace("aa-trace", cl::Hidden, cl::init(false))
Print a trace of alias analysis queries and their results.
static bool isNoAliasOrByValArgument(const Value *V)
static cl::opt< bool > DisableBasicAA("disable-basic-aa", cl::Hidden, cl::init(false))
Allow disabling BasicAA from the AA results.
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This is the interface for a simple mod/ref and alias analysis over globals.
#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.
#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
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This is the interface for a SCEV-based alias analysis.
This is the interface for a metadata-based scoped no-alias analysis.
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
#define LLVM_DEBUG(...)
Definition Debug.h:119
This is the interface for a metadata-based TBAA.
A manager for alias analyses.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
This class stores info we want to provide to or retain within an alias query.
unsigned Depth
Query depth used to distinguish recursive queries.
CaptureAnalysis * CA
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
bool runOnFunction(Function &F) override
Run the wrapper pass to rebuild an aggregation over known AA passes.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
ModRefInfo callCapturesBefore(const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT)
Return information about whether a particular call site modifies or reads the specified memory locati...
LLVM_ABI AAResults(const TargetLibraryInfo &TLI)
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
LLVM_ABI ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx)
Get the ModRef info associated with a pointer argument of a call.
LLVM_ABI bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, const MemoryLocation &Loc, const ModRefInfo Mode)
Check if it is possible for the execution of the specified instructions to mod(according to the mode)...
LLVM_ABI AliasResult aliasErrno(const MemoryLocation &Loc, const Module *M)
LLVM_ABI ~AAResults()
LLVM_ABI bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc)
Check if it is possible for execution of the specified basic block to modify the location Loc.
The possible results of an alias query.
@ 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.
constexpr int32_t getOffset() const
constexpr bool hasOffset() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this 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
An instruction that atomically checks whether a specified value is in a memory location,...
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
an instruction that atomically reads a memory location, combines it with another value,...
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
Legacy wrapper pass to provide the BasicAAResult object.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction & back() const
Definition BasicBlock.h:486
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
const Instruction & front() const
Definition BasicBlock.h:484
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Represents which components of the pointer may be captured in which location.
Definition ModRef.h:414
CaptureComponents getOtherComponents() const
Get components potentially captured through locations other than the return value.
Definition ModRef.h:446
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
An instruction for ordering other memory operations.
FunctionPass(char &pid)
Definition Pass.h:316
Legacy wrapper pass to provide the GlobalsAAResult object.
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:285
ImmutablePass(char &pid)
Definition Pass.h:287
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
An instruction for reading from memory.
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
Definition ModRef.h:219
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
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 std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Legacy wrapper pass to provide the SCEVAAResult object.
Legacy wrapper pass to provide the ScopedNoAliasAAResult object.
AAQueryInfo that uses SimpleCaptureAnalysis.
An instruction for storing to memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Legacy wrapper pass to provide the TypeBasedAAResult object.
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:165
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
bool capturesReadProvenanceOnly(CaptureComponents CC)
Definition ModRef.h:391
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isStrongerThanMonotonic(AtomicOrdering AO)
LLVM_ABI bool isBaseOfObject(const Value *V)
Return true if we know V to the base address of the corresponding memory object.
bool isStrongerThanUnordered(AtomicOrdering AO)
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, const Instruction *I, const DominatorTree *DT, bool IncludeI=false, unsigned MaxUsesToExplore=0, const LoopInfo *LI=nullptr)
PointerMayBeCapturedBefore - Return true if this pointer value may be captured by the enclosing funct...
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 raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
LLVM_ABI bool isNotVisibleOnUnwind(const Value *Object, bool &RequiresNoCaptureBeforeUnwind)
Return true if Object memory is not visible after an unwind, in the sense that program semantics cann...
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
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
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
IRMemLocation
The locations at which a function might access memory.
Definition ModRef.h:60
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
LLVM_ABI bool isEscapeSource(const Value *V)
Returns true if the pointer is one which would have been considered an escape by isNotCapturedBefore.
bool capturesAnything(CaptureComponents CC)
Definition ModRef.h:379
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool capturesAnyProvenance(CaptureComponents CC)
Definition ModRef.h:400
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI ImmutablePass * createExternalAAWrapperPass(std::function< void(Pass &, Function &, AAResults &)> Callback)
A wrapper pass around a callback which can be used to populate the AAResults in the AAResultsWrapperP...
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:860
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.
A wrapper pass for external alias analyses.
std::function< void(Pass &, Function &, AAResults &)> CallbackT
static LLVM_ABI char ID
bool RunEarly
Flag indicating whether this external AA should run before Basic AA.