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
79
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
152 bool IgnoreLocals) {
153 SimpleAAQueryInfo AAQIP(*this);
154 return getModRefInfoMask(Loc, AAQIP, IgnoreLocals);
155}
156
158 AAQueryInfo &AAQI, bool IgnoreLocals) {
160
161 for (const auto &AA : AAs) {
162 Result &= AA->getModRefInfoMask(Loc, AAQI, IgnoreLocals);
163
164 // Early-exit the moment we reach the bottom of the lattice.
165 if (isNoModRef(Result))
167 }
168
169 return Result;
170}
171
172ModRefInfo AAResults::getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
174
175 for (const auto &AA : AAs) {
176 Result &= AA->getArgModRefInfo(Call, ArgIdx);
177
178 // Early-exit the moment we reach the bottom of the lattice.
179 if (isNoModRef(Result))
181 }
182
183 return Result;
184}
185
187 const CallBase *Call2) {
188 SimpleAAQueryInfo AAQIP(*this);
189 return getModRefInfo(I, Call2, AAQIP);
190}
191
193 AAQueryInfo &AAQI) {
194 // We may have two calls.
195 if (const auto *Call1 = dyn_cast<CallBase>(I)) {
196 // Check if the two calls modify the same memory.
197 return getModRefInfo(Call1, Call2, AAQI);
198 }
199 // If this is a fence, just return ModRef.
200 if (I->isFenceLike())
201 return ModRefInfo::ModRef;
202 // Otherwise, check if the call modifies or references the
203 // location this memory access defines. The best we can say
204 // is that if the call references what this instruction
205 // defines, it must be clobbered by this location.
206 const MemoryLocation DefLoc = MemoryLocation::get(I);
207 ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI);
208 if (isModOrRefSet(MR))
209 return ModRefInfo::ModRef;
211}
212
214 const MemoryLocation &Loc,
215 AAQueryInfo &AAQI) {
217
218 for (const auto &AA : AAs) {
219 Result &= AA->getModRefInfo(Call, Loc, AAQI);
220
221 // Early-exit the moment we reach the bottom of the lattice.
222 if (isNoModRef(Result))
224 }
225
226 // Apply the ModRef mask. This ensures that if Loc is a constant memory
227 // location, we take into account the fact that the call definitely could not
228 // modify the memory location.
229 if (!isNoModRef(Result))
230 Result &= getModRefInfoMask(Loc);
231
232 return Result;
233}
234
236 const CallBase *Call2, AAQueryInfo &AAQI) {
238
239 for (const auto &AA : AAs) {
240 Result &= AA->getModRefInfo(Call1, Call2, AAQI);
241
242 // Early-exit the moment we reach the bottom of the lattice.
243 if (isNoModRef(Result))
245 }
246
247 // Try to refine the mod-ref info further using other API entry points to the
248 // aggregate set of AA results.
249
250 // If Call1 or Call2 are readnone, they don't interact.
251 auto Call1B = getMemoryEffects(Call1, AAQI);
252 if (Call1B.doesNotAccessMemory())
254
255 auto Call2B = getMemoryEffects(Call2, AAQI);
256 if (Call2B.doesNotAccessMemory())
258
259 // If they both only read from memory, there is no dependence.
260 if (Call1B.onlyReadsMemory() && Call2B.onlyReadsMemory())
262
263 // If Call1 only reads memory, the only dependence on Call2 can be
264 // from Call1 reading memory written by Call2.
265 if (Call1B.onlyReadsMemory())
266 Result &= ModRefInfo::Ref;
267 else if (Call1B.onlyWritesMemory())
268 Result &= ModRefInfo::Mod;
269
270 // If Call2 only access memory through arguments, accumulate the mod/ref
271 // information from Call1's references to the memory referenced by
272 // Call2's arguments.
273 if (Call2B.onlyAccessesArgPointees()) {
274 if (!Call2B.doesAccessArgPointees())
277 for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) {
278 const Value *Arg = *I;
279 if (!Arg->getType()->isPointerTy())
280 continue;
281 unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I);
282 auto Call2ArgLoc =
283 MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI);
284
285 // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the
286 // dependence of Call1 on that location is the inverse:
287 // - If Call2 modifies location, dependence exists if Call1 reads or
288 // writes.
289 // - If Call2 only reads location, dependence exists if Call1 writes.
290 ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx);
292 if (isModSet(ArgModRefC2))
293 ArgMask = ModRefInfo::ModRef;
294 else if (isRefSet(ArgModRefC2))
295 ArgMask = ModRefInfo::Mod;
296
297 // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use
298 // above ArgMask to update dependence info.
299 ArgMask &= getModRefInfo(Call1, Call2ArgLoc, AAQI);
300
301 R = (R | ArgMask) & Result;
302 if (R == Result)
303 break;
304 }
305
306 return R;
307 }
308
309 // If Call1 only accesses memory through arguments, check if Call2 references
310 // any of the memory referenced by Call1's arguments. If not, return NoModRef.
311 if (Call1B.onlyAccessesArgPointees()) {
312 if (!Call1B.doesAccessArgPointees())
315 for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) {
316 const Value *Arg = *I;
317 if (!Arg->getType()->isPointerTy())
318 continue;
319 unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I);
320 auto Call1ArgLoc =
321 MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI);
322
323 // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1
324 // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by
325 // Call2. If Call1 might Ref, then we care only about a Mod by Call2.
326 ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx);
327 ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc, AAQI);
328 if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) ||
329 (isRefSet(ArgModRefC1) && isModSet(ModRefC2)))
330 R = (R | ArgModRefC1) & Result;
331
332 if (R == Result)
333 break;
334 }
335
336 return R;
337 }
338
339 return Result;
340}
341
343 const Instruction *I2) {
344 SimpleAAQueryInfo AAQIP(*this);
345 return getModRefInfo(I1, I2, AAQIP);
346}
347
349 const Instruction *I2, AAQueryInfo &AAQI) {
350 // Early-exit if either instruction does not read or write memory.
351 if (!I1->mayReadOrWriteMemory() || !I2->mayReadOrWriteMemory())
353
354 if (const auto *Call2 = dyn_cast<CallBase>(I2))
355 return getModRefInfo(I1, Call2, AAQI);
356
357 // FIXME: We can have a more precise result.
360}
361
363 AAQueryInfo &AAQI) {
365
366 for (const auto &AA : AAs) {
367 Result &= AA->getMemoryEffects(Call, AAQI);
368
369 // Early-exit the moment we reach the bottom of the lattice.
370 if (Result.doesNotAccessMemory())
371 return Result;
372 }
373
374 return Result;
375}
376
378 SimpleAAQueryInfo AAQI(*this);
379 return getMemoryEffects(Call, AAQI);
380}
381
384
385 for (const auto &AA : AAs) {
386 Result &= AA->getMemoryEffects(F);
387
388 // Early-exit the moment we reach the bottom of the lattice.
389 if (Result.doesNotAccessMemory())
390 return Result;
391 }
392
393 return Result;
394}
395
397 switch (AR) {
399 OS << "NoAlias";
400 break;
402 OS << "MustAlias";
403 break;
405 OS << "MayAlias";
406 break;
408 OS << "PartialAlias";
409 if (AR.hasOffset())
410 OS << " (off " << AR.getOffset() << ")";
411 break;
412 }
413 return OS;
414}
415
416//===----------------------------------------------------------------------===//
417// Helper method implementation
418//===----------------------------------------------------------------------===//
419
421 const MemoryLocation &Loc,
422 AAQueryInfo &AAQI) {
423 // Be conservative in the face of atomic.
424 if (isStrongerThan(L->getOrdering(), AtomicOrdering::Unordered))
425 return ModRefInfo::ModRef;
426
427 // If the load address doesn't alias the given address, it doesn't read
428 // or write the specified memory.
429 if (Loc.Ptr) {
430 AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI, L);
431 if (AR == AliasResult::NoAlias)
433 }
434 // Otherwise, a load just reads.
435 return ModRefInfo::Ref;
436}
437
439 const MemoryLocation &Loc,
440 AAQueryInfo &AAQI) {
441 // Be conservative in the face of atomic.
443 return ModRefInfo::ModRef;
444
445 if (Loc.Ptr) {
446 AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI, S);
447 // If the store address cannot alias the pointer in question, then the
448 // specified memory cannot be modified by the store.
449 if (AR == AliasResult::NoAlias)
451
452 // Examine the ModRef mask. If Mod isn't present, then return NoModRef.
453 // This ensures that if Loc is a constant memory location, we take into
454 // account the fact that the store definitely could not modify the memory
455 // location.
456 if (!isModSet(getModRefInfoMask(Loc)))
458 }
459
460 // Otherwise, a store just writes.
461 return ModRefInfo::Mod;
462}
463
465 const MemoryLocation &Loc,
466 AAQueryInfo &AAQI) {
467 // All we know about a fence instruction is what we get from the ModRef
468 // mask: if Loc is a constant memory location, the fence definitely could
469 // not modify it.
470 if (Loc.Ptr)
471 return getModRefInfoMask(Loc);
472 return ModRefInfo::ModRef;
473}
474
476 const MemoryLocation &Loc,
477 AAQueryInfo &AAQI) {
478 if (Loc.Ptr) {
479 AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI, V);
480 // If the va_arg address cannot alias the pointer in question, then the
481 // specified memory cannot be accessed by the va_arg.
482 if (AR == AliasResult::NoAlias)
484
485 // If the pointer is a pointer to invariant memory, then it could not have
486 // been modified by this va_arg.
487 return getModRefInfoMask(Loc, AAQI);
488 }
489
490 // Otherwise, a va_arg reads and writes.
491 return ModRefInfo::ModRef;
492}
493
495 const MemoryLocation &Loc,
496 AAQueryInfo &AAQI) {
497 if (Loc.Ptr) {
498 // If the pointer is a pointer to invariant memory,
499 // then it could not have been modified by this catchpad.
500 return getModRefInfoMask(Loc, AAQI);
501 }
502
503 // Otherwise, a catchpad reads and writes.
504 return ModRefInfo::ModRef;
505}
506
508 const MemoryLocation &Loc,
509 AAQueryInfo &AAQI) {
510 if (Loc.Ptr) {
511 // If the pointer is a pointer to invariant memory,
512 // then it could not have been modified by this catchpad.
513 return getModRefInfoMask(Loc, AAQI);
514 }
515
516 // Otherwise, a catchret reads and writes.
517 return ModRefInfo::ModRef;
518}
519
521 const MemoryLocation &Loc,
522 AAQueryInfo &AAQI) {
523 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
525 return ModRefInfo::ModRef;
526
527 if (Loc.Ptr) {
528 AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI, CX);
529 // If the cmpxchg address does not alias the location, it does not access
530 // it.
531 if (AR == AliasResult::NoAlias)
533 }
534
535 return ModRefInfo::ModRef;
536}
537
539 const MemoryLocation &Loc,
540 AAQueryInfo &AAQI) {
541 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
543 return ModRefInfo::ModRef;
544
545 if (Loc.Ptr) {
546 AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI, RMW);
547 // If the atomicrmw address does not alias the location, it does not access
548 // it.
549 if (AR == AliasResult::NoAlias)
551 }
552
553 return ModRefInfo::ModRef;
554}
555
557 const std::optional<MemoryLocation> &OptLoc,
558 AAQueryInfo &AAQIP) {
559 if (OptLoc == std::nullopt) {
560 if (const auto *Call = dyn_cast<CallBase>(I))
561 return getMemoryEffects(Call, AAQIP).getModRef();
562 }
563
564 const MemoryLocation &Loc = OptLoc.value_or(MemoryLocation());
565
566 switch (I->getOpcode()) {
567 case Instruction::VAArg:
568 return getModRefInfo((const VAArgInst *)I, Loc, AAQIP);
569 case Instruction::Load:
570 return getModRefInfo((const LoadInst *)I, Loc, AAQIP);
571 case Instruction::Store:
572 return getModRefInfo((const StoreInst *)I, Loc, AAQIP);
573 case Instruction::Fence:
574 return getModRefInfo((const FenceInst *)I, Loc, AAQIP);
575 case Instruction::AtomicCmpXchg:
576 return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP);
577 case Instruction::AtomicRMW:
578 return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP);
579 case Instruction::Call:
580 case Instruction::CallBr:
581 case Instruction::Invoke:
582 return getModRefInfo((const CallBase *)I, Loc, AAQIP);
583 case Instruction::CatchPad:
584 return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP);
585 case Instruction::CatchRet:
586 return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP);
587 default:
588 assert(!I->mayReadOrWriteMemory() &&
589 "Unhandled memory access instruction!");
591 }
592}
593
594/// Return information about whether a particular call site modifies
595/// or reads the specified memory location \p MemLoc before instruction \p I
596/// in a BasicBlock.
597/// FIXME: this is really just shoring-up a deficiency in alias analysis.
598/// BasicAA isn't willing to spend linear time determining whether an alloca
599/// was captured before or after this particular call, while we are. However,
600/// with a smarter AA in place, this test is just wasting compile time.
602 const MemoryLocation &MemLoc,
603 DominatorTree *DT,
604 AAQueryInfo &AAQI) {
605 if (!DT)
606 return ModRefInfo::ModRef;
607
608 const Value *Object = getUnderlyingObject(MemLoc.Ptr);
609 if (!isIdentifiedFunctionLocal(Object))
610 return ModRefInfo::ModRef;
611
612 const auto *Call = dyn_cast<CallBase>(I);
613 if (!Call || Call == Object)
614 return ModRefInfo::ModRef;
615
617 Object, /* ReturnCaptures */ true, I, DT,
618 /* include Object */ true, CaptureComponents::Provenance)))
619 return ModRefInfo::ModRef;
620
621 unsigned ArgNo = 0;
623 // Set flag only if no May found and all operands processed.
624 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
625 CI != CE; ++CI, ++ArgNo) {
626 // Only look at the no-capture or byval pointer arguments. If this
627 // pointer were passed to arguments that were neither of these, then it
628 // couldn't be no-capture.
629 if (!(*CI)->getType()->isPointerTy())
630 continue;
631
632 // Make sure we still check captures(ret: address, provenance) and
633 // captures(address) arguments, as these wouldn't be treated as a capture
634 // at the call-site.
635 CaptureInfo Captures = Call->getCaptureInfo(ArgNo);
637 continue;
638
639 AliasResult AR =
641 MemoryLocation::getBeforeOrAfter(Object), AAQI, Call);
642 // If this is a no-capture pointer argument, see if we can tell that it
643 // is impossible to alias the pointer we're checking. If not, we have to
644 // assume that the call could touch the pointer, even though it doesn't
645 // escape.
646 if (AR == AliasResult::NoAlias)
647 continue;
648 if (Call->doesNotAccessMemory(ArgNo))
649 continue;
650 if (Call->onlyReadsMemory(ArgNo)) {
651 R = ModRefInfo::Ref;
652 continue;
653 }
654 return ModRefInfo::ModRef;
655 }
656 return R;
657}
658
659/// canBasicBlockModify - Return true if it is possible for execution of the
660/// specified basic block to modify the location Loc.
661///
663 const MemoryLocation &Loc) {
664 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, ModRefInfo::Mod);
665}
666
667/// canInstructionRangeModRef - Return true if it is possible for the
668/// execution of the specified instructions to mod\ref (according to the
669/// mode) the location Loc. The instructions to consider are all
670/// of the instructions in the range of [I1,I2] INCLUSIVE.
671/// I1 and I2 must be in the same basic block.
673 const Instruction &I2,
674 const MemoryLocation &Loc,
675 const ModRefInfo Mode) {
676 assert(I1.getParent() == I2.getParent() &&
677 "Instructions not in same basic block!");
678 BasicBlock::const_iterator I = I1.getIterator();
680 ++E; // Convert from inclusive to exclusive range.
681
682 for (; I != E; ++I) // Check every instruction in range
683 if (isModOrRefSet(getModRefInfo(&*I, Loc) & Mode))
684 return true;
685 return false;
686}
687
688// Provide a definition for the root virtual destructor.
689AAResults::Concept::~Concept() = default;
690
691// Provide a definition for the static object used to identify passes.
692AnalysisKey AAManager::Key;
693
695
697 : ImmutablePass(ID), CB(std::move(CB)), RunEarly(RunEarly) {}
698
700
701INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis",
702 false, true)
703
706 return new ExternalAAWrapperPass(std::move(Callback));
707}
708
710
712
714 "Function Alias Analysis Results", false, true)
723
724/// Run the wrapper pass to rebuild an aggregation over known AA passes.
725///
726/// This is the legacy pass manager's interface to the new-style AA results
727/// aggregation object. Because this is somewhat shoe-horned into the legacy
728/// pass manager, we hard code all the specific alias analyses available into
729/// it. While the particular set enabled is configured via commandline flags,
730/// adding a new alias analysis to LLVM will require adding support for it to
731/// this list.
733 // NB! This *must* be reset before adding new AA results to the new
734 // AAResults object because in the legacy pass manager, each instance
735 // of these will refer to the *same* immutable analyses, registering and
736 // unregistering themselves with them. We need to carefully tear down the
737 // previous object first, in this case replacing it with an empty one, before
738 // registering new results.
739 AAR.reset(
740 new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F)));
741
742 // Add any target-specific alias analyses that should be run early.
743 auto *ExtWrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>();
744 if (ExtWrapperPass && ExtWrapperPass->RunEarly && ExtWrapperPass->CB) {
745 LLVM_DEBUG(dbgs() << "AAResults register Early ExternalAA: "
746 << ExtWrapperPass->getPassName() << "\n");
747 ExtWrapperPass->CB(*this, F, *AAR);
748 }
749
750 // BasicAA is always available for function analyses. Also, we add it first
751 // so that it can trump TBAA results when it proves MustAlias.
752 // FIXME: TBAA should have an explicit mode to support this and then we
753 // should reconsider the ordering here.
754 if (!DisableBasicAA) {
755 LLVM_DEBUG(dbgs() << "AAResults register BasicAA\n");
756 AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult());
757 }
758
759 // Populate the results with the currently available AAs.
760 if (auto *WrapperPass =
761 getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>()) {
762 LLVM_DEBUG(dbgs() << "AAResults register ScopedNoAliasAA\n");
763 AAR->addAAResult(WrapperPass->getResult());
764 }
765 if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) {
766 LLVM_DEBUG(dbgs() << "AAResults register TypeBasedAA\n");
767 AAR->addAAResult(WrapperPass->getResult());
768 }
769 if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>()) {
770 LLVM_DEBUG(dbgs() << "AAResults register GlobalsAA\n");
771 AAR->addAAResult(WrapperPass->getResult());
772 }
773 if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>()) {
774 LLVM_DEBUG(dbgs() << "AAResults register SCEVAA\n");
775 AAR->addAAResult(WrapperPass->getResult());
776 }
777
778 // If available, run an external AA providing callback over the results as
779 // well.
780 if (ExtWrapperPass && !ExtWrapperPass->RunEarly && ExtWrapperPass->CB) {
781 LLVM_DEBUG(dbgs() << "AAResults register Late ExternalAA: "
782 << ExtWrapperPass->getPassName() << "\n");
783 ExtWrapperPass->CB(*this, F, *AAR);
784 }
785
786 // Analyses don't mutate the IR, so return false.
787 return false;
788}
789
791 AU.setPreservesAll();
794
795 // We also need to mark all the alias analysis passes we will potentially
796 // probe in runOnFunction as used here to ensure the legacy pass manager
797 // preserves them. This hard coding of lists of alias analyses is specific to
798 // the legacy pass manager.
804}
805
808 for (auto &Getter : ResultGetters)
809 (*Getter)(F, AM, R);
810 return R;
811}
812
814 if (const auto *Call = dyn_cast<CallBase>(V))
815 return Call->hasRetAttr(Attribute::NoAlias);
816 return false;
817}
818
819static bool isNoAliasOrByValArgument(const Value *V) {
820 if (const Argument *A = dyn_cast<Argument>(V))
821 return A->hasNoAliasAttr() || A->hasByValAttr();
822 return false;
823}
824
826 if (isa<AllocaInst>(V))
827 return true;
828 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
829 return true;
830 if (isNoAliasCall(V))
831 return true;
833 return true;
834 return false;
835}
836
838 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasOrByValArgument(V);
839}
840
842 // TODO: We can handle other cases here
843 // 1) For GC languages, arguments to functions are often required to be
844 // base pointers.
845 // 2) Result of allocation routines are often base pointers. Leverage TLI.
846 return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));
847}
848
850 if (auto *CB = dyn_cast<CallBase>(V)) {
852 return false;
853
854 // The return value of a function with a captures(ret: address, provenance)
855 // attribute is not necessarily an escape source. The return value may
856 // alias with a non-escaping object.
857 return !CB->hasArgumentWithAdditionalReturnCaptureComponents();
858 }
859
860 // The load case works because isNotCapturedBefore considers all
861 // stores to be escapes (it passes true for the StoreCaptures argument
862 // to PointerMayBeCaptured).
863 if (isa<LoadInst>(V))
864 return true;
865
866 // The inttoptr case works because isNotCapturedBefore considers all
867 // means of converting or equating a pointer to an int (ptrtoint, ptr store
868 // which could be followed by an integer load, ptr<->int compare) as
869 // escaping, and objects located at well-known addresses via platform-specific
870 // means cannot be considered non-escaping local objects.
871 if (isa<IntToPtrInst>(V))
872 return true;
873
874 // Capture tracking considers insertions into aggregates and vectors as
875 // captures. As such, extractions from aggregates and vectors are escape
876 // sources.
877 if (isa<ExtractValueInst, ExtractElementInst>(V))
878 return true;
879
880 // Same for inttoptr constant expressions.
881 if (auto *CE = dyn_cast<ConstantExpr>(V))
882 if (CE->getOpcode() == Instruction::IntToPtr)
883 return true;
884
885 return false;
886}
887
889 bool &RequiresNoCaptureBeforeUnwind) {
890 RequiresNoCaptureBeforeUnwind = false;
891
892 // Alloca goes out of scope on unwind.
893 if (isa<AllocaInst>(Object))
894 return true;
895
896 // Byval goes out of scope on unwind.
897 if (auto *A = dyn_cast<Argument>(Object))
898 return A->hasByValAttr() || A->hasAttribute(Attribute::DeadOnUnwind);
899
900 // A noalias return is not accessible from any other code. If the pointer
901 // does not escape prior to the unwind, then the caller cannot access the
902 // memory either.
903 if (isNoAliasCall(Object)) {
904 RequiresNoCaptureBeforeUnwind = true;
905 return true;
906 }
907
908 return false;
909}
910
911// We don't consider globals as writable: While the physical memory is writable,
912// we may not have provenance to perform the write.
913bool llvm::isWritableObject(const Value *Object,
914 bool &ExplicitlyDereferenceableOnly) {
915 ExplicitlyDereferenceableOnly = false;
916
917 // TODO: Alloca might not be writable after its lifetime ends.
918 // See https://github.com/llvm/llvm-project/issues/51838.
919 if (isa<AllocaInst>(Object))
920 return true;
921
922 if (auto *A = dyn_cast<Argument>(Object)) {
923 // Also require noalias, otherwise writability at function entry cannot be
924 // generalized to writability at other program points, even if the pointer
925 // does not escape.
926 if (A->hasAttribute(Attribute::Writable) && A->hasNoAliasAttr()) {
927 ExplicitlyDereferenceableOnly = true;
928 return true;
929 }
930
931 return A->hasByValAttr();
932 }
933
934 // TODO: Noalias shouldn't imply writability, this should check for an
935 // allocator function instead.
936 return isNoAliasCall(Object);
937}
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)
Function Alias Analysis Results
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.
block Block Frequency Analysis
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
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
raw_pwrite_stream & OS
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:167
#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.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
A private abstract base class describing the concept of an individual alias analysis implementation.
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 ~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.
Definition: AliasAnalysis.h:78
@ MayAlias
The two locations may or may not alias.
Definition: AliasAnalysis.h:99
@ NoAlias
The two locations do not alias at all.
Definition: AliasAnalysis.h:96
@ 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
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:294
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
Definition: PassManager.h:312
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
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,...
Definition: Instructions.h:506
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
Definition: Instructions.h:587
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:709
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
Definition: Instructions.h:863
Legacy wrapper pass to provide the BasicAAResult object.
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:171
const Instruction & front() const
Definition: BasicBlock.h:482
const Instruction & back() const
Definition: BasicBlock.h:484
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Definition: InstrTypes.h:1267
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Definition: InstrTypes.h:1273
Represents which components of the pointer may be captured in which location.
Definition: ModRef.h:354
CaptureComponents getOtherComponents() const
Get components potentially captured through locations other than the return value.
Definition: ModRef.h:386
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
An instruction for ordering other memory operations.
Definition: Instructions.h:429
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
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
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
Definition: Instruction.h:808
An instruction for reading from memory.
Definition: Instructions.h:180
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
Definition: ModRef.h:188
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
Definition: ModRef.h:115
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 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.
Definition: Instructions.h:296
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Definition: Instructions.h:347
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:134
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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.
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
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...
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.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:312
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:1886
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:319
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:340
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...
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:856
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