1 //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the generic AliasAnalysis interface which is used as the
11 // common interface used by all clients and implementations of alias analysis.
13 // This file also implements the default version of the AliasAnalysis interface
14 // that is to be used when no other implementation is specified. This does some
15 // simple tests that detect obvious cases: two different global pointers cannot
16 // alias, a global cannot alias a malloc, two different mallocs cannot alias,
19 // This alias analysis implementation really isn't very good for anything, but
20 // it is very fast, and makes a nice clean default implementation. Because it
21 // handles lots of little corner cases, other, more complex, alias analysis
22 // implementations may choose to rely on this pass to resolve these simple and
25 //===----------------------------------------------------------------------===//
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/Pass.h"
43 // Register the AliasAnalysis interface, providing a nice name to refer to.
44 INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
45 char AliasAnalysis::ID = 0;
47 //===----------------------------------------------------------------------===//
48 // Default chaining methods
49 //===----------------------------------------------------------------------===//
51 AliasResult AliasAnalysis::alias(const MemoryLocation &LocA,
52 const MemoryLocation &LocB) {
53 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
54 return AA->alias(LocA, LocB);
57 bool AliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
59 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
60 return AA->pointsToConstantMemory(Loc, OrLocal);
63 AliasAnalysis::ModRefResult
64 AliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
65 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
66 return AA->getArgModRefInfo(CS, ArgIdx);
69 AliasAnalysis::ModRefResult
70 AliasAnalysis::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
71 // We may have two calls
72 if (auto CS = ImmutableCallSite(I)) {
73 // Check if the two calls modify the same memory
74 return getModRefInfo(Call, CS);
76 // Otherwise, check if the call modifies or references the
77 // location this memory access defines. The best we can say
78 // is that if the call references what this instruction
79 // defines, it must be clobbered by this location.
80 const MemoryLocation DefLoc = MemoryLocation::get(I);
81 if (getModRefInfo(Call, DefLoc) != AliasAnalysis::NoModRef)
82 return AliasAnalysis::ModRef;
84 return AliasAnalysis::NoModRef;
87 AliasAnalysis::ModRefResult
88 AliasAnalysis::getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
89 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
91 ModRefBehavior MRB = getModRefBehavior(CS);
92 if (MRB == DoesNotAccessMemory)
95 ModRefResult Mask = ModRef;
96 if (onlyReadsMemory(MRB))
99 if (onlyAccessesArgPointees(MRB)) {
100 bool doesAlias = false;
101 ModRefResult AllArgsMask = NoModRef;
102 if (doesAccessArgPointees(MRB)) {
103 for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
105 const Value *Arg = *AI;
106 if (!Arg->getType()->isPointerTy())
108 unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
109 MemoryLocation ArgLoc =
110 MemoryLocation::getForArgument(CS, ArgIdx, *TLI);
111 if (!isNoAlias(ArgLoc, Loc)) {
112 ModRefResult ArgMask = getArgModRefInfo(CS, ArgIdx);
114 AllArgsMask = ModRefResult(AllArgsMask | ArgMask);
120 Mask = ModRefResult(Mask & AllArgsMask);
123 // If Loc is a constant memory location, the call definitely could not
124 // modify the memory location.
125 if ((Mask & Mod) && pointsToConstantMemory(Loc))
126 Mask = ModRefResult(Mask & ~Mod);
128 // If this is the end of the chain, don't forward.
129 if (!AA) return Mask;
131 // Otherwise, fall back to the next AA in the chain. But we can merge
132 // in any mask we've managed to compute.
133 return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
136 AliasAnalysis::ModRefResult
137 AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
138 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
140 // If CS1 or CS2 are readnone, they don't interact.
141 ModRefBehavior CS1B = getModRefBehavior(CS1);
142 if (CS1B == DoesNotAccessMemory) return NoModRef;
144 ModRefBehavior CS2B = getModRefBehavior(CS2);
145 if (CS2B == DoesNotAccessMemory) return NoModRef;
147 // If they both only read from memory, there is no dependence.
148 if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
151 AliasAnalysis::ModRefResult Mask = ModRef;
153 // If CS1 only reads memory, the only dependence on CS2 can be
154 // from CS1 reading memory written by CS2.
155 if (onlyReadsMemory(CS1B))
156 Mask = ModRefResult(Mask & Ref);
158 // If CS2 only access memory through arguments, accumulate the mod/ref
159 // information from CS1's references to the memory referenced by
161 if (onlyAccessesArgPointees(CS2B)) {
162 AliasAnalysis::ModRefResult R = NoModRef;
163 if (doesAccessArgPointees(CS2B)) {
164 for (ImmutableCallSite::arg_iterator
165 I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
166 const Value *Arg = *I;
167 if (!Arg->getType()->isPointerTy())
169 unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
170 auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, *TLI);
172 // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence of
173 // CS1 on that location is the inverse.
174 ModRefResult ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
177 else if (ArgMask == Ref)
180 R = ModRefResult((R | (getModRefInfo(CS1, CS2ArgLoc) & ArgMask)) & Mask);
188 // If CS1 only accesses memory through arguments, check if CS2 references
189 // any of the memory referenced by CS1's arguments. If not, return NoModRef.
190 if (onlyAccessesArgPointees(CS1B)) {
191 AliasAnalysis::ModRefResult R = NoModRef;
192 if (doesAccessArgPointees(CS1B)) {
193 for (ImmutableCallSite::arg_iterator
194 I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
195 const Value *Arg = *I;
196 if (!Arg->getType()->isPointerTy())
198 unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
199 auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, *TLI);
201 // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
202 // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
203 // might Ref, then we care only about a Mod by CS2.
204 ModRefResult ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
205 ModRefResult ArgR = getModRefInfo(CS2, CS1ArgLoc);
206 if (((ArgMask & Mod) != NoModRef && (ArgR & ModRef) != NoModRef) ||
207 ((ArgMask & Ref) != NoModRef && (ArgR & Mod) != NoModRef))
208 R = ModRefResult((R | ArgMask) & Mask);
217 // If this is the end of the chain, don't forward.
218 if (!AA) return Mask;
220 // Otherwise, fall back to the next AA in the chain. But we can merge
221 // in any mask we've managed to compute.
222 return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
225 AliasAnalysis::ModRefBehavior
226 AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
227 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
229 ModRefBehavior Min = UnknownModRefBehavior;
231 // Call back into the alias analysis with the other form of getModRefBehavior
232 // to see if it can give a better response.
233 if (const Function *F = CS.getCalledFunction())
234 Min = getModRefBehavior(F);
236 // If this is the end of the chain, don't forward.
239 // Otherwise, fall back to the next AA in the chain. But we can merge
240 // in any result we've managed to compute.
241 return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
244 AliasAnalysis::ModRefBehavior
245 AliasAnalysis::getModRefBehavior(const Function *F) {
246 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
247 return AA->getModRefBehavior(F);
250 //===----------------------------------------------------------------------===//
251 // AliasAnalysis non-virtual helper method implementation
252 //===----------------------------------------------------------------------===//
254 AliasAnalysis::ModRefResult
255 AliasAnalysis::getModRefInfo(const LoadInst *L, const MemoryLocation &Loc) {
256 // Be conservative in the face of volatile/atomic.
257 if (!L->isUnordered())
260 // If the load address doesn't alias the given address, it doesn't read
261 // or write the specified memory.
262 if (Loc.Ptr && !alias(MemoryLocation::get(L), Loc))
265 // Otherwise, a load just reads.
269 AliasAnalysis::ModRefResult
270 AliasAnalysis::getModRefInfo(const StoreInst *S, const MemoryLocation &Loc) {
271 // Be conservative in the face of volatile/atomic.
272 if (!S->isUnordered())
276 // If the store address cannot alias the pointer in question, then the
277 // specified memory cannot be modified by the store.
278 if (!alias(MemoryLocation::get(S), Loc))
281 // If the pointer is a pointer to constant memory, then it could not have
282 // been modified by this store.
283 if (pointsToConstantMemory(Loc))
288 // Otherwise, a store just writes.
292 AliasAnalysis::ModRefResult
293 AliasAnalysis::getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc) {
296 // If the va_arg address cannot alias the pointer in question, then the
297 // specified memory cannot be accessed by the va_arg.
298 if (!alias(MemoryLocation::get(V), Loc))
301 // If the pointer is a pointer to constant memory, then it could not have
302 // been modified by this va_arg.
303 if (pointsToConstantMemory(Loc))
307 // Otherwise, a va_arg reads and writes.
311 AliasAnalysis::ModRefResult
312 AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX,
313 const MemoryLocation &Loc) {
314 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
315 if (CX->getSuccessOrdering() > Monotonic)
318 // If the cmpxchg address does not alias the location, it does not access it.
319 if (Loc.Ptr && !alias(MemoryLocation::get(CX), Loc))
325 AliasAnalysis::ModRefResult
326 AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW,
327 const MemoryLocation &Loc) {
328 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
329 if (RMW->getOrdering() > Monotonic)
332 // If the atomicrmw address does not alias the location, it does not access it.
333 if (Loc.Ptr && !alias(MemoryLocation::get(RMW), Loc))
339 // FIXME: this is really just shoring-up a deficiency in alias analysis.
340 // BasicAA isn't willing to spend linear time determining whether an alloca
341 // was captured before or after this particular call, while we are. However,
342 // with a smarter AA in place, this test is just wasting compile time.
343 AliasAnalysis::ModRefResult AliasAnalysis::callCapturesBefore(
344 const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT) {
346 return AliasAnalysis::ModRef;
348 const Value *Object = GetUnderlyingObject(MemLoc.Ptr, *DL);
349 if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
350 isa<Constant>(Object))
351 return AliasAnalysis::ModRef;
353 ImmutableCallSite CS(I);
354 if (!CS.getInstruction() || CS.getInstruction() == Object)
355 return AliasAnalysis::ModRef;
357 if (llvm::PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
358 /* StoreCaptures */ true, I, DT,
359 /* include Object */ true))
360 return AliasAnalysis::ModRef;
363 AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
364 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
365 CI != CE; ++CI, ++ArgNo) {
366 // Only look at the no-capture or byval pointer arguments. If this
367 // pointer were passed to arguments that were neither of these, then it
368 // couldn't be no-capture.
369 if (!(*CI)->getType()->isPointerTy() ||
370 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
373 // If this is a no-capture pointer argument, see if we can tell that it
374 // is impossible to alias the pointer we're checking. If not, we have to
375 // assume that the call could touch the pointer, even though it doesn't
377 if (isNoAlias(MemoryLocation(*CI), MemoryLocation(Object)))
379 if (CS.doesNotAccessMemory(ArgNo))
381 if (CS.onlyReadsMemory(ArgNo)) {
382 R = AliasAnalysis::Ref;
385 return AliasAnalysis::ModRef;
390 // AliasAnalysis destructor: DO NOT move this to the header file for
391 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
392 // the AliasAnalysis.o file in the current .a file, causing alias analysis
393 // support to not be included in the tool correctly!
395 AliasAnalysis::~AliasAnalysis() {}
397 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
398 /// AliasAnalysis interface before any other methods are called.
400 void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
402 auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
403 TLI = TLIP ? &TLIP->getTLI() : nullptr;
404 AA = &P->getAnalysis<AliasAnalysis>();
407 // getAnalysisUsage - All alias analysis implementations should invoke this
408 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
409 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
410 AU.addRequired<AliasAnalysis>(); // All AA's chain
413 /// getTypeStoreSize - Return the DataLayout store size for the given type,
414 /// if known, or a conservative value otherwise.
416 uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
417 return DL ? DL->getTypeStoreSize(Ty) : MemoryLocation::UnknownSize;
420 /// canBasicBlockModify - Return true if it is possible for execution of the
421 /// specified basic block to modify the location Loc.
423 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
424 const MemoryLocation &Loc) {
425 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, Mod);
428 /// canInstructionRangeModRef - Return true if it is possible for the
429 /// execution of the specified instructions to mod\ref (according to the
430 /// mode) the location Loc. The instructions to consider are all
431 /// of the instructions in the range of [I1,I2] INCLUSIVE.
432 /// I1 and I2 must be in the same basic block.
433 bool AliasAnalysis::canInstructionRangeModRef(const Instruction &I1,
434 const Instruction &I2,
435 const MemoryLocation &Loc,
436 const ModRefResult Mode) {
437 assert(I1.getParent() == I2.getParent() &&
438 "Instructions not in same basic block!");
439 BasicBlock::const_iterator I = &I1;
440 BasicBlock::const_iterator E = &I2;
441 ++E; // Convert from inclusive to exclusive range.
443 for (; I != E; ++I) // Check every instruction in range
444 if (getModRefInfo(I, Loc) & Mode)
449 /// isNoAliasCall - Return true if this pointer is returned by a noalias
451 bool llvm::isNoAliasCall(const Value *V) {
452 if (isa<CallInst>(V) || isa<InvokeInst>(V))
453 return ImmutableCallSite(cast<Instruction>(V))
454 .paramHasAttr(0, Attribute::NoAlias);
458 /// isNoAliasArgument - Return true if this is an argument with the noalias
460 bool llvm::isNoAliasArgument(const Value *V)
462 if (const Argument *A = dyn_cast<Argument>(V))
463 return A->hasNoAliasAttr();
467 /// isIdentifiedObject - Return true if this pointer refers to a distinct and
468 /// identifiable object. This returns true for:
469 /// Global Variables and Functions (but not Global Aliases)
470 /// Allocas and Mallocs
471 /// ByVal and NoAlias Arguments
474 bool llvm::isIdentifiedObject(const Value *V) {
475 if (isa<AllocaInst>(V))
477 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
479 if (isNoAliasCall(V))
481 if (const Argument *A = dyn_cast<Argument>(V))
482 return A->hasNoAliasAttr() || A->hasByValAttr();
486 /// isIdentifiedFunctionLocal - Return true if V is umabigously identified
487 /// at the function-level. Different IdentifiedFunctionLocals can't alias.
488 /// Further, an IdentifiedFunctionLocal can not alias with any function
489 /// arguments other than itself, which is not necessarily true for
490 /// IdentifiedObjects.
491 bool llvm::isIdentifiedFunctionLocal(const Value *V)
493 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);