LLVM 22.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
248 const CallBase *Call2, AAQueryInfo &AAQI) {
250
251 for (const auto &AA : AAs) {
252 Result &= AA->getModRefInfo(Call1, Call2, AAQI);
253
254 // Early-exit the moment we reach the bottom of the lattice.
255 if (isNoModRef(Result))
257 }
258
259 // Try to refine the mod-ref info further using other API entry points to the
260 // aggregate set of AA results.
261
262 // If Call1 or Call2 are readnone, they don't interact.
263 auto Call1B = getMemoryEffects(Call1, AAQI);
264 if (Call1B.doesNotAccessMemory())
266
267 auto Call2B = getMemoryEffects(Call2, AAQI);
268 if (Call2B.doesNotAccessMemory())
270
271 // If they both only read from memory, there is no dependence.
272 if (Call1B.onlyReadsMemory() && Call2B.onlyReadsMemory())
274
275 // If Call1 only reads memory, the only dependence on Call2 can be
276 // from Call1 reading memory written by Call2.
277 if (Call1B.onlyReadsMemory())
278 Result &= ModRefInfo::Ref;
279 else if (Call1B.onlyWritesMemory())
280 Result &= ModRefInfo::Mod;
281
282 // If Call2 only access memory through arguments, accumulate the mod/ref
283 // information from Call1's references to the memory referenced by
284 // Call2's arguments.
285 if (Call2B.onlyAccessesArgPointees()) {
286 if (!Call2B.doesAccessArgPointees())
289 for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) {
290 const Value *Arg = *I;
291 if (!Arg->getType()->isPointerTy())
292 continue;
293 unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I);
294 auto Call2ArgLoc =
295 MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI);
296
297 // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the
298 // dependence of Call1 on that location is the inverse:
299 // - If Call2 modifies location, dependence exists if Call1 reads or
300 // writes.
301 // - If Call2 only reads location, dependence exists if Call1 writes.
302 ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx);
304 if (isModSet(ArgModRefC2))
305 ArgMask = ModRefInfo::ModRef;
306 else if (isRefSet(ArgModRefC2))
307 ArgMask = ModRefInfo::Mod;
308
309 // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use
310 // above ArgMask to update dependence info.
311 ArgMask &= getModRefInfo(Call1, Call2ArgLoc, AAQI);
312
313 R = (R | ArgMask) & Result;
314 if (R == Result)
315 break;
316 }
317
318 return R;
319 }
320
321 // If Call1 only accesses memory through arguments, check if Call2 references
322 // any of the memory referenced by Call1's arguments. If not, return NoModRef.
323 if (Call1B.onlyAccessesArgPointees()) {
324 if (!Call1B.doesAccessArgPointees())
327 for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) {
328 const Value *Arg = *I;
329 if (!Arg->getType()->isPointerTy())
330 continue;
331 unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I);
332 auto Call1ArgLoc =
333 MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI);
334
335 // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1
336 // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by
337 // Call2. If Call1 might Ref, then we care only about a Mod by Call2.
338 ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx);
339 ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc, AAQI);
340 if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) ||
341 (isRefSet(ArgModRefC1) && isModSet(ModRefC2)))
342 R = (R | ArgModRefC1) & Result;
343
344 if (R == Result)
345 break;
346 }
347
348 return R;
349 }
350
351 return Result;
352}
353
355 const Instruction *I2) {
356 SimpleAAQueryInfo AAQIP(*this);
357 return getModRefInfo(I1, I2, AAQIP);
358}
359
361 const Instruction *I2, AAQueryInfo &AAQI) {
362 // Early-exit if either instruction does not read or write memory.
363 if (!I1->mayReadOrWriteMemory() || !I2->mayReadOrWriteMemory())
365
366 if (const auto *Call2 = dyn_cast<CallBase>(I2))
367 return getModRefInfo(I1, Call2, AAQI);
368
369 // FIXME: We can have a more precise result.
372}
373
375 AAQueryInfo &AAQI) {
377
378 for (const auto &AA : AAs) {
379 Result &= AA->getMemoryEffects(Call, AAQI);
380
381 // Early-exit the moment we reach the bottom of the lattice.
382 if (Result.doesNotAccessMemory())
383 return Result;
384 }
385
386 return Result;
387}
388
393
396
397 for (const auto &AA : AAs) {
398 Result &= AA->getMemoryEffects(F);
399
400 // Early-exit the moment we reach the bottom of the lattice.
401 if (Result.doesNotAccessMemory())
402 return Result;
403 }
404
405 return Result;
406}
407
409 switch (AR) {
411 OS << "NoAlias";
412 break;
414 OS << "MustAlias";
415 break;
417 OS << "MayAlias";
418 break;
420 OS << "PartialAlias";
421 if (AR.hasOffset())
422 OS << " (off " << AR.getOffset() << ")";
423 break;
424 }
425 return OS;
426}
427
428//===----------------------------------------------------------------------===//
429// Helper method implementation
430//===----------------------------------------------------------------------===//
431
433 const MemoryLocation &Loc,
434 AAQueryInfo &AAQI) {
435 // Be conservative in the face of atomic.
436 if (isStrongerThanMonotonic(L->getOrdering()))
437 return ModRefInfo::ModRef;
438
439 // If the load address doesn't alias the given address, it doesn't read
440 // or write the specified memory.
441 if (Loc.Ptr) {
442 AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI, L);
443 if (AR == AliasResult::NoAlias)
445 }
446
447 assert(!isStrongerThanMonotonic(L->getOrdering()) &&
448 "Stronger atomic orderings should have been handled above!");
449
450 if (isStrongerThanUnordered(L->getOrdering()))
451 return ModRefInfo::ModRef;
452
453 // Otherwise, a load just reads.
454 return ModRefInfo::Ref;
455}
456
458 const MemoryLocation &Loc,
459 AAQueryInfo &AAQI) {
460 // Be conservative in the face of atomic.
462 return ModRefInfo::ModRef;
463
464 if (Loc.Ptr) {
465 AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI, S);
466 // If the store address cannot alias the pointer in question, then the
467 // specified memory cannot be modified by the store.
468 if (AR == AliasResult::NoAlias)
470
471 // Examine the ModRef mask. If Mod isn't present, then return NoModRef.
472 // This ensures that if Loc is a constant memory location, we take into
473 // account the fact that the store definitely could not modify the memory
474 // location.
477 }
478
480 "Stronger atomic orderings should have been handled above!");
481
483 return ModRefInfo::ModRef;
484
485 // A store just writes.
486 return ModRefInfo::Mod;
487}
488
490 const MemoryLocation &Loc,
491 AAQueryInfo &AAQI) {
492 // All we know about a fence instruction is what we get from the ModRef
493 // mask: if Loc is a constant memory location, the fence definitely could
494 // not modify it.
495 if (Loc.Ptr)
496 return getModRefInfoMask(Loc);
497 return ModRefInfo::ModRef;
498}
499
501 const MemoryLocation &Loc,
502 AAQueryInfo &AAQI) {
503 if (Loc.Ptr) {
504 AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI, V);
505 // If the va_arg address cannot alias the pointer in question, then the
506 // specified memory cannot be accessed by the va_arg.
507 if (AR == AliasResult::NoAlias)
509
510 // If the pointer is a pointer to invariant memory, then it could not have
511 // been modified by this va_arg.
512 return getModRefInfoMask(Loc, AAQI);
513 }
514
515 // Otherwise, a va_arg reads and writes.
516 return ModRefInfo::ModRef;
517}
518
520 const MemoryLocation &Loc,
521 AAQueryInfo &AAQI) {
522 if (Loc.Ptr) {
523 // If the pointer is a pointer to invariant memory,
524 // then it could not have been modified by this catchpad.
525 return getModRefInfoMask(Loc, AAQI);
526 }
527
528 // Otherwise, a catchpad reads and writes.
529 return ModRefInfo::ModRef;
530}
531
533 const MemoryLocation &Loc,
534 AAQueryInfo &AAQI) {
535 if (Loc.Ptr) {
536 // If the pointer is a pointer to invariant memory,
537 // then it could not have been modified by this catchpad.
538 return getModRefInfoMask(Loc, AAQI);
539 }
540
541 // Otherwise, a catchret reads and writes.
542 return ModRefInfo::ModRef;
543}
544
546 const MemoryLocation &Loc,
547 AAQueryInfo &AAQI) {
548 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
550 return ModRefInfo::ModRef;
551
552 if (Loc.Ptr) {
553 AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI, CX);
554 // If the cmpxchg address does not alias the location, it does not access
555 // it.
556 if (AR == AliasResult::NoAlias)
558 }
559
560 return ModRefInfo::ModRef;
561}
562
564 const MemoryLocation &Loc,
565 AAQueryInfo &AAQI) {
566 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
568 return ModRefInfo::ModRef;
569
570 if (Loc.Ptr) {
571 AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI, RMW);
572 // If the atomicrmw address does not alias the location, it does not access
573 // it.
574 if (AR == AliasResult::NoAlias)
576 }
577
578 return ModRefInfo::ModRef;
579}
580
582 const std::optional<MemoryLocation> &OptLoc,
583 AAQueryInfo &AAQIP) {
584 if (OptLoc == std::nullopt) {
585 if (const auto *Call = dyn_cast<CallBase>(I))
586 return getMemoryEffects(Call, AAQIP).getModRef();
587 }
588
589 const MemoryLocation &Loc = OptLoc.value_or(MemoryLocation());
590
591 switch (I->getOpcode()) {
592 case Instruction::VAArg:
593 return getModRefInfo((const VAArgInst *)I, Loc, AAQIP);
594 case Instruction::Load:
595 return getModRefInfo((const LoadInst *)I, Loc, AAQIP);
596 case Instruction::Store:
597 return getModRefInfo((const StoreInst *)I, Loc, AAQIP);
598 case Instruction::Fence:
599 return getModRefInfo((const FenceInst *)I, Loc, AAQIP);
600 case Instruction::AtomicCmpXchg:
601 return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP);
602 case Instruction::AtomicRMW:
603 return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP);
604 case Instruction::Call:
605 case Instruction::CallBr:
606 case Instruction::Invoke:
607 return getModRefInfo((const CallBase *)I, Loc, AAQIP);
608 case Instruction::CatchPad:
609 return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP);
610 case Instruction::CatchRet:
611 return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP);
612 default:
613 assert(!I->mayReadOrWriteMemory() &&
614 "Unhandled memory access instruction!");
616 }
617}
618
619/// Return information about whether a particular call site modifies
620/// or reads the specified memory location \p MemLoc before instruction \p I
621/// in a BasicBlock.
622/// FIXME: this is really just shoring-up a deficiency in alias analysis.
623/// BasicAA isn't willing to spend linear time determining whether an alloca
624/// was captured before or after this particular call, while we are. However,
625/// with a smarter AA in place, this test is just wasting compile time.
627 const MemoryLocation &MemLoc,
628 DominatorTree *DT,
629 AAQueryInfo &AAQI) {
630 if (!DT)
631 return ModRefInfo::ModRef;
632
633 const Value *Object = getUnderlyingObject(MemLoc.Ptr);
634 if (!isIdentifiedFunctionLocal(Object))
635 return ModRefInfo::ModRef;
636
637 const auto *Call = dyn_cast<CallBase>(I);
638 if (!Call || Call == Object)
639 return ModRefInfo::ModRef;
640
642 Object, /* ReturnCaptures */ true, I, DT,
643 /* include Object */ true, CaptureComponents::Provenance)))
644 return ModRefInfo::ModRef;
645
646 unsigned ArgNo = 0;
648 // Set flag only if no May found and all operands processed.
649 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
650 CI != CE; ++CI, ++ArgNo) {
651 // Only look at the no-capture or byval pointer arguments. If this
652 // pointer were passed to arguments that were neither of these, then it
653 // couldn't be no-capture.
654 if (!(*CI)->getType()->isPointerTy())
655 continue;
656
657 // Make sure we still check captures(ret: address, provenance) and
658 // captures(address) arguments, as these wouldn't be treated as a capture
659 // at the call-site.
660 CaptureInfo Captures = Call->getCaptureInfo(ArgNo);
662 continue;
663
664 AliasResult AR =
667 // If this is a no-capture pointer argument, see if we can tell that it
668 // is impossible to alias the pointer we're checking. If not, we have to
669 // assume that the call could touch the pointer, even though it doesn't
670 // escape.
671 if (AR == AliasResult::NoAlias)
672 continue;
673 if (Call->doesNotAccessMemory(ArgNo))
674 continue;
675 if (Call->onlyReadsMemory(ArgNo)) {
676 R = ModRefInfo::Ref;
677 continue;
678 }
679 return ModRefInfo::ModRef;
680 }
681 return R;
682}
683
684/// canBasicBlockModify - Return true if it is possible for execution of the
685/// specified basic block to modify the location Loc.
686///
691
692/// canInstructionRangeModRef - Return true if it is possible for the
693/// execution of the specified instructions to mod\ref (according to the
694/// mode) the location Loc. The instructions to consider are all
695/// of the instructions in the range of [I1,I2] INCLUSIVE.
696/// I1 and I2 must be in the same basic block.
698 const Instruction &I2,
699 const MemoryLocation &Loc,
700 const ModRefInfo Mode) {
701 assert(I1.getParent() == I2.getParent() &&
702 "Instructions not in same basic block!");
703 BasicBlock::const_iterator I = I1.getIterator();
705 ++E; // Convert from inclusive to exclusive range.
706
707 for (; I != E; ++I) // Check every instruction in range
708 if (isModOrRefSet(getModRefInfo(&*I, Loc) & Mode))
709 return true;
710 return false;
711}
712
713// Provide a definition for the root virtual destructor.
715
716// Provide a definition for the static object used to identify passes.
717AnalysisKey AAManager::Key;
718
720
723
725
726INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis",
727 false, true)
728
731 return new ExternalAAWrapperPass(std::move(Callback));
732}
733
735
737
739 "Function Alias Analysis Results", false, true)
747 "Function Alias Analysis Results", false, true)
748
749/// Run the wrapper pass to rebuild an aggregation over known AA passes.
750///
751/// This is the legacy pass manager's interface to the new-style AA results
752/// aggregation object. Because this is somewhat shoe-horned into the legacy
753/// pass manager, we hard code all the specific alias analyses available into
754/// it. While the particular set enabled is configured via commandline flags,
755/// adding a new alias analysis to LLVM will require adding support for it to
756/// this list.
758 // NB! This *must* be reset before adding new AA results to the new
759 // AAResults object because in the legacy pass manager, each instance
760 // of these will refer to the *same* immutable analyses, registering and
761 // unregistering themselves with them. We need to carefully tear down the
762 // previous object first, in this case replacing it with an empty one, before
763 // registering new results.
764 AAR.reset(
766
767 // Add any target-specific alias analyses that should be run early.
768 auto *ExtWrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>();
769 if (ExtWrapperPass && ExtWrapperPass->RunEarly && ExtWrapperPass->CB) {
770 LLVM_DEBUG(dbgs() << "AAResults register Early ExternalAA: "
771 << ExtWrapperPass->getPassName() << "\n");
772 ExtWrapperPass->CB(*this, F, *AAR);
773 }
774
775 // BasicAA is always available for function analyses. Also, we add it first
776 // so that it can trump TBAA results when it proves MustAlias.
777 // FIXME: TBAA should have an explicit mode to support this and then we
778 // should reconsider the ordering here.
779 if (!DisableBasicAA) {
780 LLVM_DEBUG(dbgs() << "AAResults register BasicAA\n");
781 AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult());
782 }
783
784 // Populate the results with the currently available AAs.
785 if (auto *WrapperPass =
787 LLVM_DEBUG(dbgs() << "AAResults register ScopedNoAliasAA\n");
788 AAR->addAAResult(WrapperPass->getResult());
789 }
790 if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) {
791 LLVM_DEBUG(dbgs() << "AAResults register TypeBasedAA\n");
792 AAR->addAAResult(WrapperPass->getResult());
793 }
794 if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>()) {
795 LLVM_DEBUG(dbgs() << "AAResults register GlobalsAA\n");
796 AAR->addAAResult(WrapperPass->getResult());
797 }
798 if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>()) {
799 LLVM_DEBUG(dbgs() << "AAResults register SCEVAA\n");
800 AAR->addAAResult(WrapperPass->getResult());
801 }
802
803 // If available, run an external AA providing callback over the results as
804 // well.
805 if (ExtWrapperPass && !ExtWrapperPass->RunEarly && ExtWrapperPass->CB) {
806 LLVM_DEBUG(dbgs() << "AAResults register Late ExternalAA: "
807 << ExtWrapperPass->getPassName() << "\n");
808 ExtWrapperPass->CB(*this, F, *AAR);
809 }
810
811 // Analyses don't mutate the IR, so return false.
812 return false;
813}
814
816 AU.setPreservesAll();
819
820 // We also need to mark all the alias analysis passes we will potentially
821 // probe in runOnFunction as used here to ensure the legacy pass manager
822 // preserves them. This hard coding of lists of alias analyses is specific to
823 // the legacy pass manager.
829}
830
833 for (auto &Getter : ResultGetters)
834 (*Getter)(F, AM, R);
835 return R;
836}
837
839 if (const auto *Call = dyn_cast<CallBase>(V))
840 return Call->hasRetAttr(Attribute::NoAlias);
841 return false;
842}
843
844static bool isNoAliasOrByValArgument(const Value *V) {
845 if (const Argument *A = dyn_cast<Argument>(V))
846 return A->hasNoAliasAttr() || A->hasByValAttr();
847 return false;
848}
849
851 if (isa<AllocaInst>(V))
852 return true;
854 return true;
855 if (isNoAliasCall(V))
856 return true;
858 return true;
859 return false;
860}
861
865
867 // TODO: We can handle other cases here
868 // 1) For GC languages, arguments to functions are often required to be
869 // base pointers.
870 // 2) Result of allocation routines are often base pointers. Leverage TLI.
871 return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));
872}
873
875 if (auto *CB = dyn_cast<CallBase>(V)) {
877 return false;
878
879 // The return value of a function with a captures(ret: address, provenance)
880 // attribute is not necessarily an escape source. The return value may
881 // alias with a non-escaping object.
882 return !CB->hasArgumentWithAdditionalReturnCaptureComponents();
883 }
884
885 // The load case works because isNotCapturedBefore considers all
886 // stores to be escapes (it passes true for the StoreCaptures argument
887 // to PointerMayBeCaptured).
888 if (isa<LoadInst>(V))
889 return true;
890
891 // The inttoptr case works because isNotCapturedBefore considers all
892 // means of converting or equating a pointer to an int (ptrtoint, ptr store
893 // which could be followed by an integer load, ptr<->int compare) as
894 // escaping, and objects located at well-known addresses via platform-specific
895 // means cannot be considered non-escaping local objects.
896 if (isa<IntToPtrInst>(V))
897 return true;
898
899 // Capture tracking considers insertions into aggregates and vectors as
900 // captures. As such, extractions from aggregates and vectors are escape
901 // sources.
903 return true;
904
905 // Same for inttoptr constant expressions.
906 if (auto *CE = dyn_cast<ConstantExpr>(V))
907 if (CE->getOpcode() == Instruction::IntToPtr)
908 return true;
909
910 return false;
911}
912
914 bool &RequiresNoCaptureBeforeUnwind) {
915 RequiresNoCaptureBeforeUnwind = false;
916
917 // Alloca goes out of scope on unwind.
918 if (isa<AllocaInst>(Object))
919 return true;
920
921 // Byval goes out of scope on unwind.
922 if (auto *A = dyn_cast<Argument>(Object))
923 return A->hasByValAttr() || A->hasAttribute(Attribute::DeadOnUnwind);
924
925 // A noalias return is not accessible from any other code. If the pointer
926 // does not escape prior to the unwind, then the caller cannot access the
927 // memory either.
928 if (isNoAliasCall(Object)) {
929 RequiresNoCaptureBeforeUnwind = true;
930 return true;
931 }
932
933 return false;
934}
935
936// We don't consider globals as writable: While the physical memory is writable,
937// we may not have provenance to perform the write.
938bool llvm::isWritableObject(const Value *Object,
939 bool &ExplicitlyDereferenceableOnly) {
940 ExplicitlyDereferenceableOnly = false;
941
942 // TODO: Alloca might not be writable after its lifetime ends.
943 // See https://github.com/llvm/llvm-project/issues/51838.
944 if (isa<AllocaInst>(Object))
945 return true;
946
947 if (auto *A = dyn_cast<Argument>(Object)) {
948 // Also require noalias, otherwise writability at function entry cannot be
949 // generalized to writability at other program points, even if the pointer
950 // does not escape.
951 if (A->hasAttribute(Attribute::Writable) && A->hasNoAliasAttr()) {
952 ExplicitlyDereferenceableOnly = true;
953 return true;
954 }
955
956 return A->hasByValAttr();
957 }
958
959 // TODO: Noalias shouldn't imply writability, this should check for an
960 // allocator function instead.
961 return isNoAliasCall(Object);
962}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:114
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.
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:484
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
const Instruction & front() const
Definition BasicBlock.h:482
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:359
CaptureComponents getOtherComponents() const
Get components potentially captured through locations other than the return value.
Definition ModRef.h:391
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
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:193
static MemoryEffectsBase unknown()
Definition ModRef.h:120
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:267
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:256
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.
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 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:301
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 bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveNullness)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
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:207
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...
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
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:1879
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:324
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 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:345
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:867
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
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.