LLVM  10.0.0
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 
39 #include "llvm/IR/Argument.h"
40 #include "llvm/IR/Attributes.h"
41 #include "llvm/IR/BasicBlock.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/Value.h"
47 #include "llvm/InitializePasses.h"
48 #include "llvm/Pass.h"
50 #include "llvm/Support/Casting.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <functional>
55 #include <iterator>
56 
57 using namespace llvm;
58 
59 /// Allow disabling BasicAA from the AA results. This is particularly useful
60 /// when testing to isolate a single AA implementation.
61 static cl::opt<bool> DisableBasicAA("disable-basicaa", cl::Hidden,
62  cl::init(false));
63 
65  : TLI(Arg.TLI), AAs(std::move(Arg.AAs)), AADeps(std::move(Arg.AADeps)) {
66  for (auto &AA : AAs)
67  AA->setAAResults(this);
68 }
69 
71 // FIXME; It would be nice to at least clear out the pointers back to this
72 // aggregation here, but we end up with non-nesting lifetimes in the legacy
73 // pass manager that prevent this from working. In the legacy pass manager
74 // we'll end up with dangling references here in some cases.
75 #if 0
76  for (auto &AA : AAs)
77  AA->setAAResults(nullptr);
78 #endif
79 }
80 
83  // AAResults preserves the AAManager by default, due to the stateless nature
84  // of AliasAnalysis. There is no need to check whether it has been preserved
85  // explicitly. Check if any module dependency was invalidated and caused the
86  // AAManager to be invalidated. Invalidate ourselves in that case.
87  auto PAC = PA.getChecker<AAManager>();
88  if (!PAC.preservedWhenStateless())
89  return true;
90 
91  // Check if any of the function dependencies were invalidated, and invalidate
92  // ourselves in that case.
93  for (AnalysisKey *ID : AADeps)
94  if (Inv.invalidate(ID, F, PA))
95  return true;
96 
97  // Everything we depend on is still fine, so are we. Nothing to invalidate.
98  return false;
99 }
100 
101 //===----------------------------------------------------------------------===//
102 // Default chaining methods
103 //===----------------------------------------------------------------------===//
104 
106  const MemoryLocation &LocB) {
107  AAQueryInfo AAQIP;
108  return alias(LocA, LocB, AAQIP);
109 }
110 
112  const MemoryLocation &LocB, AAQueryInfo &AAQI) {
113  for (const auto &AA : AAs) {
114  auto Result = AA->alias(LocA, LocB, AAQI);
115  if (Result != MayAlias)
116  return Result;
117  }
118  return MayAlias;
119 }
120 
122  bool OrLocal) {
123  AAQueryInfo AAQIP;
124  return pointsToConstantMemory(Loc, AAQIP, OrLocal);
125 }
126 
128  AAQueryInfo &AAQI, bool OrLocal) {
129  for (const auto &AA : AAs)
130  if (AA->pointsToConstantMemory(Loc, AAQI, OrLocal))
131  return true;
132 
133  return false;
134 }
135 
136 ModRefInfo AAResults::getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
138 
139  for (const auto &AA : AAs) {
140  Result = intersectModRef(Result, AA->getArgModRefInfo(Call, ArgIdx));
141 
142  // Early-exit the moment we reach the bottom of the lattice.
143  if (isNoModRef(Result))
144  return ModRefInfo::NoModRef;
145  }
146 
147  return Result;
148 }
149 
151  AAQueryInfo AAQIP;
152  return getModRefInfo(I, Call2, AAQIP);
153 }
154 
156  AAQueryInfo &AAQI) {
157  // We may have two calls.
158  if (const auto *Call1 = dyn_cast<CallBase>(I)) {
159  // Check if the two calls modify the same memory.
160  return getModRefInfo(Call1, Call2, AAQI);
161  } else if (I->isFenceLike()) {
162  // If this is a fence, just return ModRef.
163  return ModRefInfo::ModRef;
164  } else {
165  // Otherwise, check if the call modifies or references the
166  // location this memory access defines. The best we can say
167  // is that if the call references what this instruction
168  // defines, it must be clobbered by this location.
169  const MemoryLocation DefLoc = MemoryLocation::get(I);
170  ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI);
171  if (isModOrRefSet(MR))
172  return setModAndRef(MR);
173  }
174  return ModRefInfo::NoModRef;
175 }
176 
178  const MemoryLocation &Loc) {
179  AAQueryInfo AAQIP;
180  return getModRefInfo(Call, Loc, AAQIP);
181 }
182 
184  const MemoryLocation &Loc,
185  AAQueryInfo &AAQI) {
187 
188  for (const auto &AA : AAs) {
189  Result = intersectModRef(Result, AA->getModRefInfo(Call, Loc, AAQI));
190 
191  // Early-exit the moment we reach the bottom of the lattice.
192  if (isNoModRef(Result))
193  return ModRefInfo::NoModRef;
194  }
195 
196  // Try to refine the mod-ref info further using other API entry points to the
197  // aggregate set of AA results.
198  auto MRB = getModRefBehavior(Call);
199  if (MRB == FMRB_DoesNotAccessMemory ||
201  return ModRefInfo::NoModRef;
202 
203  if (onlyReadsMemory(MRB))
204  Result = clearMod(Result);
205  else if (doesNotReadMemory(MRB))
206  Result = clearRef(Result);
207 
209  bool IsMustAlias = true;
210  ModRefInfo AllArgsMask = ModRefInfo::NoModRef;
211  if (doesAccessArgPointees(MRB)) {
212  for (auto AI = Call->arg_begin(), AE = Call->arg_end(); AI != AE; ++AI) {
213  const Value *Arg = *AI;
214  if (!Arg->getType()->isPointerTy())
215  continue;
216  unsigned ArgIdx = std::distance(Call->arg_begin(), AI);
217  MemoryLocation ArgLoc =
218  MemoryLocation::getForArgument(Call, ArgIdx, TLI);
219  AliasResult ArgAlias = alias(ArgLoc, Loc);
220  if (ArgAlias != NoAlias) {
221  ModRefInfo ArgMask = getArgModRefInfo(Call, ArgIdx);
222  AllArgsMask = unionModRef(AllArgsMask, ArgMask);
223  }
224  // Conservatively clear IsMustAlias unless only MustAlias is found.
225  IsMustAlias &= (ArgAlias == MustAlias);
226  }
227  }
228  // Return NoModRef if no alias found with any argument.
229  if (isNoModRef(AllArgsMask))
230  return ModRefInfo::NoModRef;
231  // Logical & between other AA analyses and argument analysis.
232  Result = intersectModRef(Result, AllArgsMask);
233  // If only MustAlias found above, set Must bit.
234  Result = IsMustAlias ? setMust(Result) : clearMust(Result);
235  }
236 
237  // If Loc is a constant memory location, the call definitely could not
238  // modify the memory location.
239  if (isModSet(Result) && pointsToConstantMemory(Loc, /*OrLocal*/ false))
240  Result = clearMod(Result);
241 
242  return Result;
243 }
244 
246  const CallBase *Call2) {
247  AAQueryInfo AAQIP;
248  return getModRefInfo(Call1, Call2, AAQIP);
249 }
250 
252  const CallBase *Call2, AAQueryInfo &AAQI) {
254 
255  for (const auto &AA : AAs) {
256  Result = intersectModRef(Result, AA->getModRefInfo(Call1, Call2, AAQI));
257 
258  // Early-exit the moment we reach the bottom of the lattice.
259  if (isNoModRef(Result))
260  return ModRefInfo::NoModRef;
261  }
262 
263  // Try to refine the mod-ref info further using other API entry points to the
264  // aggregate set of AA results.
265 
266  // If Call1 or Call2 are readnone, they don't interact.
267  auto Call1B = getModRefBehavior(Call1);
268  if (Call1B == FMRB_DoesNotAccessMemory)
269  return ModRefInfo::NoModRef;
270 
271  auto Call2B = getModRefBehavior(Call2);
272  if (Call2B == FMRB_DoesNotAccessMemory)
273  return ModRefInfo::NoModRef;
274 
275  // If they both only read from memory, there is no dependence.
276  if (onlyReadsMemory(Call1B) && onlyReadsMemory(Call2B))
277  return ModRefInfo::NoModRef;
278 
279  // If Call1 only reads memory, the only dependence on Call2 can be
280  // from Call1 reading memory written by Call2.
281  if (onlyReadsMemory(Call1B))
282  Result = clearMod(Result);
283  else if (doesNotReadMemory(Call1B))
284  Result = clearRef(Result);
285 
286  // If Call2 only access memory through arguments, accumulate the mod/ref
287  // information from Call1's references to the memory referenced by
288  // Call2's arguments.
289  if (onlyAccessesArgPointees(Call2B)) {
290  if (!doesAccessArgPointees(Call2B))
291  return ModRefInfo::NoModRef;
293  bool IsMustAlias = true;
294  for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) {
295  const Value *Arg = *I;
296  if (!Arg->getType()->isPointerTy())
297  continue;
298  unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I);
299  auto Call2ArgLoc =
300  MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI);
301 
302  // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the
303  // dependence of Call1 on that location is the inverse:
304  // - If Call2 modifies location, dependence exists if Call1 reads or
305  // writes.
306  // - If Call2 only reads location, dependence exists if Call1 writes.
307  ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx);
309  if (isModSet(ArgModRefC2))
310  ArgMask = ModRefInfo::ModRef;
311  else if (isRefSet(ArgModRefC2))
312  ArgMask = ModRefInfo::Mod;
313 
314  // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use
315  // above ArgMask to update dependence info.
316  ModRefInfo ModRefC1 = getModRefInfo(Call1, Call2ArgLoc);
317  ArgMask = intersectModRef(ArgMask, ModRefC1);
318 
319  // Conservatively clear IsMustAlias unless only MustAlias is found.
320  IsMustAlias &= isMustSet(ModRefC1);
321 
322  R = intersectModRef(unionModRef(R, ArgMask), Result);
323  if (R == Result) {
324  // On early exit, not all args were checked, cannot set Must.
325  if (I + 1 != E)
326  IsMustAlias = false;
327  break;
328  }
329  }
330 
331  if (isNoModRef(R))
332  return ModRefInfo::NoModRef;
333 
334  // If MustAlias found above, set Must bit.
335  return IsMustAlias ? setMust(R) : clearMust(R);
336  }
337 
338  // If Call1 only accesses memory through arguments, check if Call2 references
339  // any of the memory referenced by Call1's arguments. If not, return NoModRef.
340  if (onlyAccessesArgPointees(Call1B)) {
341  if (!doesAccessArgPointees(Call1B))
342  return ModRefInfo::NoModRef;
344  bool IsMustAlias = true;
345  for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) {
346  const Value *Arg = *I;
347  if (!Arg->getType()->isPointerTy())
348  continue;
349  unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I);
350  auto Call1ArgLoc =
351  MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI);
352 
353  // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1
354  // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by
355  // Call2. If Call1 might Ref, then we care only about a Mod by Call2.
356  ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx);
357  ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc);
358  if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) ||
359  (isRefSet(ArgModRefC1) && isModSet(ModRefC2)))
360  R = intersectModRef(unionModRef(R, ArgModRefC1), Result);
361 
362  // Conservatively clear IsMustAlias unless only MustAlias is found.
363  IsMustAlias &= isMustSet(ModRefC2);
364 
365  if (R == Result) {
366  // On early exit, not all args were checked, cannot set Must.
367  if (I + 1 != E)
368  IsMustAlias = false;
369  break;
370  }
371  }
372 
373  if (isNoModRef(R))
374  return ModRefInfo::NoModRef;
375 
376  // If MustAlias found above, set Must bit.
377  return IsMustAlias ? setMust(R) : clearMust(R);
378  }
379 
380  return Result;
381 }
382 
385 
386  for (const auto &AA : AAs) {
387  Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(Call));
388 
389  // Early-exit the moment we reach the bottom of the lattice.
390  if (Result == FMRB_DoesNotAccessMemory)
391  return Result;
392  }
393 
394  return Result;
395 }
396 
399 
400  for (const auto &AA : AAs) {
401  Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(F));
402 
403  // Early-exit the moment we reach the bottom of the lattice.
404  if (Result == FMRB_DoesNotAccessMemory)
405  return Result;
406  }
407 
408  return Result;
409 }
410 
412  switch (AR) {
413  case NoAlias:
414  OS << "NoAlias";
415  break;
416  case MustAlias:
417  OS << "MustAlias";
418  break;
419  case MayAlias:
420  OS << "MayAlias";
421  break;
422  case PartialAlias:
423  OS << "PartialAlias";
424  break;
425  }
426  return OS;
427 }
428 
429 //===----------------------------------------------------------------------===//
430 // Helper method implementation
431 //===----------------------------------------------------------------------===//
432 
434  const MemoryLocation &Loc) {
435  AAQueryInfo AAQIP;
436  return getModRefInfo(L, Loc, AAQIP);
437 }
439  const MemoryLocation &Loc,
440  AAQueryInfo &AAQI) {
441  // Be conservative in the face of atomic.
443  return ModRefInfo::ModRef;
444 
445  // If the load address doesn't alias the given address, it doesn't read
446  // or write the specified memory.
447  if (Loc.Ptr) {
448  AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI);
449  if (AR == NoAlias)
450  return ModRefInfo::NoModRef;
451  if (AR == MustAlias)
452  return ModRefInfo::MustRef;
453  }
454  // Otherwise, a load just reads.
455  return ModRefInfo::Ref;
456 }
457 
459  const MemoryLocation &Loc) {
460  AAQueryInfo AAQIP;
461  return getModRefInfo(S, Loc, AAQIP);
462 }
464  const MemoryLocation &Loc,
465  AAQueryInfo &AAQI) {
466  // Be conservative in the face of atomic.
468  return ModRefInfo::ModRef;
469 
470  if (Loc.Ptr) {
471  AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI);
472  // If the store address cannot alias the pointer in question, then the
473  // specified memory cannot be modified by the store.
474  if (AR == NoAlias)
475  return ModRefInfo::NoModRef;
476 
477  // If the pointer is a pointer to constant memory, then it could not have
478  // been modified by this store.
479  if (pointsToConstantMemory(Loc, AAQI))
480  return ModRefInfo::NoModRef;
481 
482  // If the store address aliases the pointer as must alias, set Must.
483  if (AR == MustAlias)
484  return ModRefInfo::MustMod;
485  }
486 
487  // Otherwise, a store just writes.
488  return ModRefInfo::Mod;
489 }
490 
492  AAQueryInfo AAQIP;
493  return getModRefInfo(S, Loc, AAQIP);
494 }
495 
497  const MemoryLocation &Loc,
498  AAQueryInfo &AAQI) {
499  // If we know that the location is a constant memory location, the fence
500  // cannot modify this location.
501  if (Loc.Ptr && pointsToConstantMemory(Loc, AAQI))
502  return ModRefInfo::Ref;
503  return ModRefInfo::ModRef;
504 }
505 
507  const MemoryLocation &Loc) {
508  AAQueryInfo AAQIP;
509  return getModRefInfo(V, Loc, AAQIP);
510 }
511 
513  const MemoryLocation &Loc,
514  AAQueryInfo &AAQI) {
515  if (Loc.Ptr) {
516  AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI);
517  // If the va_arg address cannot alias the pointer in question, then the
518  // specified memory cannot be accessed by the va_arg.
519  if (AR == NoAlias)
520  return ModRefInfo::NoModRef;
521 
522  // If the pointer is a pointer to constant memory, then it could not have
523  // been modified by this va_arg.
524  if (pointsToConstantMemory(Loc, AAQI))
525  return ModRefInfo::NoModRef;
526 
527  // If the va_arg aliases the pointer as must alias, set Must.
528  if (AR == MustAlias)
529  return ModRefInfo::MustModRef;
530  }
531 
532  // Otherwise, a va_arg reads and writes.
533  return ModRefInfo::ModRef;
534 }
535 
537  const MemoryLocation &Loc) {
538  AAQueryInfo AAQIP;
539  return getModRefInfo(CatchPad, Loc, AAQIP);
540 }
541 
543  const MemoryLocation &Loc,
544  AAQueryInfo &AAQI) {
545  if (Loc.Ptr) {
546  // If the pointer is a pointer to constant memory,
547  // then it could not have been modified by this catchpad.
548  if (pointsToConstantMemory(Loc, AAQI))
549  return ModRefInfo::NoModRef;
550  }
551 
552  // Otherwise, a catchpad reads and writes.
553  return ModRefInfo::ModRef;
554 }
555 
557  const MemoryLocation &Loc) {
558  AAQueryInfo AAQIP;
559  return getModRefInfo(CatchRet, Loc, AAQIP);
560 }
561 
563  const MemoryLocation &Loc,
564  AAQueryInfo &AAQI) {
565  if (Loc.Ptr) {
566  // If the pointer is a pointer to constant memory,
567  // then it could not have been modified by this catchpad.
568  if (pointsToConstantMemory(Loc, AAQI))
569  return ModRefInfo::NoModRef;
570  }
571 
572  // Otherwise, a catchret reads and writes.
573  return ModRefInfo::ModRef;
574 }
575 
577  const MemoryLocation &Loc) {
578  AAQueryInfo AAQIP;
579  return getModRefInfo(CX, Loc, AAQIP);
580 }
581 
583  const MemoryLocation &Loc,
584  AAQueryInfo &AAQI) {
585  // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
587  return ModRefInfo::ModRef;
588 
589  if (Loc.Ptr) {
590  AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI);
591  // If the cmpxchg address does not alias the location, it does not access
592  // it.
593  if (AR == NoAlias)
594  return ModRefInfo::NoModRef;
595 
596  // If the cmpxchg address aliases the pointer as must alias, set Must.
597  if (AR == MustAlias)
598  return ModRefInfo::MustModRef;
599  }
600 
601  return ModRefInfo::ModRef;
602 }
603 
605  const MemoryLocation &Loc) {
606  AAQueryInfo AAQIP;
607  return getModRefInfo(RMW, Loc, AAQIP);
608 }
609 
611  const MemoryLocation &Loc,
612  AAQueryInfo &AAQI) {
613  // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
615  return ModRefInfo::ModRef;
616 
617  if (Loc.Ptr) {
618  AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI);
619  // If the atomicrmw address does not alias the location, it does not access
620  // it.
621  if (AR == NoAlias)
622  return ModRefInfo::NoModRef;
623 
624  // If the atomicrmw address aliases the pointer as must alias, set Must.
625  if (AR == MustAlias)
626  return ModRefInfo::MustModRef;
627  }
628 
629  return ModRefInfo::ModRef;
630 }
631 
632 /// Return information about whether a particular call site modifies
633 /// or reads the specified memory location \p MemLoc before instruction \p I
634 /// in a BasicBlock. An ordered basic block \p OBB can be used to speed up
635 /// instruction-ordering queries inside the BasicBlock containing \p I.
636 /// FIXME: this is really just shoring-up a deficiency in alias analysis.
637 /// BasicAA isn't willing to spend linear time determining whether an alloca
638 /// was captured before or after this particular call, while we are. However,
639 /// with a smarter AA in place, this test is just wasting compile time.
641  const MemoryLocation &MemLoc,
642  DominatorTree *DT,
643  OrderedBasicBlock *OBB) {
644  if (!DT)
645  return ModRefInfo::ModRef;
646 
647  const Value *Object =
649  if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
650  isa<Constant>(Object))
651  return ModRefInfo::ModRef;
652 
653  const auto *Call = dyn_cast<CallBase>(I);
654  if (!Call || Call == Object)
655  return ModRefInfo::ModRef;
656 
657  if (PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
658  /* StoreCaptures */ true, I, DT,
659  /* include Object */ true,
660  /* OrderedBasicBlock */ OBB))
661  return ModRefInfo::ModRef;
662 
663  unsigned ArgNo = 0;
665  bool IsMustAlias = true;
666  // Set flag only if no May found and all operands processed.
667  for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
668  CI != CE; ++CI, ++ArgNo) {
669  // Only look at the no-capture or byval pointer arguments. If this
670  // pointer were passed to arguments that were neither of these, then it
671  // couldn't be no-capture.
672  if (!(*CI)->getType()->isPointerTy() ||
673  (!Call->doesNotCapture(ArgNo) && ArgNo < Call->getNumArgOperands() &&
674  !Call->isByValArgument(ArgNo)))
675  continue;
676 
677  AliasResult AR = alias(MemoryLocation(*CI), MemoryLocation(Object));
678  // If this is a no-capture pointer argument, see if we can tell that it
679  // is impossible to alias the pointer we're checking. If not, we have to
680  // assume that the call could touch the pointer, even though it doesn't
681  // escape.
682  if (AR != MustAlias)
683  IsMustAlias = false;
684  if (AR == NoAlias)
685  continue;
686  if (Call->doesNotAccessMemory(ArgNo))
687  continue;
688  if (Call->onlyReadsMemory(ArgNo)) {
689  R = ModRefInfo::Ref;
690  continue;
691  }
692  // Not returning MustModRef since we have not seen all the arguments.
693  return ModRefInfo::ModRef;
694  }
695  return IsMustAlias ? setMust(R) : clearMust(R);
696 }
697 
698 /// canBasicBlockModify - Return true if it is possible for execution of the
699 /// specified basic block to modify the location Loc.
700 ///
702  const MemoryLocation &Loc) {
703  return canInstructionRangeModRef(BB.front(), BB.back(), Loc, ModRefInfo::Mod);
704 }
705 
706 /// canInstructionRangeModRef - Return true if it is possible for the
707 /// execution of the specified instructions to mod\ref (according to the
708 /// mode) the location Loc. The instructions to consider are all
709 /// of the instructions in the range of [I1,I2] INCLUSIVE.
710 /// I1 and I2 must be in the same basic block.
712  const Instruction &I2,
713  const MemoryLocation &Loc,
714  const ModRefInfo Mode) {
715  assert(I1.getParent() == I2.getParent() &&
716  "Instructions not in same basic block!");
719  ++E; // Convert from inclusive to exclusive range.
720 
721  for (; I != E; ++I) // Check every instruction in range
722  if (isModOrRefSet(intersectModRef(getModRefInfo(&*I, Loc), Mode)))
723  return true;
724  return false;
725 }
726 
727 // Provide a definition for the root virtual destructor.
728 AAResults::Concept::~Concept() = default;
729 
730 // Provide a definition for the static object used to identify passes.
731 AnalysisKey AAManager::Key;
732 
733 namespace {
734 
735 
736 } // end anonymous namespace
737 
740 }
741 
743  : ImmutablePass(ID), CB(std::move(CB)) {
745 }
746 
748 
749 INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis",
750  false, true)
751 
754  return new ExternalAAWrapperPass(std::move(Callback));
755 }
756 
759 }
760 
761 char AAResultsWrapperPass::ID = 0;
762 
764  "Function Alias Analysis Results", false, true)
770 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
775  "Function Alias Analysis Results", false, true)
776 
778  return new AAResultsWrapperPass();
779 }
780 
781 /// Run the wrapper pass to rebuild an aggregation over known AA passes.
782 ///
783 /// This is the legacy pass manager's interface to the new-style AA results
784 /// aggregation object. Because this is somewhat shoe-horned into the legacy
785 /// pass manager, we hard code all the specific alias analyses available into
786 /// it. While the particular set enabled is configured via commandline flags,
787 /// adding a new alias analysis to LLVM will require adding support for it to
788 /// this list.
790  // NB! This *must* be reset before adding new AA results to the new
791  // AAResults object because in the legacy pass manager, each instance
792  // of these will refer to the *same* immutable analyses, registering and
793  // unregistering themselves with them. We need to carefully tear down the
794  // previous object first, in this case replacing it with an empty one, before
795  // registering new results.
796  AAR.reset(
797  new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F)));
798 
799  // BasicAA is always available for function analyses. Also, we add it first
800  // so that it can trump TBAA results when it proves MustAlias.
801  // FIXME: TBAA should have an explicit mode to support this and then we
802  // should reconsider the ordering here.
803  if (!DisableBasicAA)
804  AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult());
805 
806  // Populate the results with the currently available AAs.
807  if (auto *WrapperPass = getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>())
808  AAR->addAAResult(WrapperPass->getResult());
809  if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>())
810  AAR->addAAResult(WrapperPass->getResult());
811  if (auto *WrapperPass =
812  getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>())
813  AAR->addAAResult(WrapperPass->getResult());
814  if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>())
815  AAR->addAAResult(WrapperPass->getResult());
816  if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>())
817  AAR->addAAResult(WrapperPass->getResult());
818  if (auto *WrapperPass = getAnalysisIfAvailable<CFLAndersAAWrapperPass>())
819  AAR->addAAResult(WrapperPass->getResult());
820  if (auto *WrapperPass = getAnalysisIfAvailable<CFLSteensAAWrapperPass>())
821  AAR->addAAResult(WrapperPass->getResult());
822 
823  // If available, run an external AA providing callback over the results as
824  // well.
825  if (auto *WrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>())
826  if (WrapperPass->CB)
827  WrapperPass->CB(*this, F, *AAR);
828 
829  // Analyses don't mutate the IR, so return false.
830  return false;
831 }
832 
834  AU.setPreservesAll();
837 
838  // We also need to mark all the alias analysis passes we will potentially
839  // probe in runOnFunction as used here to ensure the legacy pass manager
840  // preserves them. This hard coding of lists of alias analyses is specific to
841  // the legacy pass manager.
850 }
851 
853  BasicAAResult &BAR) {
855 
856  // Add in our explicitly constructed BasicAA results.
857  if (!DisableBasicAA)
858  AAR.addAAResult(BAR);
859 
860  // Populate the results with the other currently available AAs.
861  if (auto *WrapperPass =
863  AAR.addAAResult(WrapperPass->getResult());
864  if (auto *WrapperPass = P.getAnalysisIfAvailable<TypeBasedAAWrapperPass>())
865  AAR.addAAResult(WrapperPass->getResult());
866  if (auto *WrapperPass =
868  AAR.addAAResult(WrapperPass->getResult());
869  if (auto *WrapperPass = P.getAnalysisIfAvailable<GlobalsAAWrapperPass>())
870  AAR.addAAResult(WrapperPass->getResult());
871  if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLAndersAAWrapperPass>())
872  AAR.addAAResult(WrapperPass->getResult());
873  if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLSteensAAWrapperPass>())
874  AAR.addAAResult(WrapperPass->getResult());
875  if (auto *WrapperPass = P.getAnalysisIfAvailable<ExternalAAWrapperPass>())
876  if (WrapperPass->CB)
877  WrapperPass->CB(P, F, AAR);
878 
879  return AAR;
880 }
881 
882 bool llvm::isNoAliasCall(const Value *V) {
883  if (const auto *Call = dyn_cast<CallBase>(V))
884  return Call->hasRetAttr(Attribute::NoAlias);
885  return false;
886 }
887 
889  if (const Argument *A = dyn_cast<Argument>(V))
890  return A->hasNoAliasAttr();
891  return false;
892 }
893 
895  if (isa<AllocaInst>(V))
896  return true;
897  if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
898  return true;
899  if (isNoAliasCall(V))
900  return true;
901  if (const Argument *A = dyn_cast<Argument>(V))
902  return A->hasNoAliasAttr() || A->hasByValAttr();
903  return false;
904 }
905 
907  return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
908 }
909 
911  // This function needs to be in sync with llvm::createLegacyPMAAResults -- if
912  // more alias analyses are added to llvm::createLegacyPMAAResults, they need
913  // to be added here also.
922 }
Legacy wrapper pass to provide the GlobalsAAResult object.
The access may reference and may modify the value stored in memory.
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:78
LLVM_NODISCARD ModRefInfo unionModRef(const ModRefInfo MRI1, const ModRefInfo MRI2)
User::op_iterator data_operands_end()
Definition: InstrTypes.h:1167
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:667
The access neither references nor modifies the value stored in memory.
LLVM_NODISCARD ModRefInfo clearMust(const ModRefInfo MRI)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
bool doesNotAccessMemory(unsigned OpNo) const
Definition: InstrTypes.h:1569
Atomic ordering constants.
SI Whole Quad Mode
bool isFenceLike() const
Return true if this instruction behaves like a memory fence: it can load or store to memory location ...
Definition: Instruction.h:561
This is the interface for LLVM&#39;s inclusion-based alias analysis implemented with CFL graph reachabili...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This is the interface for a simple mod/ref and alias analysis over globals.
An instruction for ordering other memory operations.
Definition: Instructions.h:471
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:547
std::function< void(Pass &, Function &, AAResults &)> CallbackT
This class stores info we want to provide to or retain within an alias query.
This is the interface for a metadata-based scoped no-alias analysis.
The two locations do not alias at all.
Definition: AliasAnalysis.h:84
INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis", false, true) ImmutablePass *llvm
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Definition: Instructions.h:258
Function Alias Analysis Results
This is the AA result object for the basic, local, and stateless alias analysis.
static bool onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB)
Checks if functions with the specified behavior are known to read and write at most from memory that ...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1105
F(f)
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Definition: InstrTypes.h:1217
bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
block Block Frequency true
An instruction for reading from memory.
Definition: Instructions.h:169
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:710
User::op_iterator data_operands_begin()
data_operands_begin/data_operands_end - Return iterators iterating over the call / invoke argument li...
Definition: InstrTypes.h:1163
void initializeExternalAAWrapperPassPass(PassRegistry &)
This indicates that the function could not be classified into one of the behaviors above...
Legacy wrapper pass to provide the TypeBasedAAResult object.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: PassManager.h:312
LLVM_NODISCARD ModRefInfo clearMod(const ModRefInfo MRI)
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
bool doesNotCapture(unsigned OpNo) const
Determine whether this data operand is not captured.
Definition: InstrTypes.h:1541
AnalysisUsage & addRequired()
The only memory references in this function (if it has any) are references of memory that is otherwis...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
Definition: BitVector.h:937
This is the interface for a SCEV-based alias analysis.
FunctionPass * createAAResultsWrapperPass()
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
static bool doesNotReadMemory(FunctionModRefBehavior MRB)
Checks if functions with the specified behavior are known to only write memory (or not access memory ...
bool isStrongerThan(AtomicOrdering ao, AtomicOrdering other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice, which is based on C++&#39;s definition.
LLVM_NODISCARD ModRefInfo clearRef(const ModRefInfo MRI)
The access may reference the value stored in memory, a mustAlias relation was found, and no mayAlias or partialAlias found.
The access may reference the value stored in memory.
This file contains the simple types necessary to represent the attributes associated with functions a...
static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR)
A helper for the legacy pass manager to create a AAResults object populated to the best of our abilit...
bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
void initializeAAResultsWrapperPassPass(PassRegistry &)
FunctionModRefBehavior getModRefBehavior(const CallBase *Call)
Return the behavior of the given call site.
LLVM_NODISCARD bool isMustSet(const ModRefInfo MRI)
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
Definition: Instructions.h:601
The access may reference, modify or both the value stored in memory, a mustAlias relation was found...
FunctionModRefBehavior
Summary of how a function affects memory in the program.
The access may modify the value stored in memory, a mustAlias relation was found, and no mayAlias or ...
bool runOnFunction(Function &F) override
Run the wrapper pass to rebuild an aggregation over known AA passes.
Legacy wrapper pass to provide the CFLSteensAAResult object.
An instruction for storing to memory.
Definition: Instructions.h:331
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, bool StoreCaptures, const Instruction *I, const DominatorTree *DT, bool IncludeI=false, OrderedBasicBlock *OBB=nullptr, unsigned MaxUsesToExplore=DefaultMaxUsesToExplore)
PointerMayBeCapturedBefore - Return true if this pointer value may be captured by the enclosing funct...
static cl::opt< bool > DisableBasicAA("disable-basicaa", cl::Hidden, cl::init(false))
Allow disabling BasicAA from the AA results.
bool isStrongerThanMonotonic(AtomicOrdering ao)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
AliasResult
The possible results of an alias query.
Definition: AliasAnalysis.h:78
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
Checks whether the given location points to constant memory, or if OrLocal is true whether it points ...
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...
Legacy wrapper pass to provide the ScopedNoAliasAAResult object.
#define P(N)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
This is the interface for LLVM&#39;s unification-based alias analysis implemented with CFL graph reachabi...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
LLVM_NODISCARD ModRefInfo setMust(const ModRefInfo MRI)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
This is the interface for a metadata-based TBAA.
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
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)...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
const Instruction & front() const
Definition: BasicBlock.h:285
A manager for alias analyses.
Legacy wrapper pass to provide the CFLAndersAAResult object.
Represent the analysis usage information of a pass.
const Instruction & back() const
Definition: BasicBlock.h:287
static bool doesAccessArgPointees(FunctionModRefBehavior MRB)
Checks if functions with the specified behavior are known to potentially read or write from objects p...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:282
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
TargetLibraryInfo & getTLI(const Function &F)
self_iterator getIterator()
Definition: ilist_node.h:81
bool onlyReadsMemory(const CallBase *Call)
Checks if the specified call is known to only read from non-volatile memory (or not access memory at ...
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
Definition: Instructions.h:808
void getAAResultsAnalysisUsage(AnalysisUsage &AU)
A helper for the legacy pass manager to populate AU to add uses to make sure the analyses required by...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This file declares a simple ARC-aware AliasAnalysis using special knowledge of Objective C to enhance...
This function does not perform any non-local loads or stores to memory.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
Definition: InstrTypes.h:1546
bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
The two locations may or may not alias. This is the least precise result.
Definition: AliasAnalysis.h:86
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
The two locations precisely alias each other.
Definition: AliasAnalysis.h:90
Iterator for intrusive lists based on ilist_node.
INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa", "Function Alias Analysis Results", false, true) INITIALIZE_PASS_END(AAResultsWrapperPass
Legacy wrapper pass to provide the SCEVAAResult object.
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:253
Module.h This file contains the declarations for the Module class.
The access may modify the value stored in memory.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
ModRefInfo callCapturesBefore(const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT, OrderedBasicBlock *OBB=nullptr)
Return information about whether a particular call site modifies or reads the specified memory locati...
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM_NODISCARD bool isNoModRef(const ModRefInfo MRI)
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Definition: InstrTypes.h:1211
AAResults(const TargetLibraryInfo &TLI)
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB)
Checks if functions with the specified behavior are known to read and write at most from objects poin...
unsigned getNumArgOperands() const
Definition: InstrTypes.h:1244
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Definition: Instructions.h:389
This file provides utility analysis objects describing memory locations.
LLVM_NODISCARD ModRefInfo intersectModRef(const ModRefInfo MRI1, const ModRefInfo MRI2)
bool onlyReadsMemory(unsigned OpNo) const
Definition: InstrTypes.h:1575
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2096
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:649
ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx)
Get the ModRef info associated with a pointer argument of a call.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
LLVM Value Representation.
Definition: Value.h:74
Legacy wrapper pass to provide the ObjCARCAAResult object.
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
A wrapper pass for external alias analyses.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
LLVM_NODISCARD ModRefInfo setModAndRef(const ModRefInfo MRI)
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
bool isNoAliasArgument(const Value *V)
Return true if this is an argument with the noalias attribute.
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
The two locations alias, but only due to a partial overlap.
Definition: AliasAnalysis.h:88
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...
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:71
const BasicBlock * getParent() const
Definition: Instruction.h:66
Legacy wrapper pass to provide the BasicAAResult object.
LLVM_NODISCARD bool isRefSet(const ModRefInfo MRI)